10.2. Write a PersistentVolumeClaim#

In this lab you’ll configure the mysite pod to use the PersistentVolumeClaim that you made in the last lab, 10.1. Persistent Volumes. Using a PersistentVolumeClaim ensures that your valuable user data is kept separately from your pods.

Update the Pod Definition#

There are two fragments that you must add to your pod definition in deployment/pod.yaml. The first one goes under the spec key and ensures that the PersistentVolume is available to the machine running the pod:

volumes:
- name: db
  persistentVolumeClaim:
      claimName: mysite-data

The second fragment makes the volume available to a particular container. This one is siblings with image, ports and resources definition under the spec.containers[0] key:

volumeMounts:
- name: db
  mountPath: /data

Redeploy the Pod#

You can’t simply update the pod with a volume mount. You have to delete and restart it:

$ kubectl delete pod/mysite-pod
$ kubectl apply -f pod.yaml

Verify that the volume is present:

$ kubectl describe pod/postgres
...
    Mounts:
      /var/lib/postgresql/data from db (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-vr2qm (ro)
...
Volumes:
  db:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  db
    ReadOnly:   false
  default-token-vr2qm:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-vr2qm
    Optional:    false

Re-Initialize the Database#

Now that the data has moved to its permanent location you have to start the database fresh:

$ kubectl exec --stdin --tty  pod/mysite-pod -- /bin/bash 
root@mysite-pod:/mysite# python manage.py migrate
root@mysite-pod:/mysite# python manage.py createsuperuser 
...