Перейти к содержанию

Docker

Daemon configuration file

The default location of the configuration file on Linux is /etc/docker/daemon.json.

See docker_daemon.json code in my repo

Documentation

Dockerfile

Defines the contents and startup behavior of a single container.

See Dockerfile code in my repo

.dockerignore

See .dockerignore code in my repo

Bash scripts build, run, push.

See Docker bash script code in my repo

ENTRYPOINT vs CMD

The ENTRYPOINT specifies a command that will always be executed when the container starts. The CMD specifies arguments that will be fed to the ENTRYPOINT.

FROM Ubuntu

# The command that will be run when the container is started.
ENTRYPOINT ["sleep"]

# The argument will be used unless otherwise specified in the command parameters.
CMD ["5"]
# Run without an argument. The value from CMD will be substituted.
docker run ubuntu-sleeper
# sleep 5

# Run with an argument.
docker run ubuntu-sleeper 10
# sleep 10

<none>:<none> images & BuildKit

If images with the name <none>:<none> appear when building the application image, then BuildKit can be useful.

DOCKER_BUILDKIT=1 docker build [OPTIONS] PATH | URL | -
For details, see this GitHub comment.

Security

By default, all processes inside a container run as root. Just run ps aux inside the container to make sure.

To change user:

FROM ubuntu

USER 1000

By default, the Docker container starts with a limited list of Linux capabilities (/usr/include/linux/capability.h) . You can change them like this:

docker run --cap-add MAC_ADMIN ubuntu  # add
docker run --cap-drop KILL ubuntu  # remove
docker run --privileged ubuntu  # enable all privileges

Networking

Documentation

Network drivers:

  1. bridge:
    1. Default bridge network is not recommended for production.
    2. User-defined bridge network is recommended for standalone containers running in production.
  2. host:
    1. Compared to the default bridge mode, the host mode gives significantly better networking performance since it uses the host’s native networking stack whereas the bridge has to go through one level of virtualization through the docker daemon. It is recommended to run containers in this mode when their networking performance is critical, for example, a production Load Balancer or a High Performance Web Server.

Attention

--network="host" gives the container full access to local system services such as D-bus and is therefore considered insecure.

  1. overlay
  2. ipvlan
  3. macvlan
  4. none
  5. Network plugins.
$ docker network ls

NETWORK ID     NAME       DRIVER    SCOPE
80fc08088b73   bridge     bridge    local
54d6b145b19f   host       host      local
7b05eb3b46c9   minikube   bridge    local
2660544dc0e7   none       null      local
docker network inspect bridge

Command-line reference

Documentation

docker attach

Attach local standard input, output, and error streams to a running container:

$ docker attach boilerplate

INFO:     172.17.0.1:41634 - "GET / HTTP/1.1" 200 OK
INFO:     172.17.0.1:41636 - "GET /docs HTTP/1.1" 200 OK
INFO:     172.17.0.1:41636 - "GET /openapi.json HTTP/1.1" 200 OK

docker exec

Run a command in a running container:

docker exec -it boilerplate bash

docker logs

Fetch the logs of a container:

$ docker logs boilerplate

[2022-05-23T10:43:38+0000]: docker_entrypoint.sh: START SCRIPT EXECUTION
[2022-05-23T10:43:38+0000]: Running a Python application inside a Docker container...
...

docker run

1. General form

The basic docker run command takes this form:

docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

2. Detached vs foreground running

-d              : Detached mode: Run container in the background, print new container id
-i              : Keep STDIN open even if not attached
-t              : Allocate a pseudo-tty
-a=[]           : Attach to `STDIN`, `STDOUT` and/or `STDERR`
--sig-proxy=true: Proxy all received signals to the process (non-TTY mode only)

The -dit flags mean to start the container detached (in the background), interactive (with the ability to type into it), and with a TTY (so you can see the input and output).

3. Container identification

--name=<some_name> image[:tag] image[@digest]

4. Network settings

--dns=[]           : Set custom dns servers for the container
--network="bridge" : Connect a container to a network
                      'bridge': create a network stack on the default Docker bridge
                      'none': no networking
                      'container:<name|id>': reuse another container's network stack
                      'host': use the Docker host network stack
                      '<network-name>|<network-id>': connect to a user-defined network
--network-alias=[] : Add network-scoped alias for the container
--add-host=""      : Add a line to /etc/hosts (host:IP)
--mac-address=""   : Sets the container's Ethernet device's MAC address
--ip=""            : Sets the container's Ethernet device's IPv4 address
--ip6=""           : Sets the container's Ethernet device's IPv6 address
--link-local-ip=[] : Sets one or more container's Ethernet device's link local IPv4/IPv6 addresses

Restart policies (--restart)

--restart=<no(default) / on-failure[:max-retries] / always / unless-stopped>

Using the --restart flag on Docker run you can specify a restart policy for how a container should or should not be restarted on exit.

Note

Combining --restart (restart policy) with the --rm (clean up) flag results in an error. On container restart, attached clients are disconnected.

Clean up (--rm)

By default a container’s file system persists even after the container exits. This makes debugging a lot easier (since you can inspect the final state) and you retain all your data by default.

