Listing containers

As we continue to run containers over time, we get a lot of them in our system. To find out what is currently running on our host, we can use the container list command as follows:

$ docker container ls

This will list all currently-running containers. Such a list might look similar to this:

By default, Docker outputs seven columns with the following meanings:

Column Description
CONTAINER ID The unique ID of the container. It is a SHA-256.
IMAGE The name of the container image from which this container is instantiated.
COMMAND The command that is used to run the main process in the container.
CREATED The date and time when the container was created.
STATUS The status of the container (created, restarting, running, removing, paused, exited, or dead).
PORTS The list of container ports that have been mapped to the host.
NAMES The name assigned to this container (multiple names are possible).

If we want to list not only the currently running containers but all containers that are defined on our system, then we can use the command-line parameter -a or –all as follows:

$ docker container ls -a

This will list containers in any state, such as created, running, or exited.

Sometimes, we want to just list the IDs of all containers. For this, we have the parameter -q(quietly):

$ docker container ls -q
Stopping and starting containers

Sometimes, we want to (temporarily) stop a running container. Let’s try this out with the quotes container we used previously. Run the container again with this command:

$ docker container run -d –name my-container alpine /bin/sh -c “while true; do echo ‘This is my container!!’; sleep 1; done”

Now, if we want to stop this container then we can do so by issuing this command:

$ docker container stop my-container

When you try to stop the quotes 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.

If a container is stopped, it can be started again using the docker container start command. Let’s do this with our my-container container.

$ docker container start my-container

Lean back and take a deep breath. Then, try to find out what the preceding command does. Don’t read any further until you find the answer or give up.

Happy learning!!

Leave a Reply

Your email address will not be published. Required fields are marked *