You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker Compose中Nginx搭配php-fpm时,为何容器命名为app才正常?

问题:修改PHP-FPM服务名称后Nginx返回空响应

正常运行的Docker Compose配置

version: '3'

services:
    app:
        image: php:8.2-fpm
        working_dir: "/var/www"
        volumes:
            - ./src:/var/www/html   
        networks:
            - internal
    nginx:
        restart: always
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - ./nginx:/etc/nginx/conf.d
            - ./src:/var/www/html
        depends_on:
            - app
        networks:
            - internal

networks:
    internal:
        name: internal

正常运行结果

$ docker-compose up -d        
[+] Running 3/3
 ✔ Network internal          Created 0.1s 
 ✔ Container my-php-app-1    Started 0.5s 
 ✔ Container my-php-nginx-1  Started
   
$ curl "http://localhost:8080"
{"message": "Hello World!"}

修改后的Docker Compose配置(出现问题)

将PHP-FPM服务名称从app改为apiapp后:

services:
    apiapp:
        image: php:8.2-fpm
        working_dir: "/var/www"
        volumes:
            - ./src:/var/www/html   
        networks:
            - internal
    nginx:
        restart: always
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - ./nginx:/etc/nginx/conf.d
            - ./src:/var/www/html
        depends_on:
            - apiapp
        networks:
            - internal

networks:
    internal:
        name: internal

修改后的运行结果(错误)

$ docker-compose up -d
[+] Running 3/3
 ✔ Network internal           Created 0.0s 
 ✔ Container my-php-apiapp-1  Started 0.5s 
 ✔ Container my-php-nginx-1   Started 0.9s 
$ curl "http://localhost:8080"
curl: (52) Empty reply from server

已确认旧服务已完全移除,新旧容器无关联,但修改服务名称后服务无法正常运行。

我的Nginx配置

server {
    listen 80;
    root /var/www/html;
    index index.php;

    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
            return 404;
        }
        fastcgi_param HTTP_PROXY "";
        fastcgi_pass app:9000; 
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location / {
        root /var/www/html;
        index index.php;
        try_files $uri $uri/ $uri.php /index.php?$query_string =404;
    }
}

问题原因及解决方案

问题出在Nginx配置的fastcgi_pass app:9000;这一行:
Docker Compose中,服务名称会作为容器在内部网络中的主机名。当你把PHP-FPM服务名称从app改成apiapp后,Nginx仍然尝试通过旧的主机名app访问PHP-FPM容器,导致连接失败,返回空响应。

只需将Nginx配置中的fastcgi_pass app:9000;修改为fastcgi_pass apiapp:9000;,重新启动Nginx容器即可恢复正常。

内容的提问来源于stack exchange,提问作者iigmir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 14:20:15