kubernetes

How to run command after initialization


I would like to run specific command after initialization of deployment is successful.

This is my yaml file:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: auth
spec:
  replicas: 1
  template:
    metadata:
        labels:
          app: auth
    spec:
      containers:
        - name: auth
          image: {{my-service-image}}
          env:
          - name: NODE_ENV
            value: "docker-dev"
          resources:
            requests:
              cpu: 100m
              memory: 100Mi
          ports:
            - containerPort: 3000

However, I would like to run command for db migration after (not before) deployment is successfully initialized and pods are running.

I can do it manually for every pod (with kubectl exec), but this is not very scalable.


Solution

  • I resolved it using lifecycles:

    apiVersion: extensions/v1beta1
    kind: Deployment
    metadata:
      name: auth
    spec:
      replicas: 1
      template:
        metadata:
            labels:
              app: auth
        spec:
          containers:
            - name: auth
              image: {{my-service-image}}
              env:
              - name: NODE_ENV
                value: "docker-dev"
              resources:
                requests:
                  cpu: 100m
                  memory: 100Mi
              ports:
                - containerPort: 3000
              lifecycle:
                postStart:
                  exec:
                    command: ["/bin/sh", "-c", {{cmd}}]