Article Image
read

Keeping your docker swarm hosts clean is a necessity. As you roll out new images, you're faced with constant image downloads by each host, as well as possibly dead and stopped containers spending your precious resources (inodes I'm looking at you).

When I first set up cleanup, I simply had a cron job that ran hourly and cleaned up everything (except volumes!).

I didn't like the cron job since it was the only thing (besides the docker install) that actually needed to be set up explicitely on the host server.

Cleanup Stack

I did a bunch of googling, and found a clever solution for cron jobs: A job that will always restart on every node with an hour delay.

Unlike a cron job, this won't run at a specific time, but given my needs, this is more than sufficient.

The below stack will prune containers and images on all hosts in the swarm every hour.

It's worth noting that I explicitely don't prune volumes in this configuration, since I treat them as reliable data.

You can create by running:

$ docker stack deploy --compose-file cleaner.yaml
version: "3.3"
services:
  swarm-cleanup:
    image: docker
    command: |
      sh -c "
        docker container prune -f &&
        docker image prune -f -a"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    deploy:
      mode: global
      restart_policy:
        delay: 1h
      resources:
        limits: { cpus: '0.1', memory: '32M' }
        reservations: { cpus: '0.025', memory: '16M' }

Enjoy!

Blog Logo

Christopher LaPointe


Published

Interested in Related Posts from this Site?

Virtual PDF Network Printer

May 04, 2023: For my [paperless-ngx](https://github.com/paperless-ngx/paperless-ngx) install, I wanted to be able to easily "print" to it from...

Set up your own mailserver with Maddy

February 10, 2022: About a year ago I wanted to expand beyond namecheap's simple "email forwarding" service and...

Extracting a Certificate from Traefik/acme.json

February 04, 2022: It's a fairly common need to extract a certificate and key from traefik to use...

Docker Samba / CIFS Volume (Photoview)

July 12, 2021: Recently I had a need to mount a CIFS volume as a docker volume: The...

Self-Hosted Analytics: Docker & Privacy-First

July 02, 2021: I have a lot of little sites. Probably too many. Includes various personal sites, sites...

Docker Swarm Registry and Auto Garbage Collection on NFS

March 15, 2021: After moving Traefik to v2, I also updated the common registry infrastructure. Namely, this stack...

Image

Chris LaPointe

Another site of Code

Back to Overview