首頁  >  文章  >  後端開發  >  容器運作完後退出

容器運作完後退出

WBOY
WBOY轉載
2024-02-09 09:50:191081瀏覽

容器運作完後退出

在Web開發中,容器是一種常見的技術,如Docker、Kubernetes等。它們能夠提供環境隔離和資源管理的功能,使應用程式能夠在不同的環境中運作。然而,有時候我們希望容器運行完畢後能夠自動退出,而不是一直保持運作狀態。那麼,如何實現容器運作完畢後自動退出呢?本文將為大家介紹一些實作方法和技巧。

問題內容

我的 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(僅 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 開始偵聽連接埠 8080

為什麼我的容器會單獨退出?它應該啟動 fiber api。

解決方法

我發現了這個問題。在我的 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)
}

並採取相應行動。

以上是容器運作完後退出的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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