
Stopping and starting containers
Sometimes, we want to (temporarily) stop a running container. Let's try this out with the trivia container we used previously:
- Run the container again with this command:
$ docker container run -d --name trivia fundamentalsofdocker/trivia:ed2
- Now, if we want to stop this container, then we can do so by issuing this command:
$ docker container stop trivia
When you try to stop the trivia container, you will probably note that it takes a while until this command is executed. To be precise, it takes about 10 seconds. Why is this the case?
Docker sends a Linux SIGTERM signal to the main process running inside the container. If the process doesn't react to this signal and terminate itself, Docker waits for 10 seconds and then sends SIGKILL, which will kill the process forcefully and terminate the container.
In the preceding command, we have used the name of the container to specify which container we want to stop. But we could have also used the container ID instead.
How do we get the ID of a container? There are several ways of doing so. The manual approach is to list all running containers and find the one that we're looking for in the list. From there, we copy its ID. A more automated way is to use some shell scripting and environment variables. If, for example, we want to get the ID of the trivia container, we can use this expression:
$ export CONTAINER_ID=$(docker container ls -a | grep trivia | awk '{print $1}')
Now, instead of using the container name, we can use the $CONTAINER_ID variable in our expression:
$ docker container stop $CONTAINER_ID
Once we have stopped the container, its status changes to Exited.
If a container is stopped, it can be started again using the docker container start command. Let's do this with our trivia container. It is good to have it running again, as we'll need it in the subsequent sections of this chapter:
$ docker container start trivia
It is now time to discuss what to do with stopped containers that we don't need anymore.