How to Remove Old Unused Images on Kubernetes Cluster.

Delete Old unused Images on Kubernetes Cluster

Docker is an open-source containerisation platform which is designed to make it easier to create, deploy, and run applications by using containers.

Kubernetes is a container orchestrator, it needs a container runtime in order to orchestrate. Kubernetes is most commonly used with Docker, but it can also be used with any container runtime.

When working with kubernates, you can quickly accumulate a large number of unused objects that consume significant disk space. kubernates doesn’t remove unused images on your kubernates cluster nodes.

In this article we will see how to depoly DaemonSet on cluster which remove the unused images on kubernates cluster.

Git Url:

1) Make Dockerfile

The Docker image is created with instructions written in the Dockerfile. So we use official ubuntu:18.04 base image, install package, copy dockerimages-cron and files to cron.d directory and root directory respectively. Then we give execution rights on the cron job and apply cron job and on last line Run the command on container startup.

FROM ubuntu:18.04


ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get install -yq --no-install-recommends \
apt-utils \ \
cron \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
# Copy dockerimages-cron file to the cron.d directory
COPY dockerimages-cron /etc/cron.d/dockerimages-cron
# Copy Script on root Directory
COPY /root/
# Give execution rights on the cron job
RUN chmod 0744 /etc/cron.d/dockerimages-cron
# Apply cron job
RUN crontab /etc/cron.d/dockerimages-cron
# Create the log file to be able to run tail
RUN touch /var/log/cron.log
# Run the command on container startup
#CMD cron && tail -f /var/log/cron.log
CMD ["cron", "-f"]

2) Bluid the Docker image.

We using docker build command to build the image.

docker build -t kumargaurav522/docker_cleanup:latest .

3) Push image on docker repository.

We using docker hub repository to push the docker image.

docker push kumargaurav522/docker_cleanup:latest

4) Deploy on kubernates cluster.

We use DaemonSet in a YAML file. which will ensures that all (or some) Nodes run a copy of a Pod. you can download deployment.yaml file.

kubectl apply -f  deployment.yaml

Hope this post will help Devops beginners. Please share you feedback and Comments. Stay tune for more updates with …!!!

Leave a Reply


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of