So I want to deploy my simple Go backend in Cloud Run. I use Gin to handle the routing. My main function that handle it look 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 try to build it using docker and it success. My Dockerfile look 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 try to run it with docker run in Google Cloud CLI, and it seems to run pretty 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 try to just deploy it in Cloud Run, but to no surprise, it's not working. 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 the answer from @Hans Kilian in the comment is the right one. The problem is because I use localhost instead of 0.0.0.0
. I thought that I has changed it to 0.0.0.0
in the code but seems like I did some mistake when I built it.