tl;dr: scroll to the bottom
Stop all containers
So, if there's a command which will start or stop whatever we need, what's the point of this article? Good question!
Sometimes, you start containers from your IDE, and forget to stop them before you switch projects. Or, maybe you're done with your work (you lucky, you!) and don't want to waste any memory or CPU cycles on the services which you aren't using. Can't really say, I'm not you.
You've got something hogging the ports you need, eating up your RAM and battery, IDE UI is gone, what do you do? Time to go to your terminal. Surely there's a command like docker stop all which will stop everything? Nope. You have to stop your containers, one by one. 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
Cool, so we just need to stop (or kill) those four containers. So all you need to do is type these four commands:
$ docker stop 9c07b6375e0e
$ docker stop 91b757beda05
$ docker stop 245f7e35f4f3
$ docker stop 77bc948bb148
Quite a mouthful. You can speed it up a bit by typing only first few letters of the container ID, or use
docker kill instead of
docker stop (most of the services won't mind). It would be great if we could run PS, then somehow grab container IDs and pass them to the
docker stop command. Well, today is our lucky day, because that's exactly what we're going to do!
Step 1: Get running container IDs
If you run
docker ps with a
-q flag, it will return only container IDs. Look!
$ docker ps -q
Many tutorials on this subject will tell you to add the
-a flag, so the full command would be
docker ps -aq. In this case, the
-a flag is redundant. According to the docker ps documentation if you omit the
-a flag, the command will return only running containers - which is, in our case, exactly what we need. We only want to stop running containers.
Alrighty, now let's pass that to the
stop command. Almost every shell lets you to run a command in a subshell, then capture its output and use that as a parameter for another command. This syntax works well 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 faster shutdown, it might save you a few seconds, but make sure that you don't break anything. Not every service appreciates being killed.
Previous: Why Docker?