公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

php小编西瓜在这里为大家解答一个常见问题:为什么Go语言无法访问Docker容器中的8080端口?在使用Docker容器时,我们常常会遇到无法访问容器内部端口的问题。这往往是因为Docker容器的网络配置问题所致。通过对Docker网络的理解和相应的调整,我们可以解决这个问题,并使Go语言能够成功访问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 但似乎我在构建它时犯了一些错误。

分享到:
标签:Go语言
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定