php小編西瓜在這里為大家解答一個(gè)常見問題:為什么Go語(yǔ)言無法訪問Docker容器中的8080端口?在使用Docker容器時(shí),我們常常會(huì)遇到無法訪問容器內(nèi)部端口的問題。這往往是因?yàn)镈ocker容器的網(wǎng)絡(luò)配置問題所致。通過對(duì)Docker網(wǎng)絡(luò)的理解和相應(yīng)的調(diào)整,我們可以解決這個(gè)問題,并使Go語(yǔ)言能夠成功訪問Docker容器中的8080端口。下面,我將詳細(xì)解釋如何解決這個(gè)問題。
問題內(nèi)容
所以我想在 cloud run 中部署我的簡(jiǎn)單 go 后端。我使用 gin 來處理路由。我處理它的主要函數(shù)如下所示:
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") }
登錄后復(fù)制
我嘗試使用 docker 構(gòu)建它并且成功了。我的 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"]
登錄后復(fù)制
所以我嘗試在 google cloud cli 中使用 docker run 來運(yùn)行它,它似乎運(yùn)行得很好:
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
登錄后復(fù)制
但是當(dāng)我嘗試在端口 8080 上預(yù)覽它時(shí),我無法訪問它:
我嘗試將其部署在 cloud run 中,但毫不奇怪,它不起作用。我得到:
STARTUP HTTP probe failed 1 time consecutively for container "math-arc-api-1" on path "/api/health". The instance was not started.
登錄后復(fù)制
我做錯(cuò)了什么?
解決方法
所以評(píng)論中 @Hans Kilian 的答案是正確的。問題是因?yàn)槲沂褂?localhost 而不是 0.0.0.0
。我以為我已經(jīng)在代碼中將其更改為 0.0.0.0
但似乎我在構(gòu)建它時(shí)犯了一些錯(cuò)誤。