Search code examples
gogoogle-cloud-rungo-fiber

Container exits after running after running


I have a Golang Fiber server that exits automatically with the following message when running on Google Cloud Run:

Container called exit(0).

I am running it with the following Dockerfile

# Use the offical golang image to create a binary.
FROM golang:buster as builder

# Create and change to the app directory.
WORKDIR /app

# Retrieve application dependencies.
COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY . ./
RUN go build

# Use the official Debian slim image for a lean production container.
# https://hub.docker.com/_/debian
# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage- builds
FROM debian:buster-slim
RUN set -x && apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
    ca-certificates && \
    rm -rf /var/lib/apt/lists/*

# Copy the binary to the production image from the builder stage.
COPY --from=builder /app/redirect-middleware.git /app/
COPY --from=builder /app/pkg /app/pkg/

EXPOSE 8080

# Run the web service on container startup.
CMD ["/app/redirect-middleware.git", "dev"]

and my main.go (only func main())

func main() {
    // Load env config
    c, err := config.LoadConfig()
    if err != nil {
        log.Fatalln("Failed at config", err)
    }

    // init DB
    db.InitDb()

    // init fiber API
    app := fiber.New()
    log.Print("Started new Fiber app...")

    // initial route sending version of API
    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString(fmt.Sprintf("Redirection middleware - v%s", viper.Get("Version").(string)))
    })
    log.Print("Default root route set...")

    // api routes
    api := app.Group("/api") // /api
    v1 := api.Group("/v1") // /api/v1
    log.Print("api/v1 group set...")

    // register routes v1
    mastermenus.RegisterRoutes(v1)
    log.Print("Route registered...")

    app.Listen(c.Port)
    log.Print("Api started listening in port 8080")
}

The last line is executing fine in Google Cloud Run logs, I can see the Api started listening in port 8080.

Why is my container exiting alone? It should start the Fiber API.


Solution

  • I found the issue. In my stage.env file I have setup the port to be :8080. Locally, passing app.Listen(c.Port) translates fine to app.Listen(":8080") as expected. When using that in Cloud Run this is transformed to app.Listen("8080"), which of course does not work as it thinks this is a host and not a port.

    I added app.Listen(":" + c.Port) which works.

    In case you experience that, please catch the error:

    errApp := app.Listen(":" + c.Port)
    if errApp != nil {
        log.Printf("An error happened while running the api: %s", errApp)
    } else {
        log.Printf("Api started listening in port %s", c.Port)
    }
    

    And act accordingly.