登录
首页 >  Golang >  Go问答

无法访问Docker容器中的8080端口的原因

来源:stackoverflow

时间:2024-02-06 11:21:21 463浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《无法访问Docker容器中的8080端口的原因》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

所以我想在 cloud run 中部署我的简单 go 后端。我使用 gin 来处理路由。我处理它的主要函数如下所示:

func main() {
    r := gin.default()
    r.get("/api/health", handlers.healthcheckhandler())
    r.post("/questions", handlers.createquestionhandler(client))
    r.get("/questions/:level", handlers.getallquestionhandler(client))
    r.run("0.0.0.0:8080")
}

我尝试使用 docker 构建它并且成功了。我的 dockerfile 如下所示:

from golang:1.20
env gin_mode=release

workdir /app

# download go modules
copy go.mod go.sum ./
run go mod download


copy . .

# build
run  go build -o /docker-api

expose 8080

# run
cmd ["/docker-api"]

所以我尝试在 google cloud cli 中使用 docker run 来运行它,它似乎运行得很好:

docker run -p 8080:8080  gcr.io/matharc/math-arc-api
[gin-debug] [warning] creating an engine instance with the logger and recovery middleware already attached.

[gin-debug] [warning] running in "debug" mode. switch to "release" mode in production.
 - using env:   export gin_mode=release
 - using code:  gin.setmode(gin.releasemode)

[gin-debug] get    /api/health               --> matharc.com/m/handlers.healthcheckhandler.func1 (3 handlers)
[gin-debug] post   /questions                --> matharc.com/m/handlers.createquestionhandler.func1 (3 handlers)
[gin-debug] get    /questions/:level         --> matharc.com/m/handlers.getallquestionhandler.func1 (3 handlers)
[gin-debug] [warning] you trusted all proxies, this is not safe. we recommend you to set a value.
please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[gin-debug] listening and serving http on localhost:8080

但是当我尝试在端口 8080 上预览它时,我无法访问它:

我尝试将其部署在 cloud run 中,但毫不奇怪,它不起作用。我得到:

STARTUP HTTP probe failed 1 time consecutively for container "math-arc-api-1" on path "/api/health". The instance was not started.

我做错了什么?


正确答案


所以评论中 @Hans Kilian 的答案是正确的。问题是因为我使用 localhost 而不是 0.0.0.0。我以为我已经在代码中将其更改为 0.0.0.0 但似乎我在构建它时犯了一些错误。

今天关于《无法访问Docker容器中的8080端口的原因》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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