Klaus

Tear down docker test containers based on image name

 Thu, 01 Sep 2016 16:49:47 +0200 
Given your #CI generates #Docker images from your Git commits and tags them with something like web01-qa:$BUILD_NUMBER. Right now I can not set a name for the container that gets spun up after every commit, so I needed a solution to tear down the old containers after successful start of a new container based on the image they were created from. This is what I came up with:

docker ps --format "{{.ID}}\t{{.Image}}" | awk -F ':' '/web01-qa/{print $NF, $0}' | sort -r -n | tail -n+2 | awk '/web01-qa/{system("docker stop " $2)}'
Get all running containers, sort them by $BUILD_NUMBER for the image name containing web01-qa, stop all matching containers except the one from the newest image.

Or use docker rm -f if not interested in the old containers anymore.