首頁  >  文章  >  後端開發  >  為什麼go無法存取docker中的8080端口

為什麼go無法存取docker中的8080端口

WBOY
WBOY轉載
2024-02-11 18:54:08886瀏覽

為什麼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中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除