Kubernetes Deployments and Init Containers

To avoid confusion, ill answer your specific question. i agree with oswin that you may want to consider another method.

Yes, you can use init containers with a deployment. this is an example using the old style (pre 1.6) but it should work

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: 'nginx'
spec:
  replicas: 1
  selector:
    matchLabels:
      app: 'nginx'

  template:
    metadata:
      labels:
        app: 'nginx'
      annotations:
        pod.beta.kubernetes.io/init-containers: '[
            {
                "name": "install",
                "image": "busybox",
                "imagePullPolicy": "IfNotPresent",
                "command": ["wget", "-O", "/application/index.html", "http://kubernetes.io/index.html"],
                "volumeMounts": [
                    {
                      "name": "application",
                      "mountPath": "/application"
                    }
                ]
            }
        ]'
    spec:
      volumes:
        - name: 'application'
          emptyDir: {}

      containers:

      - name: webserver
        image: 'nginx'
        ports:
        - name: http
          containerPort: 80
        volumeMounts:
          - name: 'application'
            mountPath: '/application'

You probably want to use readiness probes instead of init containers for this use case. Check out this link and a blog. Also note that a deployment will not send traffic to a pod that is not reported ready - If that was your worry.

This is a well known pattern and a readiness probe in the web server would simply check the DB endpoint / data availability before reporting ready. This is a simple solution as opposed to the complexity of an extra init container and has the advantage of detecting DB outages correctly as well.

Tags:

Kubernetes