# Docker Note

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/docker-note/>). I am continuously working to improve the translation.

## Preface

Docker—I've learned it, read about it, and used it, but all in a scattered way. This time I've decided to go through it systematically.

Let me sort out the things I'm not so familiar with:

- Docker Compose
- Docker networking

This time I'll focus on filling in these two areas.

The main thread of my study is the book *"[Docker 从入门到实践](https://yeasy.gitbook.io/docker_practice)"* (Docker: From Beginner to Practitioner), supplemented by documentation I may read and tutorial videos I may watch.

## Introduction to Docker

- A lightweight virtualization technology
- Applications and their dependent environments can be packaged into a standardized unit, running with a high degree of consistency in environments that meet the prerequisites of architecture, kernel capabilities, and external dependencies.

### Differences from Virtual Machines

Traditional virtual machines:

- Virtualize a complete set of hardware, on top of which a full OS runs

Docker containers:

- Containers run on the **host's kernel**; containers have no kernel of their own and no hardware virtualization

| Feature | Docker Container | Traditional VM |
| ------------ | ------------ | ---------- |
| **Startup speed** | Seconds | Minutes |
| **Resource usage** | MB level | GB level |
| **Performance** | Close to native | Noticeable overhead |
| **Isolation level** | Process-level isolation | Full isolation |
| **Number per machine** | Can run thousands | Usually dozens |

### Advantages of Docker

- Build once, run anywhere
- Environment consistency
- Fast startup
    - Great for CI/CD and elastic scaling
- Higher resource efficiency than virtual machines
- Continuous delivery and deployment
    - Fits the DevOps workflow: code commit,
- Easy migration
- The cornerstone of microservice architecture

## Docker Concepts

### Images

- A read-only **template** containing everything needed to run an application.

    > [!important]
    >
    > Images are **read-only, contain no dynamic data, and their content does not change after being built**.

- One image can create multiple containers, while the image itself remains unchanged.

#### Images and the OS

An OS is divided into the **kernel** and **user space**:

```mermaid
flowchart TD
    subgraph UserSpace ["用户空间"]
        direction TB
        App["应用程序、工具、库、配置文件...<br/>（这部分被打包成 Docker 镜像）"]
    end

    subgraph KernelSpace ["Linux 内核"]
        direction TB
        Kernel["容器共享宿主机的内核"]
    end

    UserSpace --- KernelSpace
```

A Docker container: essentially its own `root` filesystem, running mounted under the OS kernel, **without containing its own kernel**.

#### Layered Storage

It is divided into many layers, with each layer built on top of the previous one.

This is reflected in the different lines of a `Dockerfile`.

Here's a **pitfall-style** example to understand this:

```dockerfile
## 错误示范 ❌

FROM ubuntu:24.04
RUN apt-get update
RUN apt-get install -y build-essential  # 安装编译工具（约 200MB）
RUN make && make install                  # 编译应用
RUN apt-get remove build-essential        # 试图删除编译工具

## 结果：镜像仍然包含 200MB 的编译工具！
```

```dockerfile
## 正确做法 ✅

FROM ubuntu:24.04
RUN apt-get update && \
    apt-get install -y build-essential && \
    make && make install && \
    apt-get remove -y build-essential && \
    apt-get autoremove -y && \
    rm -rf /var/lib/apt/lists/*

## 在同一层完成安装、使用、清理
```

#### Image Identifiers

Multiple ways to identify an image:

- **Image name and tag**:

    - Format: `[仓库地址/]仓库名[:标签]`, but there are also abbreviated forms, for example:
    - Full format: `registry.example.com/myproject/myapp:v1.2.3`
    - Shorthand, where the default registry address is the official Docker Hub: `nginx:1.28`
    - Omitting the tag, `nginx`, is equivalent to `nginx:latest`

- **Image ID**

    ```bash
    $ docker images
    REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
    nginx        latest    a6bd71f48f68   2 weeks ago    187MB
    ubuntu       24.04     ca2b0f26964c   3 weeks ago    78.1MB
    ```

    The `IMAGE ID` here is exactly that.

