我有一个类似的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())
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"]
我成功建立了。我用以下命令运行它
docker run -p 3000:3000 baaf0159d0cd
我得到了以下输出。服务器正在运行
Server is running on port 3000
但是当我尝试发送带有curl的请求时,我得到了空响应
>curl localhost:3000
curl: (52) Empty reply from server
为什么服务器无法正确响应?我还有另外一条未在此处放置的路线,它们也未正确响应。顺便说一下,我在MacOS上。
最佳答案
请勿在容器中使用localhost
(基本上是127.0.0.1
的别名)作为您的服务器地址。如果执行此操作,则只有“localhost”(即Docker容器网络内的任何服务)都可以访问它。
删除主机名,以确保可以在容器外部对其进行访问:
// Addr: "localhost:" + port, // unreachable outside container
Addr: ":" + port, // i.e. ":3000" - is accessible outside the container
关于docker - Docker容器中的服务器空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61047739/