Drawing of a whale

Docker Tips

I’ve been working with Docker the past few months and all-in-all, I’ve been very pleased with the quality of the documentation. But, as with any other tool, there are always a few tricks to pick up, particularly when trying to script things out for an automated build or deployment. I’ve listed some of the more useful ones below and will update this post as I learn new ones.

Note: These are mainly oriented around running Docker in a Linux environment, as that’s where I’m currently using it.

How do I stop typing sudo all the time?

Docker runs as root, so when you’re working with an out-of-the-box installation, the docker command must be preceded by sudo. Since it may not be desirable for all Docker users to be able to execute commands as root, the installation creates a docker group. Members of the group may execute docker commands without elevated privileges.

To add users to the group, execute the command:
sudo usermod -aG docker <username>

How do I remove all stopped containers?

When a container is stopped, it remains loaded. You can remove it by issuing the command docker rm container_name, but that can be a hassle if you have a large number of containers loaded and they all have random names (a frequent occurrence when you’re first learning Docker).

You can remove all stopped containers by executing the command:
docker rm $(docker ps --quiet -a --filter status=exited)

(The –filter option prevents errors from attempting to remove containers which are currently running.)

You can also cause your containers to remove themselves automatically by including the –rm option on the docker run command line.

How do I know if a container is running?

To determine if a named container (e.g. “clever_leakey”) is currently running

containerID=$(docker ps --quiet --filter status=running --filter name=clever_leakey)

if $containerID is non-null, the named container is running. If it’s null, then the container is no longer running.

Do note however that there are other non-running states, e.g. paused, which will also return a null containerID for this test. As an alternative, to find only the containers which are stopped, use status=exited.

If the docker run command includes the –rm option, the container will be removed from memory.

(Image via openclipart under Creative Commans CC0 1.0 Universal)