docker, jenkins,

Clean up Docker space for Jenkins jobs

Jul 15, 2021 · 1 min read · Post a comment

Managing and deploying complex infrastructure with Jenkins sometimes can cause job failure issues. For example, if you are working with microservices and all the deployments are going through the Jenkins server that definitely will cause space issues especially if the Jenkins is inside a Docker container. The Docker images that you are building for your microservices will fill up the data blocks within containers, so you will run into a Docker space issue.

Prerequisites

  • CLI access of your Dockerized Jenkins instance
  • sudo privileges

Check Docker Data Space

Step 1. To check the Docker data space on your Dockerized Jenkins instance, execute:

sudo docker info | grep "Data Space"

If you don’t have enough available space, or you just have 1 or 2GB left, jump on the steps below.

Cleaning up Docker space

Step 1. Execute the following command to see if there are any stopped containers:

sudo docker rm $(sudo docker ps -aq)

Step 2. Now check if you have some unused images and remove them with the following command:

sudo docker rmi $(sudo docker images -q)

Step 3. If the above commands didn’t free up the Docker space memory then you will have to remove the unused data blocks. You can use the following command:


sudo sh -c "docker ps -q | xargs docker inspect --format='{{ .State.Pid }}' | xargs -IZ fstrim /proc/Z/root/"

Conclusion

I wouldn’t recommend using Jenkins in a Dockerized environment, but if you already have it for your infra, and it is causing space issues, you can set up a cronjob in Jenkins with the commands above. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.