Kill all those damn left over docker-compose deployments
Have you ever booted your machine and discovered some left over docker containers?
You can easily stop them all with:
docker stop `docker ps -a -q`
But then, you check again… and they are back up again!
That’s probably because they are part of docker-compose deployments with restart: always
.
Of course in production, you are happy when a docker-compose deployment starts automatically on boot. However on your dev machine, it’s pretty much annoying.
Luckily I have a one liner for you to try out:
docker inspect `docker ps -a -q` | grep working_dir | awk '{ print $2 }' | sed -r 's/[",]+//g' | sort | uniq | while read p; do pushd $p && docker-compose down && popd; done
Let’s see what we have here:
docker inspect `docker ps -a -q`
Runs docker inspect for each container id.
grep working_dir | awk '{ print $2 }'
Filters out the working-dir
key and prints out it’s value.
sed -r 's/[",]+//g'
Cleans the value, because it shows up with “ and , .
At this point, we have a list of working directories for each container. So, we might have some directories showing up more than once.
sort | uniq
This prints out only the unique directories (every directory shows once).
And finally:
while read p; do pushd $p && docker-compose down && popd; done
Iterate over the directories, go in to each one and run docker-compose down
.
So that’s it!
Now your containers aren’t using up all your precious CPU and RAM.