Andreas Hunter
Andreas Hunter

Reputation: 5014

Ngnix laravel docker project return error 502 bad gateway

I tried run laravel inside docker container with ngnix.

Directory structure:

enter image description here

File docker-compose.yml:

version: '3'
services:
    nginx:
      image: nginx:stable-alpine
      container_name: nginx
      ports:
        - "${HOST_PORT}:80"
      volumes:
        - ../:/var/www/html
        - ./etc/nginx/default.conf:/etc/nginx/conf.d/default.conf
      depends_on:
        - php
    php:
        build:
          context: .
          dockerfile: ../Dockerfile
        restart: always
        container_name: php
        volumes:
            - "../:/var/www/html"
        ports:
          - "9000:9000"
    mongodb:
        image: mongo:latest
        container_name: mongodb
        ports:
            - "27017:27017"
    redis:
        image: redis:latest
        container_name: redis
        restart: always
        ports:
            - "6379:6379"

File Dockerfile:

FROM php:7.4-apache

RUN apt-get update && apt-get install --yes --no-install-recommends \
    libssl-dev

RUN docker-php-ext-install pdo pdo_mysql

RUN pecl install mongodb \
    && docker-php-ext-enable mongodb

Result of command docker ps:

enter image description here

When I tried open in browser address http://localhost:8004 then get error:

502 Bad Gateway nginx/1.18.0

Ngnix config file:

server {
    listen 80;
    index index.php index.html;
    server_name localhost;
    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/html/public;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

Env vars:

HOST_PORT=8004
HOST_SSL_PORT=3004

# Nginx
NGINX_HOST=localhost

Upvotes: 3

Views: 9163

Answers (1)

Yerke
Yerke

Reputation: 2215

As you're using nginx as your web-server, you don't need to install PHP Apache (FROM php:7.4-apache) in your Dockerfile.

Instead try php:7.4-fpm and make sure nginx accesses that php-fpm correctly (line fastcgi_pass php:9000; in your default.conf file. In your case everything seems configured correctly).

One more thing to note that it's not necessary to expose php-fpm port 9000 to the host machine. As both containers (in your docker-compose.yml) will use the same network, nginx container can directly access php container. You can remove the lines

ports:
 - "9000:9000"

Upvotes: 7

Related Questions