Docker cheatsheet

Monday, Aug 16 2021

Here’s how to perform some common tasks with Docker.

Clean up

Remove all stopped containers:

docker container prune

This might remove containers you want to re-use, but if you build your containers right they should be pretty stateless, so you can still spin one up if needed.

docker image prune

Deletes images not referenced by anything else. Hopefully you’ve got a Dockerfile somewhere to rebuild the images you’ve deleted by accident.

Sometimes a container behaves unexpectedly. As a quick check before logging in, you can do.

docker container top

This displays the processes inside a container. Useful if you wonder whether what was supposed to start started at all.

Ideally, your services should always log to standard out. That way you don’t have to bother with different logging configurations. Any init system worth its salt can redirect the logs to an appropriate file.

You can see the logs with

docker container logs <container_name>

Another trick to avoid having to log in!

Docker names containers automatically, but you can pick your own names with

docker run <image_name> --name <container_name>

Remember that run always starts a new container. If you want to run a container you stopped, run

docker start <container_name>

Restarting an existing container is mainly useful to save some seconds at launch. If your containers are stateless, there should be no difference between two containers build from the same image.

Manage multiple containers

When you run multiple containers with docker-compose, sometimes containers can’t connect to each other. It’s interesting to inspect the docker network to find out why. First list the networks:

docker network ls

On Linux, you’ll always see bridge, host and none. After that, you’ll see any custom network.

Then get more detailed information

docker inspect <network_name>.

Log into a container

docker attach won’t always work if the process you started is not interactive. Try to execute a shell inside the container with

docker exec -it <container name> sh