1.3. Container Lifecycle
Detached containers
So far, we’ve been running containers with our terminal attached to their standard input (stdin). In practice, however, most containers run in the background as detached processes.
Running a Docker container in “detached” mode (background) can be done with -d:
docker run -e MARIADB_ROOT_PASSWORD=my-secret-pw -d mariadb:12.0
Now, instead of seeing container logs, only the container ID is displayed. Verify by listing running containers:
docker ps
Now that we have (too) many database containers running, we need to know how to delete them:
Deleting a container
There are two ways to stop a container, we start with the recommended way.
You first have to stop the container using its name or ID. You see both in your terminal when you executed docker ps
To stop a container use the command:
docker stop <container>
After that, check the new state with
docker ps
This should show only one container running:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
699e82ed8f1f mariadb:12.0 "docker-entrypoint..." 9 minutes ago Up 9 minutes 3306/tcp jolly_bardeen
We just exited the container “gracefully”, but as an alternative you can also kill a container with the docker kill <container> command. This stops the container immediately by using the KILL signal.
You may recognize that the container upbeat_blackwell is not present in the container list anymore. That is because docker ps only shows running containers, but as always you have a parameter that helps:
docker ps --all
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
699e82ed8f1f mariadb:12.0 "docker-entrypoint.s…" 4 minutes ago Up 4 minutes 3306/tcp jolly_bardeen
7cb31f821233 mariadb "docker-entrypoint.s…" 10 minutes ago Exited (0) 32 seconds ago upbeat_blackwell
8f500e827376 mariadb:12.0 "docker-entrypoint.s…" 12 minutes ago Exited (1) 12 minutes ago confident_wright
01417368d5b6 hello-world:linux "/hello" 13 minutes ago Exited (0) 13 minutes ago vigorous_dijkstra
321f2265b76e hello-world "/hello" 14 minutes ago Exited (0) 14 minutes ago stoic_shockley
67d79f95c712 hello-world "/hello" About an hour ago Exited (0) About an hour ago upbeat_boyd
Now that the upbeat_blackwell container is stopped delete it:
docker rm <container>
Now the container has disappeared from the list:
docker ps --all
You can also delete the other stopped containers if you like.
Note
It is a good idea to delete unused containers to save disk space.🤔 Where do these strange names of the containers come from?
The CONTAINER ID and NAME values are unique identifiers for a container. If we don’t provide one, docker will come up with a unique name.