Ahti Kitsik
Building develper tools. Python, Java, JavaScript.

writings about @ahtik

Removing detached Docker containers

By Ahti Kitsik, 11 Nov 2014

Whenever your Docker containers stop they still remain in the system. Yes, you can automatically remove stopped container with --rm BUT it doesn't work with detached containers (-d)!

So I came up with a quick script to work around this. Hopefully this is also useful for others

#!/bin/bash
# Start docker without -rm and we'll get it removed after exit.
PID=$(docker run -d "$@")
[ -z "$PID" ] && echo "Container failed to start!" && exit 1 || (docker wait $PID && docker rm -v $PID)&

Pleas note the "-v" arg -- this removes the associated volumes as well.

Cheers!

@ahtik is on twitter!