But if you are running short-term foreground processes, these container file systems can really pile up. If instead you’d like Docker to automatically clean up the container and remove the file system when the container exits, you can add the --rm flag:

--rm=false: Automatically remove the container when it exits

docker ps

List containers.

Docs: docker ps

Show all containers (default shows just running):

docker ps -a

Format output:

$ docker ps --filter "label=app_name=boilerplate" --format "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.CreatedAt}}\t{{.RunningFor}}\t{{.Ports}}\t{{.State}}\t{{.Status}}\t{{.Size}}\t{{.Names}}\t{{.Labels}}\t{{.Mounts}}\t{{.Networks}}"
CONTAINER ID   IMAGE                COMMAND                  CREATED AT                      CREATED          PORTS                                           STATE     STATUS                    SIZE                 NAMES         LABELS                                                                              MOUNTS    NETWORKS
f11dd5a9b450   boilerplate:latest   "/bin/bash docker_en…"   2022-05-24 11:06:43 +0500 +05   15 minutes ago   0.0.0.0:50000->50000/tcp, :::50000->50000/tcp   running   Up 15 minutes (healthy)   0B (virtual 262MB)   boilerplate   app_name=boilerplate,author=Viacheslav Kolupaev,stage=build-image,vcs_ref=0b8e769             bridge
Docs: Formatting

docker system

Show docker disk usage:

$ docker system df

TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          5         1         1.404GB   263.1MB (18%)
Containers      1         1         3.099MB   0B (0%)
Local Volumes   1         1         1.397GB   0B (0%)
Build Cache     17        0         169.5MB   169.5MB

Get real time events from the server:

$ docker system events

2022-05-23T16:31:00.251579919+05:00 container exec_create: /bin/sh -c python --version || exit 1 419ff65ed2746b1e13978b257a7f126a7521774ed2865ac8a0137b7c5ed75c1f (author=Viacheslav Kolupaev, execID=1b18cadb58595a1306b5d14ea41ca2fec270917f7f75f31eb675640a23c3d6f4, image=boilerplate:latest, name=boilerplate, stage=build-image)
2022-05-23T16:31:00.251775452+05:00 container exec_start: /bin/sh -c python --version || exit 1 419ff65ed2746b1e13978b257a7f126a7521774ed2865ac8a0137b7c5ed75c1f (author=Viacheslav Kolupaev, execID=1b18cadb58595a1306b5d14ea41ca2fec270917f7f75f31eb675640a23c3d6f4, image=boilerplate:latest, name=boilerplate, stage=build-image)
2022-05-23T16:31:00.355702797+05:00 container exec_die 419ff65ed2746b1e13978b257a7f126a7521774ed2865ac8a0137b7c5ed75c1f (author=Viacheslav Kolupaev, execID=1b18cadb58595a1306b5d14ea41ca2fec270917f7f75f31eb675640a23c3d6f4, exitCode=0, image=boilerplate:latest, name=boilerplate, stage=build-image)

docker inspect

docker inspect my-container
docker inspect -f "{{ .State.StartedAt }}" my-container
docker inspect -f "{{ .RestartCount }}" my-container

docker stats

Display a live stream of container(s) resource usage statistics:

$ docker stats

CONTAINER ID   NAME          CPU %     MEM USAGE / LIMIT   MEM %     NET I/O       BLOCK I/O    PIDS
419ff65ed274   boilerplate   2.78%     61.88MiB / 100MiB   61.88%    4.23kB / 0B   762kB / 0B   7

docker top

Display the running processes of a container:

$ docker top boilerplate

UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
systemd+            18387               18366               0                   15:43               ?                   00:00:00            /bin/bash docker_entrypoint.sh
systemd+            18426               18387               0                   15:43               ?                   00:00:11            python3 src/boilerplate/server.py
systemd+            18431               18426               0                   15:43               ?                   00:00:00            /opt/venv/bin/python3 -B -c from multiprocessing.resource_tracker import main;main(4)
systemd+            18432               18426               0                   15:43               ?                   00:00:06            /opt/venv/bin/python3 -B -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=7) --multiprocessing-fork
systemd+            33451               18366               0                   16:12               pts/0               00:00:00            /bin/sh -c [ -e /bin/bash ] && (/bin/bash || exit 0) || /bin/sh
systemd+            33457               33451               0                   16:12               pts/0               00:00:00            /bin/sh -c [ -e /bin/bash ] && (/bin/bash || exit 0) || /bin/sh
systemd+            33458               33457               0                   16:12               pts/0               00:00:00            /bin/bash

docker manifest

$ docker manifest inspect --verbose python:3.10.4-slim

[
        {
                "Ref": "docker.io/library/python:3.10.4-slim@sha256:b4473ae501f273874a4379f489ea0270dd4dd479d26c72d6d520fb4e717493c6",
                "Descriptor": {
                        "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
                        "digest": "sha256:b4473ae501f273874a4379f489ea0270dd4dd479d26c72d6d520fb4e717493c6",
                        "size": 1370,
                        "platform": {
                                "architecture": "amd64",
                                "os": "linux"
                        }
                },
...

What's next?

  1. Found this article helpful? Share it and help spread the knowledge!
  2. Found a mistake or have ideas 💡 on what and how I can improve? Message me on Telegram.
  3. Want to know more about me? Read here.