Tech blog

Automation - How to Automatically Clean Up Unused Docker Images

14 Jun 2025

Automation - How to Automatically Clean Up Unused Docker Images


Tired of constantly cleaning up unused Docker images that accumulate over time? Here's a simple and effective solution.

Login to your server terminal where you're hosting docker

You can add a prune job on your Docker host that:

Runs automatically at regular intervals (e.g., daily/weekly)

Prunes all unused images

docker image prune -af -filter "until=24h" sudo crontab -e
docker image prune -af --filter "until=24h"

sudo crontab -e
Bash

Add the following line to your cron

0 3 * * 0 docker image prune -af -filter "until=24h"
0 3 * * 0 docker image prune -af --filter "until=24h"
Bash

This will run every Sunday at 3 am and will clean all your unused images!

If you want to take it a step further you can have it daily, just add the following line to your cron

0 3 * * * docker image prune -af -filter "until=24h"
0 3 * * * docker image prune -af --filter "until=24h"
Bash

Want something more flexible?

Use a Docker-based cron container to do this for you, without touching the host cron:

# docker-compose.pruner.yml version: "3.8" services: docker-prune: image: docker volumes: - /var/run/docker.sock:/var/run/docker.sock entrypoint: > sh -c "while true; do docker image prune -af -filter 'until=24h'; sleep 86400; done"
# docker-compose.pruner.yml
version: "3.8"
services:
  docker-prune:
    image: docker
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    entrypoint: >
      sh -c "while true; do
        docker image prune -af --filter 'until=24h';
        sleep 86400;
      done"
YAML

Deploy with:

docker system prune -af -volumes
docker system prune -af --volumes
Bash

Just beware...
This won't remove active images.

Use --filter "until=24h" to avoid pruning newly pulled images too soon.

If you ever want to do full cleanup (volumes, containers, networks), use:

Rate this post

Comments

0 total