How to use docker stop

When you're working with Docker and need to stop a running container, the docker stop
command is your go-to tool. It's straightforward to use, but there are some options you can tweak to fit your needs. Let's walk through how to use this command and explore its options with some examples.
First off, the basic way to stop a container is simple. You just type:
docker stop [container_id_or_name]
For instance, if you have a container running with the name my_container
, you would stop it like this:
docker stop my_container
This command sends a SIGTERM
signal to the container's main process, which tells it to stop. After a brief grace period, if the process hasn't stopped yet, Docker will send a SIGKILL
signal to force it to stop. This grace period is usually set to 10 seconds for Linux containers and 30 seconds for Windows containers, but you can change both the signal and the grace period.
Changing the Stop Signal
If you want to use a different signal to stop your container, you can use the --signal
or -s
option. For example, if you want to use SIGKILL
immediately instead of SIGTERM
, you could do:
docker stop --signal SIGKILL my_container
You can also use the signal number instead of the name. For SIGKILL
, which is signal number 9, the command would look like this:
docker stop --signal 9 my_container
Remember, the default signal can be changed in the Dockerfile with the STOPSIGNAL
instruction or when you start the container with the --stop-signal
option.
Setting a Custom Timeout
Sometimes, you might need more or less time for your container to stop gracefully. You can adjust this with the --time
or -t
option. For example, to give your container 30 seconds to stop instead of the default, you would use:
docker stop --time 30 my_container
If you want to wait indefinitely for the container to stop without forcing it with SIGKILL
, you can set the time to -1
:
docker stop --time -1 my_container
This tells Docker to keep waiting until the container stops on its own.
Putting It All Together
Let's say you have a container named web_server
and you want to stop it with SIGINT
(which is signal number 2) and give it 60 seconds to stop. Your command would be:
docker stop --signal SIGINT --time 60 web_server
This command sends SIGINT
to your web_server
container and gives it a full minute to shut down properly before Docker steps in with a SIGKILL
.
Using docker stop
with these options gives you the flexibility to manage your containers the way that works best for your applications. Whether you need to stop a container quickly or give it time to finish up tasks, you can tailor the command to your needs.