Docker 容器中的 Go 服务器空响应

The*_*ile 9 go docker dockerfile

我有一个 Go 服务器,类似的东西。路由器是 Gorilla MUX

var port string
if port = os.Getenv("PORT"); port == "" {
    port = "3000"
}
srv := &http.Server{
    Handler:      router,
    Addr:         "localhost:" + port,
    WriteTimeout: 15 * time.Second,
    ReadTimeout:  15 * time.Second,
}
fmt.Println("Server is running on port " + port)
log.Fatal(srv.ListenAndServe())
Run Code Online (Sandbox Code Playgroud)

Dockerfile 是

# Build Go Server
FROM golang:1.14 AS go-build
WORKDIR /app/server

COPY cmd/ ./cmd
COPY internal/ ./internal
COPY go.mod ./
COPY go.sum ./
RUN go build ./cmd/main.go


CMD ["./main"]
Run Code Online (Sandbox Code Playgroud)

我构建成功了。我用以下命令运行它

docker run -p 3000:3000 baaf0159d0cd     
Run Code Online (Sandbox Code Playgroud)

我得到以下输出。服务器正在运行

Server is running on port 3000
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用curl发送请求时,我得到了空响应

>curl localhost:3000
curl: (52) Empty reply from server
Run Code Online (Sandbox Code Playgroud)

为什么服务器没有正确响应?我还有另一条路线,但没有放在这里,它们也没有正确响应。顺便说一下,我使用的是 MacOS。

col*_*tor 10

不要使用localhost(基本上是 的别名127.0.0.1)作为 Docker 容器内的服务器地址。如果执行此操作,则只有“localhost”(即 Docker 容器网络内的任何服务)可以访问它。

删除主机名以确保可以在容器外部访问它:

// Addr:         "localhost:" + port, // unreachable outside container
Addr:         ":" + port, // i.e. ":3000" - is accessible outside the container
Run Code Online (Sandbox Code Playgroud)