Buy Me a Coffee

[Docker] Understanding `docker stack deploy --prune` in Docker Swarm

Docker Swarm - Efficient container management with prune

When managing services in Docker Swarm mode, the --prune flag in docker stack deploy helps keep your stack synchronized with your compose file. It ensures that only the services defined in your current file remain running, and anything outdated is automatically cleaned up.


What the --prune Flag Does

When you run this command:

docker stack deploy -c docker-compose.yml mystack --prune

Docker compares your current stack with the new compose file and performs three actions:

  1. Creates any new services that didn’t exist before.
  2. Updates any services whose configuration has changed.
  3. Removes (prunes) services that are no longer listed in the compose file.

Example

Initial stack:

services:
  web:
    image: nginx
  db:
    image: postgres

After deployment:

docker stack deploy -c docker-compose.yml mystack

Now you will have two services running: web and db.

Then you remove the db service from the compose file:

services:
  web:
    image: nginx:alpine

Redeploy with:

docker stack deploy -c docker-compose.yml mystack --prune

Result:

  • The web service updates to nginx:alpine
  • The db service is automatically removed

Without --prune, the db service would continue running, even though it was deleted from the compose file.


Why Old Containers Still Appear

After redeploying, you might notice:

docker service ls   # shows only active services
docker ps -a        # shows old stopped containers

This is expected. Swarm creates new containers (tasks) when a service is updated and stops the old ones. The stopped containers remain in the system for history and diagnostics.

They no longer use CPU or RAM, but they stay on disk for inspection, logs, and potential rollbacks.

To clean them up:

docker container prune

This removes all stopped containers safely.


Summary

The --prune flag keeps your Swarm stack tidy and consistent. It ensures that only what’s in your compose file remains deployed and prevents abandoned services from running. While Docker keeps stopped containers for history, you can safely prune them to maintain a clean and efficient Swarm environment.


Enjoyed this article? Support my work with a coffee ☕ on Ko-fi.
Buy Me a Coffee at ko-fi.com
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !