Skip to content

How to create a kubernetes CronJob to cleanup old docker images

Last updated on May 31, 2023

This CronJob runs every day at midnight and executes a shell script that will remove all unused images, containers, and volumes that are older than 24 hours. The script uses the `docker image prune` command to perform the cleanup.

To use this CronJob, save it to a file (e.g. `docker-image-cleanup.yaml`) and apply it to your Kubernetes cluster using the `kubectl apply` command:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: docker-image-cleanup
spec:
  schedule: "0 0 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: docker-image-cleanup
            image: docker
            command:
            - /bin/sh
            - -c
            - >
              echo y | docker system prune --force --filter "until=24h" --volumes
            volumeMounts:
            - name: docker-socket
              mountPath: /var/run/docker.sock
          volumes:
          - name: docker-socket
            hostPath:
              path: /var/run/docker.sock
          restartPolicy: OnFailure

This configuration mounts the Docker socket from the host as a volume inside the container, allowing the `docker` command to interact with the host’s Docker daemon.

Note that this configuration can be a security risk if the CronJob is running in an untrusted environment, as it provides unrestricted access to the Docker daemon. Make sure to properly secure your Kubernetes cluster and limit access to the Docker socket as necessary.

kubectl apply -f docker-image-cleanup.yaml

Additional to this, we can make telegram notifications:
* add your bot token and chat id

            command:
            - /bin/sh
            - -c
            - >
              echo y | docker system prune --force --filter "until=24h" && apk add curl && curl -s -X POST https://api.telegram.org/bot<TOKEN>/sendMessage -d chat_id=<your_channel_id> -d text="☸️ k8s-services-stage: Docker cleanup complete %0AFree disk space: $(df -h | grep sda2 | awk '{print $4}' | head -c 6) %0AAvailable memory: $(free -h |grep Mem | awk '{print $7}')"

And the result will look like this

Published inAutomationKubernetesScriptSecurityShell