为什么go无法访问docker中的8080端口
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无法访问docker中的8080端口的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

Go语言中哪些库是大公司开发或知名开源项目?在使用Go语言进行编程时,开发者常常会遇到一些常见的需求,�...

Go语言中结构体定义的两种方式:var与type关键字的差异Go语言在定义结构体时,经常会看到两种不同的写法:一�...

Go语言中使用RedisStream实现消息队列时类型转换问题在使用Go语言与Redis...

Go语言中字符串打印的区别:使用Println与string()函数的效果差异在Go...

Go指针语法及viper库使用中的寻址问题在使用Go语言进行编程时,理解指针的语法和使用方法至关重要,尤其是在...

为什么Go语言中的map迭代会导致所有值变成最后一个元素?在Go语言中,面对一些面试题时,经常会遇到关于map�...
