php editor Xigua is here to answer a common question: Why can’t the Go language access port 8080 in the Docker container? When using Docker containers, we often encounter the problem of being unable to access the internal ports of the container. This is often caused by network configuration issues with the Docker container. By understanding the Docker network and adjusting accordingly, we can solve this problem and enable the Go language to successfully access port 8080 in the Docker container. Below, I will explain in detail how to solve this problem.
So I want to deploy my simple go backend in cloud run. I use gin to handle routing. My main function that handles it looks like this:
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") }
I tried building it using docker and it worked. My dockerfile looks like this:
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"]
So I tried running it using docker run in the google cloud cli and it seemed to run fine:
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
But when I try to preview it on port 8080, I can't access it:
I tried deploying it in cloud run, but not surprisingly, it didn't work. I get:
STARTUP HTTP probe failed 1 time consecutively for container "math-arc-api-1" on path "/api/health". The instance was not started.
What did i do wrong?
So @Hans Kilian’s answer in the comments is correct. The problem is because I use localhost instead of 0.0.0.0
. I thought I had changed it in the code to 0.0.0.0
but it seems I made some mistakes while building it.
The above is the detailed content of Why can't go access port 8080 in docker. For more information, please follow other related articles on the PHP Chinese website!