본문 바로가기

Container/Kubernetes

[K8S] init container

 

https://kubernetes.io/ko/docs/concepts/workloads/pods/init-containers/

 

초기화 컨테이너

이 페이지는 초기화 컨테이너에 대한 개요를 제공한다. 초기화 컨테이너는 파드의 앱 컨테이너들이 실행되기 전에 실행되는 특수한 컨테이너이다. 초기화 컨테이너는 앱 이미지에는 없는 유틸

kubernetes.io

  • 앱(main) 컨테이너 실행 전에 미리 동작시킬 컨테이너
    • 컨테이너에서 완료까지 실행되는 프로세스를 실행하기를 원할 때.
  • main Container가 실행되기 전에 사전 작업이 필요한 경우 사용
    • Pod가 처음 생성될 때 한 번만 실행된다. (실제 application이 시작되기 전에 외부 서비스나 데이터베이스가 작동하기를 기다리는 프로세스)
    • 초기화 컨테이너는 앱 이미지에는 없는 유틸리티 또는 설정 스크립트 등을 포함
  • 초기화 컨테이너가 모두 실행된 후에 앱 컨테이너를 실행
  • Init container를 담고 있는 Pod에서는 init container가 성공하지 못하면 main container는 실행되지 않는다.
Name:             blue
Namespace:        default
Priority:         0
Service Account:  default
Node:             controlplane/192.168.251.226
Start Time:       Wed, 08 Jan 2025 11:10:51 +0000
Labels:           <none>
Annotations:      <none>
Status:           Running
IP:               10.42.0.11
IPs:
  IP:  10.42.0.11
Init Containers:
  init-myservice:
    Container ID:  containerd://19a00075ded2d16ea0b10a55e44d775a1ec3304fb4d120d440d67f78cf140cd3
    Image:         busybox
    Image ID:      docker.io/library/busybox@sha256:2919d0172f7524b2d8df9e50066a682669e6d170ac0f6a49676d54358fe970b5
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      sleep 5
    State:          Terminated   #   sleep 5를 실행시키고 종료된다.
      Reason:       Completed
      Exit Code:    0
      Started:      Wed, 08 Jan 2025 11:10:52 +0000
      Finished:     Wed, 08 Jan 2025 11:10:57 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-wjfg2 (ro)
Containers:
  green-container-1: # 그리고 본래의 Container 실행된다.
    Container ID:  containerd://eccd527f79549f7e93b1e8f9a2b3a0e641eabe848bb4d9bb7a795ba371a19cde
    Image:         busybox:1.28
    Image ID:      docker.io/library/busybox@sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      echo The app is running! && sleep 3600
    State:          Running
      Started:      Wed, 08 Jan 2025 11:10:58 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-wjfg2 (ro)

# 공식문서에서 가져온 yaml example

[master ~]$ cat > init-container-example.yaml
apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app.kubernetes.io/name: MyApp
spec:
  containers: # main container
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
  initContainers: # 2개의 초기화 컨테이너 (이렇게 initContainers Section에 기입된다.)
  - name: init-myservice
    image: busybox:1.28
    command: ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"]
  - name: init-mydb
    image: busybox:1.28
    command: ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"]

# myservice, mydb가 전부 실행(성공)되어야 myapp-container가 실행될 수 있다.
# 순차적으로 하나씩 실행된다.

[master ~]$ kubectl create -f init-container-example.yaml 
pod/myapp-pod created
[master ~]$ kubectl get pods
NAME        READY   STATUS     RESTARTS   AGE
myapp-pod   0/1     Init:0/2   0          16s
# 하나도 실행되지 못하고 있는 것 확인 (READY 0/1)

[master ~]$ cat > init-container-exam-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: myservice
spec:
  ports:
  - protocol: TCP
    port: 80
    targetPort: 9376
[master ~]$ kubectl create -f init-container-exam-svc.yaml 
service/myservice created
# 하나는 실행 중인 상태로 바뀐 것 확인
[master ~]$ kubectl get pods
NAME        READY   STATUS     RESTARTS   AGE
myapp-pod   0/1     Init:1/2   0          3m7s

[master ~]$ cat > init-container-exam-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: mydb
spec:
  ports:
  - protocol: TCP
    port: 80
    targetPort: 9377
[master ~]$ kubectl create -f init-container-exam-svc.yaml 
service/mydb created
[master ~]$ kubectl get pods
NAME        READY   STATUS     RESTARTS   AGE
myapp-pod   0/1     Init:1/2   0          4m45s
# main container 실행되는 것 확인
[master ~]$ kubectl get pods
NAME        READY   STATUS    RESTARTS   AGE
myapp-pod   1/1     Running   0          4m50s

 

[실습]

# kubectl get pods시에 InitContainer는 count되지 않고, actual container만 조회한다.
controlplane ~ ➜  kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
red     1/1     Running   0          42s
green   2/2     Running   0          42s
blue    1/1     Running   0          42s