- **Digest**

    - digest
    - A unique identifier of the image's content
    - **Recommended to use this instead of tags**


### Containers

- **A container is a running instance of an image.**
- If an image is compared to a program, then a container is a process.
- In OOP terms: **the image is the Class, the container is the Instance**.

Characteristics of containers:

- One image can create multiple containers
- Each container is independent of the others and does not affect them
- Containers can be created, started, stopped, deleted, and paused

#### The Essence of Containers

**The essence of a container is a special process**. But compared to an ordinary process, it has the following traits:

- **Independent process space**: a container cannot see other processes on the host.
- **Independent network environment**: in the default network mode, a container usually has its own network namespace and can be assigned an independent IP; this does not apply when using modes like `host` or `container:`.
- **Independent filesystem**: a container has its own root directory.
- **Independent user space**: since I don't really understand Linux user space, this is a TODO for now.

#### The Container Storage Layer

**Image layers + container layer**: suppose the image a container is based on has $N$ layers; then the container builds an $N+1$-th layer, which is writable and serves as the container storage layer.

**Copy-on-Write**:

When a container needs to modify a file in an image layer:

1. Docker **copies** the file to the container storage layer
2. The modification is made in the container layer
3. The original image layer remains unchanged

**Lifecycle of the container storage layer**: bound to the container; deleting the container also deletes the container storage layer.

**Data persistence paradigm**: Docker best practices hold that the container storage layer should remain **stateless**; if data needs to be kept, data volumes / bind mounts should be used.

#### Container Lifecycle

Existing states:

- Created
- Running
- Paused
- Stopped
- Deleted

#### Containers and Processes

The container's lifecycle = the lifecycle of the main process (PID 1)

Run:

```bash
docker run ubuntu
```

The container exits immediately: the program started by default does no continuous work, so PID 1 ends quickly. Instead, use:

```bash
docker run -it ubuntu bash
```

Then `bash` becomes PID 1; as long as you don't exit this shell, the container keeps running.

#### How Container Isolation Is Achieved

Using Linux's Namespace mechanism.

### Docker Registry

#### Core Concepts

**A Docker Registry is a service that stores and distributes Docker images, similar to GitHub for code or npm for package management.**

A Docker Registry can contain multiple Repositories, and each Repository can contain multiple Tags.

This is why the full name of an image is `[registry 地址/][用户名/]仓库名[:标签]`.

> [!note]
>
> If no Registry address is specified, Docker Hub is used by default. If no tag is specified, `latest` is used by default.

#### Public Registry Services

