Docker Cheat Sheet

Docker Cheat Sheet
Photo by Ian Taylor / Unsplash

We will start this article by understanding the Docker architecture and the main aspects, then we will continue with the important commands required for the most common Docker operations, such as: build, push, run, ship, clean up, container interaction.

Docker Architecture

Docker architecture consists of five main entities, namely: registry, image, container, daemon and client.

  • Registry: hosts public and official images, most popular being Docker HUB
  • Image: a read-only template that contains a set of instructions for creating a container.
  • Container: it is basically an instance of an image. Multiple containers can exist for a single image.
  • Daemon: creates, runs and monitors containers, along with building and storing images
  • Client: talks to Docker daemon

Build

The build command is used, well, for building images from a Dockerfile.

  • To build an image and tag it:
    docker build -t myimage:mytag
  • To list local images:
    docker images ls -a
  • To remove an image from the store:
    docker rmi myimage:mytag

Run

The run command is used for creating a container from a specific image.

  • To create a container:
    docker run --name container_name docker_image:tag
    Common flags:
    • -d: to detach the container on start
    • -p: to publish a container port (map it to a host port)
    • -v: to define and share a volume between the host and the container.
    • -rm: to remove the container once it stops

Ship

The Docker Registry is a stateless application that stores and lets you distribute Docker images.

Commands

  • Login to a registry
    docker login my.registry.com
  • To pull an image
    docker pull image:tag
  • To retag a local image
    docker tag myimage:mytag mynewimage:mynewtag
  • To push an image to the registry
    docker image push my.registry.com/mynamespace/myimage:mytag

Cleanup

To prevent wasting resources, we must know how to clean up.

  • To remove unused image:
    docker image prune
  • To prune the entire system:
    docker system prune
  • To kill all running containers:
    docker kill $(docker ps -q)
  • To delete all stopped containers
    docker rm $(docker ps -aq)
  • To delete all images:
    docker rmi $(docker images -q)

Container interaction

This is mostly used for debugging purposes. Please remember that changes done to a container will be lost if the container is "re-created".

  • To get an interactive shell
    docker exec -it container_name command
  • To follow container logs:
    docker logs -tf container_name
  • To save a running container as an image:
    docker commit -m "message" -a "author" container_name namespace/image:tag
Mastodon Romania