LoginSignup
7

More than 3 years have passed since last update.

[Kubernetes]Init Containersの動作を確認する

Last updated at Posted at 2020-06-04

はじめに

今回はInit Containersの動作を確認したいと思います。
Init Containersとは、アプリケーションコンテナの前に実行され、アプリケーションコンテナのイメージに存在しないセットアップスクリプトやユーティリティーを含んだ特別なコンテナです。

ユースケースとしては、セキュリティの観点でアプリケーションコンテナイメージに含めたくないツールの実行などがあります。
そのほか、以下のマニュアルにも記載されています。

Initコンテナは何に使用できるか?

設定

では、実際にInit Containersを実行してみたいと思います。ここではInit Containersを利用して、nginxのindex.htmlファイルを作成しています。
なお、Init Containersは複数設定することもできます。

initContainer.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-init
  labels:
    app: app1
spec:
  initContainers:
  - name: init01
    image: centos:latest
    args:
    - /bin/sh
    - -c
    - echo "test" > /test/index.html
    volumeMounts:
    - mountPath: /test
      name: nginx-index
  containers:
  - name: nginx
    image: nginx:latest
    volumeMounts:
    - mountPath: /usr/share/nginx/html/
      name: nginx-index
  volumes:
  - name: nginx-index
    hostPath:
      path: /test
      type: Directory

この設定を図にすると、以下のようになります。

image.png

  • Init Containesの初期化処理で、マウントしたボリュームにindex.htmlファイルを作成します。
  • 初期化処理が終わったらアプリケーションコンテナを起動し、index.htmlファイルを作成したボリュームにマウントします。

動作確認

上記のマニフェストをapplyします。このとき、別ターミナルでPodの状態を確認します。

$ kubectl apply -f initContainer.yaml
pod/nginx-init created
$ kubectl get pod -w
NAME         READY   STATUS    RESTARTS   AGE
nginx-init   0/1     Pending   0          0s
nginx-init   0/1     Pending   0          0s
nginx-init   0/1     Init:0/1   0          0s
nginx-init   0/1     Init:0/1   0          1s
nginx-init   0/1     PodInitializing   0          5s
nginx-init   1/1     Running           0          9s

PodがRunningになる前に、Init処理が実行されていることがわかりますね。

外部サーバからアクセスして確認します。LoadBalancerは作成済みです。

$ kubectl get svc
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP    PORT(S)          AGE
kubernetes      ClusterIP      10.96.0.1       <none>         443/TCP          103d
load-balancer   LoadBalancer   10.111.156.47   10.20.30.150   8080:30002/TCP   5d22h
[client]$ curl -s http://10.20.30.150:8080
test

Init Containersで作成したindex.htmlでリクエストが返ってきていますね。

まとめ

今回確認したInit Containersを利用すると、前処理として色々な処理ができますね。
Kubernetesの基本から応用に入ってきてると思いますが、アプリ寄りの考え方がますます必要になってきてるなと感じています。インフラ屋さんと言えど、避けては通れないですね。がんばらないと。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7