单docker-compose部署Slim4前后端,后端API无法访问求助
问题分析与解决方案
从错误信息和配置来看,核心问题在于Nginx对后端API的请求处理方式错误,以及容器间通信和PHP-FPM监听配置存在问题,以下是具体修正步骤:
1. 修正PHP-FPM监听配置(前后端均需修改)
打开backend/docker/php/php-fpm.conf和frontend/docker/php/php-fpm.conf,将监听地址从本地回环改为容器内所有接口:
[www] user = www-data group = www-data # 原配置:listen = 127.0.0.1:9000 listen = 0.0.0.0:9000 # 修改为监听所有接口,允许容器间通信 pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3
2. 修正Nginx配置(关键)
Nginx对/api/v1的请求错误使用了proxy_pass(HTTP协议),但后端是PHP-FPM(FastCGI协议),需改为fastcgi_pass,同时调整路径映射:
events { worker_connections 1024; } http { upstream backend { server backend:9000; # 使用容器内部端口9000,而非宿主机映射的9001 } upstream frontend { server frontend:9000; } server { listen 80 default_server; listen [::]:80 default_server; server_name _; server_tokens off; root /frontend/web; index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } # 修正后端API请求处理 location /api/v1 { root /backend/web; # 指定后端项目的web根目录 try_files $uri $uri/ /index.php?$query_string; # 适配Slim路由规则 include fastcgi_params; fastcgi_pass backend; # 使用FastCGI协议连接后端PHP-FPM fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; # 必须配置,Slim依赖此参数解析路由 } location ~ \.php$ { include fastcgi_params; fastcgi_pass frontend; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; } } # (可选)若无需直接通过backend域名访问后端,可删除此server块 server { listen 80; server_name backend; root /backend/web; index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include fastcgi_params; fastcgi_pass backend; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; } } }
3. (可选)优化docker-compose.yml端口映射
容器间通信无需暴露后端端口到宿主机,可删除backend服务的ports配置:
version: '3.9' services: backend: container_name: backend build: context: ./backend dockerfile: ./docker/php/Dockerfile # 移除此行:ports: - 9001:9000 volumes: - ./backend:/backend frontend: container_name: frontend build: context: ./frontend dockerfile: ./docker/php/Dockerfile ports: - 9000:9000 volumes: - ./frontend:/frontend nginx: image: nginx container_name: nginx volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf ports: - 80:80 depends_on: - backend - frontend
4. 重启容器生效
执行以下命令重建并启动容器:
docker-compose down docker-compose up --build
核心原因说明
- 协议不匹配:PHP-FPM使用FastCGI协议,而非HTTP协议,因此不能用
proxy_pass,必须用fastcgi_pass处理请求。 - 容器通信端口错误:容器间通信需使用容器内部端口(9000),而非宿主机的映射端口(9001)。
- PHP-FPM监听限制:默认监听
127.0.0.1会导致容器外的Nginx无法访问,需改为0.0.0.0允许跨容器通信。 - Slim路由依赖:必须配置
PATH_INFO参数,否则Slim无法正确解析API路由。
内容的提问来源于stack exchange,提问作者user629283
相关产品推荐
相关产品推荐

