How to automatically restart pods when a new image ready

12/13/2020

I'm using K8s on GCP.

Here is my deployment file

apiVersion: apps/v1
kind: Deployment
metadata:
  name: simpleapp-direct
  labels:
    app: simpleapp-direct
    role: backend
    stage: test
spec:
  replicas: 1
  selector:
    matchLabels:
      app: simpleapp-direct
      version: v0.0.1
  template:
    metadata:
      labels:
        app: simpleapp-direct
        version: v0.0.1
    spec:
      containers:
        - name: simpleapp-direct
          image: gcr.io/applive/simpleapp-direct:latest
          imagePullPolicy: Always

I first apply the deployment file with kubectl apply command

kubectl apply -f deployment.yaml 

The pods were created properly.

I was expecting that every time I would push a new image with the tag latest, the pods would be automatically killed and restart using the new images.

I tried the rollout command

kubectl rollout restart deploy simpleapp-direct

The pods restart as I wanted.

However, I don't want to run this command every time there is a new latest build. How can I handle this situation ?.

Thanks a lot

-- user1739211
deployment
google-cloud-platform
kubernetes

1 Answer

12/13/2020

Try to use image hash instead of tag in your Pod Definition.

Generally: there is no way to automatically restart pods when the new image is ready. It is generally advisable not to use image:latest (or just image_name) in Kubernetes as it can cause difficulties with rollback of your deployment. Also you need to make sure that the flag: imagePullPolicy is set to Always. Normally when you use CI/CD or git-ops your deployment is updated automatically by these tools when the new image is ready and passed thru the tests.

When your Docker image is updated, you need to setup a trigger on this update within your CI/CD pipilne to re-run the deployment. Not sure about the base system/image where you build your docker image, but you can add there kubernetes certificates and run the above commands like you do on your local computer.

-- yurasov
Source: StackOverflow