Docker化Laravel 7应用无法显示首页,Nginx返回502错误
Docker部署Laravel应用遭遇Nginx 502 Bad Gateway错误
问题现象
- 按教程搭建MySQL、Nginx、PHP容器后,
src/public/index.html可正常加载显示 - 清空src目录并创建Laravel应用后,访问返回502 Bad Gateway错误
- Nginx容器内
/var/log/nginx目录下的日志文件存在但无内容,容器日志显示连接PHP服务被拒绝
相关配置文件
default.conf
server { listen 81; 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$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass php:9001; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; } }
docker-compose.yml
version: '3' networks: laravel: services: nginx: image: nginx:stable-alpine container_name: nginx-laravel ports: - "8088:81" volumes: - ./src:/var/www/html - ./nginx/default.conf:/etc/nginx/conf.d/default.conf depends_on: - php - mysql networks: - laravel mysql: platform: linux/x86_64 image: mysql:5.7.34 container_name: mysql-laravel restart: unless-stopped tty: true ports: - "4306:3306" volumes: - ./mysql:/var/lib/mysql environment: MYSQL_DATABASE: homestead MYSQL_USER: homestead MYSQL_PASSWORD: secret MYSQL_ROOT_PASSWORD: secret SERVICE_TAGS: dev SERVICE_NAME: mysql networks: - laravel php: build: context: . dockerfile: Dockerfile container_name: php-laravel volumes: - ./src:/var/www/html ports: - "9001:9001" networks: - laravel
Dockerfile
FROM php:7.2-fpm-alpine RUN docker-php-ext-install pdo pdo_mysql
Nginx容器关键日志
2022-08-25T23:53:58.719467761Z 2022/08/25 23:53:58 [error] 35#35: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.20.0.2:9001", host: "localhost:8088"
错误原因
官方php:7.2-fpm-alpine镜像默认监听9000端口,但配置中Nginx尝试连接PHP容器的9001端口,同时Docker Compose将主机9001端口映射到容器9001端口,而PHP-FPM实际未在9001端口提供服务,导致连接被拒绝,触发502错误。
解决方案
方案1:修改Nginx配置,指向PHP默认端口
修改default.conf中的fastcgi_pass端口为9000:
location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass php:9000; # 替换为9000 fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; }
方案2:修改PHP容器,让FPM监听9001端口
若需保留9001端口,修改Dockerfile添加FPM端口配置:
FROM php:7.2-fpm-alpine RUN docker-php-ext-install pdo pdo_mysql # 添加以下行,修改FPM监听端口为9001 RUN echo "listen = 9001" >> /usr/local/etc/php-fpm.d/www.conf
重启容器并修复Laravel权限
修改完成后,重新构建启动容器:
docker-compose down docker-compose build php docker-compose up -d
进入PHP容器,修复Laravel目录权限:
docker exec -it php-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache docker exec -it php-laravel chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache
内容的提问来源于stack exchange,提问作者Geeda
相关产品推荐
相关产品推荐

