Ngnix Laravel Docker项目返回错误502错误的网关

时间:2020-07-23 06:09:29

标签: laravel docker nginx docker-compose nginx-config

我尝试使用ngnix在docker容器中运行laravel。

目录结构:

enter image description here

文件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"

文件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

命令docker ps的结果:

enter image description here

当我尝试在浏览器地址http://localhost:8004中打开时,收到错误消息:

502 Bad Gateway nginx / 1.18.0

Ngnix配置文件

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;
    }
}

环境变量:

HOST_PORT=8004
HOST_SSL_PORT=3004

# Nginx
NGINX_HOST=localhost

1 个答案:

答案 0 :(得分:2)

当您使用nginx作为Web服务器时,不需要在FROM php:7.4-apache中安装PHP Apache(Dockerfile)。

相反,请尝试php:7.4-fpm并确保nginx正确访问该php-fpm(在fastcgi_pass php:9000;文件中的第default.conf行。在您看来,所有配置似乎都正确)。

需要注意的另一件事是,不必向主机公开php-fpm端口9000。由于两个容器(在您的docker-compose.yml中)将使用同一网络,因此nginx容器可以直接访问php容器。您可以删除行

ports:
 - "9000:9000"