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

Docker Compose中Golang无法访问PHP服务问题求助

问题解决:Golang服务无法访问PHP-FPM服务(连接重置)

核心原因

PHP-FPM(php:8.3-fpm镜像)默认监听的是FastCGI协议端口9000,而非HTTP协议端口。你的Golang代码用http.Get()发起HTTP请求,协议不匹配直接导致连接被重置——这是根本问题,和端口修改、镜像更换无关。

解决方案

以下提供两种可行方案,按需选择:

方案1:给PHP服务添加内部Nginx反向代理(推荐,保持HTTP访问方式)

通过在内部网络中新增一个Nginx实例,将HTTP请求转换为FastCGI请求转发给PHP-FPM,这样Golang可以继续用HTTP方式访问。

修改docker-compose.yaml

在services块中新增accounting-nginx服务(仅加入内部网络,不暴露外部端口):

services:
  # ... 保留原有所有服务配置
  accounting-nginx:
    image: nginx:1.26.0
    networks:
      - internal-network
    volumes:
      - ./.docker/accounting-nginx/conf.d:/etc/nginx/conf.d
    depends_on:
      - accounting

配置内部Nginx的FastCGI转发

创建./.docker/accounting-nginx/conf.d/default.conf文件:

server {
    listen 80;
    server_name localhost;
    root /var/www/html;

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

    location ~ \.php$ {
        fastcgi_pass accounting:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

修改Golang测试代码

将请求地址替换为内部Nginx服务的地址:

router.GET("/foo", func(c *gin.Context) {
    // 替换为内部Nginx服务名+端口
    url := "http://accounting-nginx/"

    resp, err := http.Get(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
    fmt.Println(resp.StatusCode)
})

方案2:Golang直接使用FastCGI客户端访问PHP-FPM

使用Golang的FastCGI客户端库直接和PHP-FPM通信,无需额外Nginx。

安装FastCGI依赖

执行命令安装第三方库:

go get github.com/gofast/fastcgi

修改Golang测试代码

替换HTTP请求为FastCGI请求:

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/gofast/fastcgi"
)

router.GET("/foo", func(c *gin.Context) {
    // 连接PHP-FPM服务
    client, err := fastcgi.Dial("tcp", "accounting:9000")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer client.Close()

    // 构造FastCGI请求,指定要执行的PHP文件路径
    req := &fastcgi.Request{
        Method:     "GET",
        Path:       "/index.php", // 替换为你的PHP入口文件路径
        Host:       "accounting",
        RemoteAddr: c.ClientIP(),
    }

    // 发送请求并获取响应
    resp, err := req.Do(client)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    fmt.Println(resp.StatusCode)
})

额外检查点

  • 确保accounting服务的/var/www/html目录下存在可执行的PHP文件(如index.php)
  • 确认internal-network网络配置正确,所有需要通信的服务都已加入该网络

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:00:25