API Server and Pod (3)

Init Container

在 Kubernetes 中,Init Container 是一種特殊的容器,會在 Pod 的應用容器之前運行。

Init Container 的主要目的是進行一些初始化工作,為應用容器的運行做好準備。

以下是一些可能需要使用 Init Container 的場景:

  • 初始化數據:例如,你可能有一個應用需要在啟動前,從遠端數據庫,或其他存儲中加載初始化數據或配置文件。
    • 在這種情況下,你可以使用一個 Init Container 來執行這個加載任務,然後再啟動應用容器。
  • 等待其他服務:有時,你的應用可能依賴於其他服務的可用性。
    • 例如,你的應用可能需要等待一個數據庫服務變為可用。你可以使用一個 Init Container 來進行這個等待操作,然後再啟動應用容器。
  • 設置配置或環境變量:你的應用可能需要一些特殊的配置或環境變量才能運行。
    • 可以使用一個 Init Container 來設置這些配置或環境變量。
  • 運行一次性或前置任務:有些任務只需要在 Pod 啟動時運行一次,或者必須在應用容器運行前完成。

Init Container 和應用容器在同一個 Pod 中共享 Volume,意味著 Init Container 可以將數據或結果留給應用容器使用。

Pod 的初始化過程會等待所有 Init Container 成功完成後才會啟動應用容器。

這提供了一種機制,讓你可以確保應用容器在運行前完成所有必要的準備工作。

init-containers.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
apiVersion: v1
kind: Pod
metadata:
name: pod-with-init-containers
spec:
initContainers:
- name: init-service
image: busybox
command: ["sh", "-c", "echo waiting for sercice; sleep 4"]
- name: init-database
image: busybox
command: ["sh", "-c", "echo waiting for database; sleep 4"]
containers:
- name: app-container
image: nginx

使用 k get pod --watch 可以看到他的 status 從 0/1 到 1/1 的過程。

1
2
3
4
5
6
7
8
9
10
➜ k apply -f init-containers.yml        
pod/pod-with-init-containers created
➜ k get pod --watch
NAME READY STATUS RESTARTS AGE
pod-with-init-containers 0/1 Init:0/2 0 2s
pod-with-init-containers 0/1 Init:0/2 0 3s
pod-with-init-containers 0/1 Init:1/2 0 7s
pod-with-init-containers 0/1 Init:1/2 0 10s
pod-with-init-containers 0/1 PodInitializing 0 14s
pod-with-init-containers 1/1 Running 0 17s

Pod Lifecycle

待更…


API Server and Pod (3)
https://phoebeho.com/sre/20230730/3911436516/
作者
Phoebe
發布於
2023年7月30日
許可協議