how to start rails rake tasks in kubernetes cron job

8/8/2021

We are deploying a Rails application on Kubernetes.

The assets:precompile task run as part of the Docker image build process.

We want to run rake tasks like rake db:migrate task and other tasks on each deployment.

Current solution, we are using kubectl exec.

deplyment.yaml

apiVersion: extensions/v1
kind: Deployment
metadata:
  name: rails-app
spec:
  template:
    spec:
      containers:
        - image: test/rails-app:v0.0.1
          name: myapp
          imagePullPolicy: IfNotPresent

Get list of pods

$ kubectl get pods

Then exec on the rails pod:

$ kubectl exec rails-app-4007005961-1st7s                              \
          -- bash -c                                               \
          'bin/rake db:migrate

'

We need to use kubernentes cronjob (.yaml) to start our rake taks but we do not know which docker image we must use ? how to connect to rails pod and start the rake task ?. example of implementation ?

-- karlos
kubernetes
kubernetes-cronjob
ruby-on-rails
ruby-on-rails-3

1 Answer

8/9/2021

We need to use kubernentes cronjob (.yaml) to start our rake taks

I don't think you need a k8s cronjob to run your db migrations. You might wanna use the job resource in k8s, and run it as part of your CI/CD script. Run it right before you apply your deployment.yaml file. In case the migrations job fails, you should abort the deployment.

-- 3minus1
Source: StackOverflow