Skip to content

Stop all running containers in Docker

Posted in Cli, Docker

By Dušan Dželebdžić

Photo by John Matychuk on Unsplash
Photo by John Matychuk on Unsplash

There's no docker stop all. The command you actually want is:

docker stop $(docker ps -q)

That's the whole trick. If you want to know why it works, what the fish shell version looks like, and when to reach for kill instead, read on.

Why you'd want this

Sometimes you start containers from your IDE and forget to stop them before switching projects. Or maybe you're done with your work (you lucky, you!) and don't want to waste memory or CPU cycles on services you aren't using. Either way, something is hogging the ports you need, eating your RAM and battery, and the IDE that started it all is long gone. Time for the terminal.

Let's see what we're up against. What does docker ps say?

$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9c07b6375e0e my_project_tunnel "/bin/sh -c 'rm -rf …" 4 weeks ago Up 3 seconds 0.0.0.0:8062->8062/tcp my_project_tunnel_1
91b757beda05 my_project_web "docker-php-entrypoi…" 4 weeks ago Up 2 seconds 0.0.0.0:8000->80/tcp my_project_web_1
245f7e35f4f3 mysql:5.7 "docker-entrypoint.s…" 3 months ago Up 3 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp my_project_db_1
77bc948bb148 mailhog/mailhog "MailHog" 3 months ago Up 3 seconds 0.0.0.0:1025->1025/tcp, 0.0.0.0:8025->8025/tcp my_project_mailhog_1

Four containers. Docker's answer, out of the box, is four separate commands:

$ docker stop 9c07b6375e0e
$ docker stop 91b757beda05
$ docker stop 245f7e35f4f3
$ docker stop 77bc948bb148

Quite a mouthful. You can shave it down by typing only the first few characters of each container ID, but the real fix is to make the shell do the work: run docker ps, grab the container IDs, and feed them straight into docker stop.

Step 1: Get the running container IDs

Run docker ps with the -q flag and it returns only container IDs. Look!

$ docker ps -q

9c07b6375e0e
91b757beda05
245f7e35f4f3
77bc948bb148

Many tutorials will tell you to add the -a flag, making the full command docker ps -aq. Here, -a is redundant. According to the docker ps documentation, omitting -a returns only running containers, which is exactly what we need. Stopped containers don't need stopping.

Step 2: Feed them to docker stop

Almost every shell lets you run a command in a subshell, capture its output, and use it as arguments for another command. This syntax works in bash and zsh:

docker stop $(docker ps -q)

And this works in fish:

docker stop (docker ps -q)

You can use kill instead of stop for a faster shutdown. It saves a few seconds, but not every service appreciates being killed; databases in particular would rather get a polite stop and a chance to flush to disk. If the containers are throwaway dev services, kill away.