{ "@context": "https://schema.org", "@type": "Article", "headline": "Docker Go 构建不支持 HTTP 服务", "datePublished": "2024-03-27T08:18:30", "dateModified": "2024-03-27T08:18:30", "description": "在尝试为一个在端口 8080 上侦听 HTTP 请求的 Go 应用程序创建 Docker 容器时遇到了问题,容器启动后无法响应。该应用程序在本地运行时正常,但在 Docker 中运行时却没有任何反应。问题内容尝试为我的 go 应用程序创建 docker 容器 - 它在端口 8080 上创建一个 http 服务器:package mainimport ( net/http)func main() { http.handlefunc(/, dox) if err := http.li", "publisher": { "@type": "Organization", "name": "Golang学习网", "url": "https://m.17golang.com" }, "mainEntityOfPage": { "@type": "WebPage", "@id": "https://m.17golang.com/article/114383.html" } }
登录
首页 >  Golang >  Go问答

Docker Go 构建不支持 HTTP 服务

来源:stackoverflow

时间:2024-03-27 08:18:30 259浏览 收藏

在尝试为一个在端口 8080 上侦听 HTTP 请求的 Go 应用程序创建 Docker 容器时遇到了问题,容器启动后无法响应。该应用程序在本地运行时正常,但在 Docker 中运行时却没有任何反应。

问题内容

尝试为我的 go 应用程序创建 docker 容器 - 它在端口 8080 上创建一个 http 服务器:

package main
import (
    "net/http"
)

func main() {
    http.handlefunc("/", dox)
    if err := http.listenandserve("localhost:8080", nil); err != nil {
        panic(err)
    }
}

func dox(w http.responsewriter, r *http.request) {
    x
}

当我运行 go build 然后转到 localhost:8080 时它可以工作,但是当我尝试在 docker 中构建并运行它时它没有响应:

# Start from the latest golang base image
FROM golang:1.14.3-alpine

# Set the Current Working Directory inside the container
WORKDIR /app

# Copy the source from the current directory to the Working Directory inside the container
COPY /src .

# Build the Go app
RUN go build -o main .

# Expose port 8080 to the outside world
EXPOSE 8080

# Command to run the executable
CMD ["./main"]

我正在运行的命令是:

docker build -t src 。 docker run -d -p 8080:8080 src

我的所有 .go 文件都位于名为“src”的目录中。感谢帮助 - 对 docker 还很陌生,谢谢!


正确答案


将主机从 localhost 更改为 0.0.0.0。没事的。 即

func main() {
    http.handlefunc("/", dox)
    if err := http.listenandserve("0.0.0.0:8080", nil); err != nil {
        panic(err)
    }
}

环回的主要思想是在同一主机上提供资源。如果您公开端口,主机会发生变化,因此它应该抛出 connection 由peer 重置的错误。

或者,如果您的 golang 应用程序需要在不同镜像的其他容器之间进行通信,您可能希望创建一个网络。 因此首先需要创建一个新网络。

docker network create 

然后在启动此 go 容器以及不同的容器时(如果需要的话)传递 network 标志以使它们在同一子网下可用。

docker run --network  -d -p 8080:8080 src

如果您不想这样做,请在 docker 的 host 网络上运行容器(ps。这不是标准做法,但有利于调试)。如果您在 host 网络中使用 localhosthttp.listenandserve 运行您的 src 映像,您可能会立即注意到它是可访问的,但在 docker 的 bridge 网络模式上公开端口时,它是不可访问的。因此,应用程序设置中一定存在一些错误,导致外部网络看不到它。

docker run -d --network host src

谢谢:)

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Docker Go 构建不支持 HTTP 服务》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>