I have a kubernetes (eks)cluster with multiple pods running. I want to run django migrations on each pod. Whenever new code is deployed I want to run migrations automatically on each pod.
I have figured out there are 2 ways to do it:
1.Through Job 2. Running a script in specs of container.
I want to do it through job. Can someone guide how can i achieve this using jobs in kubernetes?
I have seen some articles. But in job do i have to specify new images for all pods every time i deploy latest changes?
CodePudding user response:
When you run a container you can override its main command. You can use this in the context of a Job to run migrations instead of the Django server.
apiVersion: batch/v1
kind: Job
metadata: {...}
spec:
template:
spec:
containers:
- name: migrate
image: ...
command: [./manage.py, migrate]
This Job will run only once, and you will have to delete and recreate it if you want it to run again. The Job's image:
does need to match the build of the main application, since the migrations will presumably be embedded in the image.
You tagged this question with the Helm tool. If you're using Helm, you can run this Job as a hook. This can cause it to be re-run whenever you run helm upgrade
. This also will simplify the task of keeping the per-build image:
in sync.
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "mychart.fullname" . }}-migrate
labels:
{{- include "mychart.labels" . | nindent 4 }}
annotations:
helm.sh/hook: post-install,post-upgrade
spec:
template:
spec:
containers:
- name: migrate
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
command: [./manage.py, migrate]
I've copied some of the boilerplate from the standard chart template. In particular note the helm.sh/hook
annotation, which causes the Job to be run as a Helm hook, and the templating in image
, which would let you helm upgrade mychart . --set-string tag=20230126
to provide the image tag at deploy time.