Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes Deployments and Init Containers

Tags:

kubernetes

I learned recently that Kubernetes has a feature called Init Containers. Awesome, because I can use this feature to wait for my postgres service and create/migrate the database before my web application service runs.

However, it appears that Init Containers can only be configured in a Pod yaml file. Is there a way I can do this via a Deployment yaml file? Or do I have to choose?

like image 419
Mitkins Avatar asked May 30 '17 07:05

Mitkins


2 Answers

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'
like image 156
JamStar Avatar answered Oct 18 '22 14:10

JamStar


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.

like image 20
Oswin Noetzelmann Avatar answered Oct 18 '22 15:10

Oswin Noetzelmann