Name:             blue
Namespace:        default
Priority:         0
Service Account:  default
Node:             controlplane/192.22.24.3
Start Time:       Sat, 27 Apr 2024 15:17:15 +0000
Labels:           <none>
Annotations:      <none>
Status:           Running
IP:               10.42.0.9
IPs:
  IP:  10.42.0.9
Init Containers:
  init-myservice:
    Container ID:  containerd://a19bc3ac85f6a749c97c55e02cc804483dfe69039a95fc05e183f67b8fb6b549
    Image:         busybox
    Image ID:      docker.io/library/busybox@sha256:c3839dd800b9eb7603340509769c43e146a74c63dca3045a8e7dc8ee07e53966
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      sleep 5
    State:          Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Sat, 27 Apr 2024 15:17:17 +0000
      Finished:     Sat, 27 Apr 2024 15:17:22 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-l6jm9 (ro)

 

 

controlplane ~ $ kubectl describe pod purple
Name:             purple
Namespace:        default
Priority:         0
Service Account:  default
Node:             controlplane/192.22.24.3
Start Time:       Sat, 27 Apr 2024 15:21:04 +0000
Labels:           <none>
Annotations:      <none>
Status:           Pending
IP:               10.42.0.12
IPs:
  IP:  10.42.0.12
Init Containers:
  warm-up-1:
    Container ID:  containerd://980d506251bcb2a358dab839d67e2f18bc5be451bccd74cc480bd72e0f34438b
    Image:         busybox:1.28
    Image ID:      docker.io/library/busybox@sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      sleep 600
    State:          Running
      Started:      Sat, 27 Apr 2024 15:21:05 +0000
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-dfdc7 (ro)
  warm-up-2:
    Container ID:  
    Image:         busybox:1.28
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      sleep 1200
    State:          Waiting
      Reason:       PodInitializing
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-dfdc7 (ro)
      
   # warm-up-1, warm-up-2 가 끝나고 총 30분 뒤에 Pod가 running되기 시작한다.

 

[실습] TroubleShooting

controlplane ~ ➜  kubectl get pod orange 
NAME     READY   STATUS       RESTARTS      AGE
orange   0/1     Init:Error   2 (16s ago)   18s

controlplane ~ ➜  kubectl describe pod orange 
Name:             orange
Namespace:        default
...
Init Containers:
  init-myservice:
    Container ID:  containerd://0b1c57a3e948fa0be9e013cfdbfae8fa5baaa1ca72fe53d7f9da4e2748bebbc4
    Image:         busybox
    Image ID:      docker.io/library/busybox@sha256:c3839dd800b9eb7603340509769c43e146a74c63dca3045a8e7dc8ee07e53966
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      sleeeep 2;
    State:          Terminated
      Reason:       Error
      Exit Code:    127
      Started:      Sat, 27 Apr 2024 15:40:16 +0000
      Finished:     Sat, 27 Apr 2024 15:40:16 +0000
    Last State:     Terminated
      Reason:       Error
      Exit Code:    127
      Started:      Sat, 27 Apr 2024 15:39:46 +0000
      Finished:     Sat, 27 Apr 2024 15:39:46 +0000
    Ready:          False
    Restart Count:  3
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-skt7r (ro)
...
Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  58s                default-scheduler  Successfully assigned default/orange to controlplane
  Normal   Pulled     58s                kubelet            Successfully pulled image "busybox" in 159ms (159ms including waiting)
  Normal   Pulled     43s (x2 over 57s)  kubelet            Successfully pulled image "busybox" in 166ms (166ms including waiting)
  Normal   Pulling    13s (x4 over 58s)  kubelet            Pulling image "busybox"
  Normal   Pulled     13s                kubelet            Successfully pulled image "busybox" in 167ms (167ms including waiting)
  Normal   Created    13s (x4 over 58s)  kubelet            Created container init-myservice
  Normal   Started    13s (x4 over 58s)  kubelet            Started container init-myservice
  Warning  BackOff    12s (x5 over 56s)  kubelet            Back-off restarting failed container init-myservice in pod orange_default(bde93372-263f-4b60-8517-0763e417682f)
  
controlplane ~ ➜  kubectl logs orange 
Defaulted container "orange-container" out of: orange-container, init-myservice (init)
Error from server (BadRequest): container "orange-container" in pod "orange" is waiting to start: PodInitializing
# running logs만이 log fetch될 수 있음.

# 컨테이너 지정해서 확인
controlplane ~ ✖ kubectl logs orange -c init-myservice
sh: sleeeep: not found
# 타이포 이슈 확인

 

반응형

'Container > Kubernetes' 카테고리의 다른 글

[K8S] Pod Resource 할당  (0) 2024.02.19
[K8S] pause container / Static container  (0) 2024.02.19
[K8S] Liveness Probe (Self-healing) Pod  (1) 2024.02.16
[K8S] YAML 템플릿 및 Pod  (0) 2024.02.13
[K8S] namespace란  (0) 2024.02.13