[Docker Hub](https://hub.docker.com/) is the largest public Registry and also Docker's default Registry.

- Free accounts can create public repositories
- Free personal accounts can create 1 private repository; higher tiers support more private repositories

There are also other image sources such as GitHub Container Registry, Google's, Alibaba's, Tencent's, and so on.

You can configure a **registry mirror** to speed things up:

```json
// /etc/docker/daemon.json
{
  "registry-mirrors": [
    "https://your-accelerator-url"
  ]
}
```

#### Private Registries

Cloud providers offer such services; you can look into them yourself, such as Alibaba Cloud ACR, Tencent Cloud TCR, AWS ECR, etc.

Sometimes you need to use `docker login` to log in to a Docker Registry.

#### Pushing and Pulling Images

```plaintext
Developer Machine             Registry                    Production Server
     │                           │                             │
     │  docker build             │                             │
     │  Build image              │                             │
     │                           │                             │
     │  docker push ─────────────▶                             │
     │  Push image               │  Store image                │
     │                           │                             │
     │                           │  ◀───────────── docker pull │
     │                           │                  Pull image │
     │                           │                             │
     │                           │                  docker run │
     │                           │                  Run container │
```
## Working with Images

### Obtaining Images

```bash
## 完整格式

$ docker pull docker.io/library/ubuntu:24.04

## 省略 Registry（默认 Docker Hub）

$ docker pull library/ubuntu:24.04

## 省略 library（官方镜像）

$ docker pull ubuntu:24.04

## 省略标签（默认 latest）

$ docker pull ubuntu

## 拉取第三方镜像

$ docker pull bitnami/redis:latest

## 从其他 Registry 拉取

$ docker pull ghcr.io/username/myapp:v1.0
```

#### Parsing the Download Output

```bash
$ docker pull ubuntu:24.04
24.04: Pulling from library/ubuntu
92dc2a97ff99: Pull complete
be13a9d27eb8: Pull complete
c8299583700a: Pull complete
Digest: sha256:4bc3ae6596938cb0d9e5ac51a1152ec9dcac2a1c50829c74abd9c4361e321b26
Status: Downloaded newer image for ubuntu:24.04
docker.io/library/ubuntu:24.04
```

| Output | Meaning |
| -------------------------------- | ----------------------------------- |
| `Pulling from library/ubuntu`    | Pulling from the official ubuntu repository |
| `92dc2a97ff99: Pull complete`    | Download status of each layer (showing the first 12 characters of the layer ID) |
| `Digest: sha256:...`             | The unique digest of the image's content |
| `docker.io/library/ubuntu:24.04` | The full name of the image |

As you can see, images are downloaded **layer by layer**.

> [!tip]
>
> **For `pull`**:
>
> - `--quiet -q` performs a silent pull
> - `--platform` can specify the platform architecture

#### About Digests

**Viewing image digests**:

```bash
$ docker images --digests ubuntu
REPOSITORY   TAG     DIGEST                                                                    IMAGE ID
ubuntu       24.04   sha256:4bc3ae6596938cb0d9e5ac51a1152ec9dcac2a1c50829c74abd9c4361e321b26   ca2b0f26964c
```

Then **pull using the digest**:

```bash
$ docker pull ubuntu@sha256:4bc3ae6596938cb0d9e5ac51a1152ec9dcac2a1c50829c74abd9c4361e321b26
```

> [!tip]
>
> In production, use digests rather than tags, because tags can be overwritten, while digests are immutable.

#### Solutions for Insufficient Disk Space

```bash
## 清理未使用的镜像

$ docker image prune

## 清理所有未使用资源

$ docker system prune
```

### Inspecting Images

#### Basic Usage

```bash
$ docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
redis        latest    5f515359c7f8   5 days ago     183MB
nginx        latest    05a60462f8ba   5 days ago     181MB
ubuntu       24.04     329ed837d508   3 days ago     78MB
ubuntu       noble     329ed837d508   3 days ago     78MB
```

> [!note]
>
> About `ubuntu:24.04` and `ubuntu:noble`:
>
> `ubuntu:24.04` is the specific version number, while `ubuntu:noble` is the release codename.
>
> They share the same `IMAGE ID`; they are different tags of the same image and occupy only one copy of storage.

> [!tip]
>
> Actually the base command is `docker image`, and `docker images` is an alias for `docker image ls`.

#### Understanding Image Sizes

**Local size vs. the size shown on Docker Hub**:

- The former is the actual size after local extraction
- The latter is the compressed size for network transfer

**Actual disk usage**:

- Because images are stored in layers, different images share different layers
- Therefore $\sum{\text{size}} \gt \text{实际磁盘占用}$.

**How to check actual space usage**:

```bash
$ docker system df
TYPE            TOTAL   ACTIVE   SIZE      RECLAIMABLE
Images          15      3        2.5GB     1.8GB (72%)
Containers      5       2        100MB     80MB (80%)
Local Volumes   8       2        500MB     400MB (80%)
Build Cache     0       0        0B        0B
```

#### Finding Specific Images (Filtering Images)

**Filter by image name**:

```bash
$ docker images ubuntu

$ docker images ubuntu:24.04
```

**Using filters**:

`--filter -f`

There is a series of filter conditions; I feel like even if I memorized them I'd forget—just knowing they exist is enough.

#### Dangling Images

Images whose repository name and tag both show as `<none>`.

**How they arise**:

- **Image rebuilds**: a new image takes over the old image's tag, and the old image's tag is removed
- **docker pull updates**: when pulling a newer version, the old version loses its tag (`latest`)

**How to handle them**:

- List: `docker images -f dangling=true`
- Delete: `docker image prune`

#### Intermediate Layer Images

`docker images` only lists top-level images; to view intermediate images, use `docker images -a`.

> [!important]
>
> **You never need to manually delete intermediate layer images**.

#### Formatted Output

Mainly about combining commands together.

**Output only IDs**: `docker images -q`

Example: delete all redis images: `docker rmi $(docker images -q redis)`

> [!note]
>
> Actually, for personal development, I think managing things with the Docker Desktop GUI is more convenient.
>
> For an Agent, these things can simply be described in natural language.

**Show digests**: `docker images --digests`

### Removing Images

#### Basic Usage

```bash
$ docker image rm [选项] <镜像1> [<镜像2> ...]
```

> [!tip]
>
> `docker rmi` is shorthand for `docker image rm`; the two are equivalent.

#### Ways to Identify an Image

- Short ID (the first few characters that can identify it)
- Full ID
- Image name:tag
- Image digest
    - The most precise, suitable for CI/CD scenarios

#### Output When Removing an Image

```bash
$ docker rmi redis:alpine
Untagged: redis:alpine
Untagged: redis@sha256:f1ed3708f538b537eb9c2a7dd50dc90a706f7debd7e1196c9264edeea521a86d
Deleted: sha256:501ad78535f015d88872e13fa87a828425117e3d28075d0c117932b05bf189b7
Deleted: sha256:96167737e29ca8e9d74982ef2a0dda76ed7b430da55e321c071f0dbff8c2899b
Deleted: sha256:32770d1dcf835f192cafd6b9263b7b597a1778a403a109e2cc2ee866f74adf23
```

- **Untagged**: removes the image's tag
- **Deleted**: deletes the image's storage layers

The deletion process:

First, the tags pointing to the image are checked and untagged one by one; then the image's layers are deleted one by one—layers still in use are kept, unused ones are deleted.

#### Bulk Deletion

Let me roughly describe in natural language what can be done:

- Delete all dangling images: `docker image prune`
- Delete images unused for a period of time: `docker image prune -a --filter "until=24h"`
- Delete by conditions, for example:
    - Delete all redis images
    - Delete images created before a certain point in time
    - Delete images before a certain version number

#### Reasons Deletion Can Fail

- A container depends on this image
- The image is depended on by other images as an intermediate layer
- Multiple tags point to the same image, e.g., ubuntu's `24.04` and `latest` both point to the same `IMAGE ID`

#### Cleanup Strategies

**Development environment**:

- Periodically clean up dangling images
- Clean up unused resources: `docker system prune -a`

**CI/CD**:

- Keep only recently used images (i.e., delete all images unused for a period of time in one go)

**Checking space usage**:

- `docker system df`

### Using `docker commit`

Solidifying a container's current changes on the filesystem into a new Docker image.

Command format:

```bash
$ docker commit [OPTIONS] 容器名或容器ID 新镜像名[:标签]
```

For example, after entering a container and modifying some content in its filesystem,

run

```bash
docker commit dev my-ubuntu:v1
```

What this actually does:

The original image's read-only layers + the dev container's writable layer -> converted into new read-only image layers -> a new image

The principle is that the new image continues to reuse the original image's layers, with one additional layer added to store the filesystem changes this container made relative to the original image.

#### Drawbacks

Images customized with `docker commit` have the following problems:

- Running commands will indiscriminately modify a bunch of unrelated files, which can be seen via `docker diff webserver`;
- All operations on the image are black-box operations;
- The number of layers will balloon.

### Customizing Images with a `Dockerfile`

This solves the problems described above.

A `Dockerfile` is a text file containing a series of **instructions**:

- Instructions that modify the filesystem usually create new layers;
- Instructions like `LABEL` and `CMD` that only modify image metadata do not add filesystem layers.

#### Creating a `Dockerfile`

The more detailed commands will be covered in a separate section later.

> [!note]
>
> Though I don't think that's really necessary—knowing the basic concepts matters most.

**`FROM` specifies the base image**:

Customizing an image means taking an existing image as a base and building on top of it. Hence the need for `FROM` to specify the base image.

Besides choosing an existing image as the base image, Docker also has a special image called `scratch`. This image is a virtual concept that doesn't actually exist; it represents a blank image.

```docker
FROM scratch
...
```

If you use `scratch` as the base image, it means you're not basing yourself on any image, and the instructions you write next will form the first layer of the image.

It's not uncommon to copy an executable directly into an image without basing it on any OS. For statically compiled programs on Linux, no runtime support from an operating system is needed—everything required is already in the executable—so using `FROM scratch` directly makes the image much smaller. Many applications developed with the [Go language](https://golang.google.cn/) use this approach to build images, which is one reason some people consider Go a language particularly well suited to containerized microservice architectures.

**`RUN` executes command-line commands**:

- Shell format: `RUN <命令>`
- Exec format: `RUN ["可执行文件", "参数1", "参数2"]`

> [!caution]
>
> Every `RUN` instruction produces a new image layer. To reduce image size and layer count, we usually combine multiple commands into a single `RUN` instruction.

#### Building Images

```bash
docker build [选项] <上下文路径/URL/->
```

The output after running it is fairly self-explanatory; there's no need to write it out separately to memorize.

#### The Image Build Context

As for what a **context path** is: the set of files the builder can access.

For example, a `Dockerfile` will contain `COPY` and `RUN` instructions; suppose you have this:

```dockerfile
COPY ./package.json /app/
```

What gets copied here is the `package.json` in the **context** directory.

But if you write:

```dockerfile
COPY ../package.json /app
```

The `..` here is **out of bounds**—the builder cannot read host files outside the context.

From this we can see that **the context has nothing to do with the directory where the `Dockerfile` resides.** In theory you could specify the context directly as `/`, but BuildKit's visible context would be so large that the build would become slow or even fail.

The so-called `.dockerignore` file (usually placed in the project root, at the same level as the `Dockerfile`, using the same Glob syntax as `.gitignore`) exists precisely to exclude files you don't want sent to the Docker engine during the build.

#### Other Uses of `docker build`

- Build from a Git repo
- Build from a given archive
- Build by reading the Dockerfile from standard input: `cat Dockerfile | docker build -`

## Working with Containers

### Starting

There are two ways to start a container:

* **Create and start**: create a new container from an image with `docker run`
* **Restart**: run an already-stopped container again with `docker start`

Since Docker containers are extremely lightweight, in practice people often delete and recreate containers on the fly rather than repeatedly restarting the same container.

#### Create and Start

```bash
docker run [选项] 镜像 [命令] [参数...]
```

**Interactive container**:

```bash
$ docker run -it ubuntu:24.04 /bin/bash
root@af8bae53bdd3:/#
```

| Flag | Effect |
| ----- | ------------------------------------- |
| `-i`  | Keeps standard input (stdin) open, allowing input |
| `-t`  | Allocates a pseudo-terminal (pseudo-TTY), providing a terminal interface |
| `-it` | The two combined, giving an interactive terminal |

#### Startup Options

| Option | Description | Example |
| -------- | ------------------ | -------------------------------------- |
| `-d`     | Run in the background (detach) | `docker run -d nginx:latest` |
| `-it`    | Interactive terminal | `docker run -it ubuntu:24.04 bash` |
| `--name` | Assign a container name | `docker run --name myapp nginx:latest` |
| `--rm`   | Automatically delete the container on exit | `docker run --rm ubuntu:24.04 echo hi` |

**Port mapping**:

```bash
## 将容器的 80 端口映射到宿主机的 8080 端口

$ docker run -d -p 8080:80 nginx:latest

## 只绑定到 localhost

$ docker run -d -p 127.0.0.1:8080:80 nginx:latest
```

Port mapping is very important—for services like nginx, if no port is exposed, the outside world simply cannot access them.

> [!tip]
>
> As for networking details, we'll dig into them in the networking section later.

**Data volume mounts**

Omitted—too lazy to take notes on it.

**Environment variables**

```bash
## 设置单个环境变量

$ docker run -e MYSQL_ROOT_PASSWORD=secret mysql

## 从文件加载环境变量

$ docker run --env-file .env myapp
```

That said, containers sometimes do need environment variables from files like `.env`, assuming it has been `.dockerignore`d.

But I feel like docker-ignoring the `.env` file doesn't really mean much either—why do it?

Answer from ChatGPT, summarized by me:

First, you obviously can't put `.env` into the image (recall the title of this section, "**Create and Start**"), because images are meant to be **distributed**—once distributed, anyone could directly access the `.env` file inside, and you'd be done for. So it definitely has to be ignored.

Second, doing this decouples the image from the runtime environment.

**Resource limits**:

```bash
## 限制内存

$ docker run -m 512m nginx:latest

## 限制 CPU

$ docker run --cpus=1.5 nginx:latest
```

#### Restarting Containers

Use `docker start`, followed by the container name.

To get the container name, use `docker ps -a`.

### Running in Daemon Mode

When you run a program in a terminal, there are two modes:

* **Foreground**: the program occupies the current terminal, output is displayed directly, and closing the terminal stops the program
* **Background**: the program executes in the background, doesn't occupy the terminal, and closing the terminal doesn't affect it

Docker containers run in the **foreground** by default. Using the `-d` (detach) flag lets the container run in the background.

#### Understanding Why Containers Exit Immediately

**Core principle**: a container's lifecycle is bound to its main process.

For example, even when run with the `-d` flag:

```bash
$ docker run -d ubuntu:24.04
```

The container won't show up as running in `docker ps`. The reasons:

1. The container starts
2. No command is specified, so `/bin/bash` runs by default
3. But there's no interactive terminal (no `-it` flag), so bash finds no input source
4. bash exits immediately
5. The main process exits, and the container stops

> [!important]
>
> **The `-d` flag makes the container "run in the background"; how long it runs depends on the main process**

#### Inspecting Containers

```bash
$ docker container ls
$ docker ps
# 前者是后者的简写

# 查看日志
$ docker container logs 77b2dc01fe0f

# 实时查看日志
$ docker container logs -f 77b2dc01fe0f
```

> [!tip]
>
> For one-off tasks, use the `--rm` flag to have the container automatically deleted on exit.

### Stopping

`docker stop` stops gracefully

`docker kill` stops immediately

### Entering a Container

After starting with `-d`, sometimes you need to enter the container to operate on it.

```bash
## 进入容器并启动交互式 shell

$ docker exec -it 容器名 /bin/bash

## 或使用 sh（适用于 Alpine 等精简镜像）

$ docker exec -it 容器名 /bin/sh
```

### Import and Export

`docker export` `docker import`

### Deleting

`docker rm`

> [!note]
>
> `docker rm` is shorthand for `docker container rm`; the two are equivalent.

## Dockerfile Instructions in Detail

## Data Management

### Data Volumes

First you need `$ docker volume create my-vol` to create a data volume; then, when creating a new container, use `--mount` or `-v` to mount the data volume.

### Mounting Host Directories

> [!note]
>
> **Data volume (volume)**: storage managed by Docker. You only need to specify the volume name; Docker takes care of creating, storing, and locating the actual data directory on the host.
>
> ```bash
> docker run -v mydata:/app/data nginx
> # 名为 mydata 的数据卷，映射到容器的 /app/data 目录
> ```
>
> **Bind mount**: maps a host directory you specify directly into the container.
>
> ```bash
> docker run -v /home/user/data:/app/data nginx
> ```
>
> Key differences:
>
> - **volume**: you manage the volume name, Docker manages the actual storage location—suitable for persistent data like databases.
> - **bind mount**: you manage the host path yourself—suitable for mounting code and config files during development.
> - **Portability**: volumes don't depend on specific host paths; bind mounts depend on the host's directory structure.

## Network Configuration
