在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中文網其他相關文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器