LoginSignup
0

More than 1 year has passed since last update.

[kubernetes] CronJobで複数コンテナを任意の順番で動かす方法

Last updated at Posted at 2022-08-04

概要

k8s上で定期的にJobを実行させる際、CronJobを使用することがある。
1回のJobで複数コンテナを使用し、かつ動かすコンテナの順番を任意に指定する方法を以下に示す

方法

Init Containersを使用する。
Init ContainersとはPodが立ち上がる際、メインのアプリコンテナが立ち上がる前に動作するコンテナ群であり、主にアプリコンテナのためのセットアップを行うために使用される。

通常のアプリコンテナとの差は以下の機能がサポートされない点である。

  • lifecycle
  • livenessProbe
  • readinessProbe

Init Containersを使用する理由はコンテナを任意の順番で動作させることが可能であるからである。公式ドキュメントには以下のような記載がある

If you specify multiple init containers for a Pod, kubelet runs each init container sequentially. Each init container must succeed before the next can run. When all of the init containers have run to completion, kubelet initializes the application containers for the Pod and runs them as usual.

Init Containersに指定されたコンテナ達はkubeletによって順番に実行されるのである。

つまりCronJobを使いbatch-01コンテナとbatch-02コンテナをbatch-01batch-02の順番で動作させたい場合は以下のようにyamlを記述する。

apiVersion: batch/v1
kind: CronJob
metadata:
  name: batch
spec:
  schedule: "0 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          initContainers:
          - name: batch-01
            image: batch-01
          - name: batch-02
            image: batch-02
          containers:
          - name: job-done
            image: job-done
            command: ['sh', '-c', 'echo "batch-01 and batch-02 completed"']
          restartPolicy: OnFailure

少し強引な方法ではあるが...

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
0