Kill all non-Kubernetes containers in Docker

- 2 min read

At work we’re using Kubernetes with Docker for Mac on our local development environments—which has been amazing. However, devs often end up with dangling non-Kubernetes containers hanging around (from terminals being accidentally closed or VS Code reloads) keeping expensive Docker bind mounts around. This is a command I chained together to cleanup these extra containers without disturbing those in the Kubernetes deployment.

Before I dive into how, here’s the complete tl;dr version:

docker container ps --format "{{.Names}}" | grep -v ^k8s | xargs docker kill

First: List all Docker containers by name

We use the docker container ps command to get a list of all Docker containers. We then use the --format option that accepts a Go template to restrict the output to container names:

docker container ps --format "{{.Names}}"

All Kubernetes container names are prefixed with k8s, which we’ll take advantage of next.

Next: Pipe container names to grep

We take pass the stdout stream into the grep command to look for containers that start with k8s.

docker container ps --format "{{.Names}}" | grep ^k8s

^ at the beginning of a regular expression means match from the beginning of the string—specifically the line in this case since we’re not doing a multi-line match.

However if you run this command you’ll see that we end up getting a list of only the Kubernetes containers, we want to get all of the containers that are not running in Kubernetes so that we can kill them. To do this, we invert our matches with the -v option in grep.

docker container ps --format "{{.Names}}" | grep -v ^k8s

Lastly: Pipe the non-Kubernetes container names to Docker kill

What we’d like to do is pipe each of our grep matches into docker kill, however docker kill doesn’t accept stdin. Instead we need to run docker kill [CONTAINER NAME] for each grep result.

To do this, we make use of xargs. xargs let’s us receive stdin lines and use the input lines as the last argument to a command.

You can also specify where to place the line with the -I (replace-str) option, however we don’t need to do that since we do want the container name at the end of our docker kill command.

This completes our command to kill all Docker containers that are not Kubernetes containers:

docker container ps --format "{{.Names}}" | grep -v ^k8s | xargs docker kill