Go语言 运行后容器退出

xxls0lw8  于 2023-03-27  发布在  Go
关注(0)|答案(1)|浏览(177)

我有一个Golang Fiber服务器,在Google Cloud Run上运行时会自动退出,并显示以下消息:

Container called exit(0).

我使用以下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"]

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")
}

最后一行在Google Cloud Run日志中执行得很好,我可以看到Api started listening in port 8080
为什么我的容器单独退出?它应该启动Fiber API。

btxsgosb

btxsgosb1#

我发现了这个问题。在我的stage.env文件中,我已经将端口设置为:8080。在本地,传递app.Listen(c.Port)可以按照预期转换为app.Listen(":8080")。在Cloud Run中使用时,这被转换为app.Listen("8080"),当然不起作用,因为它认为这是主机而不是端口。
我添加了app.Listen(":" + c.Port),它可以工作。
如果您遇到这种情况,请捕获错误:

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)
}

并采取相应的行动。

相关问题