Moonlit Torii

Docker Basics

Docker from zero: images, containers, networking, volumes, and common commands.

01 Docker Beginner's Guide from Scratch | 2025 Reset Edition

Earlier, I recorded a Docker beginner tutorial, it was in May 2023.

Figure 1 for 01 Docker Beginner's Guide from Scratch | 2025 Reset Edition

At that time, just changing Docker to a domestic mirror could allow images to be pulled normally.

But after 2024, due to well-known reasons, all domestic Docker sources stopped working.

So it greatly increased the difficulty of getting started.

Additionally, the content is a bit too simple. This course should include a bit more material, and in the early stages, try to explain it as clearly and simply as possible.

What can Docker do

Imagine a scenario where you are developing a web project on Windows.

Isn't it ironic? You developed it using Python, and when you deployed it to the server, first you struggled to install middleware like MySQL, Redis, and Nginx, and then when running the Python project, you found it wouldn't run no matter what. Sometimes it would say a package was missing, sometimes it would say a function didn't exist. What's going on?

After using Docker, in the future, installing middleware such as MySQL, Redis, Elasticsearch, and Nginx will only require a single command.

And for projects developed in the future, project deployment will only require one or two commands, greatly facilitating the development, installation, and deployment processes.

Those of you who can see this document, I believe everyone must be quite anxious. There are all kinds of things being said online, like Docker is no longer viable, now it's all about Kubernetes, Podman will replace Docker in the future, and so on.

Anyway, I have just one sentence: you should learn when it's time, use when it's needed, and if you really become obsolete, just embrace the new changes.

I previously also learned jQuery and used Django to write a website without separating the front end and back end.

But that doesn't stop me from now learning Go and building websites using front-end and back-end separation technology.

What is Docker

Docker is an open-source project implemented in the Go language, which allows us to easily create and use containers. Docker packages the program and all its dependencies into a Docker container, so your program can have consistent performance in any environment.

I have always felt that without Docker, the installation of various middleware would become very difficult, such as installing MySQL, ES, Nginx, because the installation process differs somewhat across different systems.

Now that we have Docker, all we need to do is write a command. As long as I can run it, if you run this command, you can run it too, regardless of the operating system.

Docker Installation

This course uniformly uses the Linux/CentOS 7 system to install Docker, and uses Docker on this system.

Bash
# 删除之前的docker残留
yum -y remove docker*

yum install -y yum-utils

yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

yum install docker-ce docker-ce-cli containerd.io -y
# 启动docker
systemctl start docker
# 开机启动
systemctl enable docker

It is not highly recommended to use Docker on Windows. Firstly, the performance of Docker on Windows is not very good. Secondly, there are subtle differences (such as the host network). Thirdly, the systems actually deployed are all Linux systems.

If yum doesn't work, remember to change the repository.

Bash
cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

yum clean all
yum makecache

Docker Set Proxy

Starting from 2024, it will no longer be possible to download images in China through Docker by switching to domestic sources.

This point has indeed discouraged many people.

Students who don't know magic can use Tencent Cloud's servers. Tencent Cloud has a private Docker repository where images can be downloaded.

You can also buy an overseas or foreign server, or you can directly pull the Docker image.

If you really want to pull images at will, the best way is still to learn magic and configure a Docker proxy.

Of course, this course can only teach you how to configure a Docker proxy.

Bash
创建 /etc/systemd/system/docker.service.d/http-proxy.conf 配置文件

[Service]
Environment="HTTP_PROXY=http://192.168.80.1:7890"
Environment="HTTPS_PROXY=http://192.168.80.1:7890"

然后重新加载配置并重启服务:
systemctl daemon-reload
systemctl restart docker

然后检查加载的配置:
systemctl show docker --property Environment

Remember to enable intranet access for the proxy software

Quick Use of Docker

How does everyone install MySQL?

Native installation?

I searched the official website for the installation file, and I have to set up a password and configure access policies—it's too troublesome.

Use Docker, with just one command

Bash
docker run -itd -p 3306:3306 --name=mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7

Then use your MySQL client, and you can connect to your MySQL, it's awesome.

Alright, I believe Docker should have sparked your interest in learning, so the course officially begins!

If you can't access it, the most likely reason is that the port is not open.

Bash
firewall-cmd --list-ports
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload

docker image

Learn Docker, starting with images

The MySQL, Redis, and others I mentioned above are made into Docker images by experts or officially on Docker Hub.

We only need to use docker pull image_name to download it to our local machine.

Basic Operations of Mirroring

Bash
# 拉取镜像
docker pull image_name:tag
# 不写tag,默认是latest

# 检索镜像
docker search image_name:tag

# 列表
docker images

# 删除镜像
docker rmi image_id


docker container

It can be understood as a very streamlined operating system.

On this operating system, only the services you need are deployed, which corresponds to your image.

For example, the nginx image, the container it runs represents that this operating system only has the nginx software service.

For example, a MySQL image, the container it runs represents that in this operating system there is only the MySQL software service.

Containers are the core concept of Docker, essentially isolated processes running based on images — they reuse the host kernel and achieve resource isolation (network, filesystem, processes) and restrictions (CPU, memory) through technologies like Namespace and Cgroups, making them lighter and faster to start than virtual machines.

Container List

Bash
# 查看正在运行中的容器
docker ps
# 查看所有容器
docker ps -a
# 只获取容器id
docker ps -a -q
# 指定输出的内容
docker ps -a --format "table {{.ID}}\t{{.Names}}"


Run container

Docker
docker run [选项] <镜像名:标签> [容器启动参数]

Option

  1. --name is used to give a name to the container being started, and this name is unique on the host machine.
  2. -t allocates a pseudo-terminal for Docker and attaches it to the container's standard input.
  3. -i keeps the container's standard input open.
  4. -v directory mapping, for data persistence. The part before the colon represents the directory on the host machine, and the part after the colon is the directory inside the container. If the directory does not exist, it will be automatically created.
  5. -p port mapping, host port: container port.
  6. -e indicates setting environment variables.
  7. -d indicates starting the container in detached mode (i.e., background mode), so executing it will return the container ID instead of entering the interactive interface. To enter the interactive interface, you need to use the -i and -t parameters.
  8. --restart indicates the container restart policy.
  9. --privileged indicates whether to use privileged mode. Setting --privileged=true elevates system execution privileges. If set to true, the root user inside the container has real root privileges; otherwise, it is just a regular user.

Container Operation

Take MySQL as an example

Bash
# 后台运行 并且 暴露端口 -p 宿主机端口:容器内端口
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3307:3306 mysql:5.7

# 传递环境变量 配置数据库名
docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_DATABASE=blog mysql:5.7

# 数据挂载 重启mysql,数据也不会丢失 -v 宿主机路径:容器内路径
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -v ./mysql_data:/var/lib/mysql mysql:5.7

# 限制 1G 内存、1 个 CPU 核心,超出内存时容器自动终止
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 --memory 1G --cpus 1 mysql:5.7

# 容器重启策略:always(总是重启,除非手动停止)
docker run -d --name  mysql -e MYSQL_ROOT_PASSWORD=123456 --restart always mysql:5.7
#on-failure[:max-retries]:仅在容器退出码非 0 时重启(可指定最大重试次数);
#always:总是重启(包括手动停止后重启 Docker 服务时);
#unless-stopped:除非手动停止,否则一直重启。

Container operations

Bash
# 停止容器
docker stop docker_id
# 启动容器
docker start docker_id
# 重启容器
docker restart docker_id
# 删除没有运行的容器
docker rm docker_id
# 删除运行中的容器
docker rm -f docker_id
# 停止所有容器
docker stop $(docker ps -a -q)
# 删除所有容器
docker rm -f $(docker ps -a -q)

View Logs

Bash
# 查看这个容器的全部日志
docker logs <容器名称>

# 持续查看日志
docker logs -f <容器名称>

# 持续查看前10条日志
docker logs -f -n 10 <容器名称>
# 持续查看前10条日志 老版本docker
docker logs -f --tail=10 <容器名称>


Enter the Container

A container is essentially an isolated process, and entering a container essentially starts a new terminal process in the namespace of that isolated process (such as sh or bash), allowing you to view files inside the container, execute commands, and debug Go programs (such as checking processes, logs, and modifying configurations).

Key premise: Only running containers can enter

Bash
docker exec -it <容器名/容器ID> <容器内执行的命令>

Port Mapping

Docker containers by default have their own network namespace (isolated network environment), and the MySQL service listening ports inside the container (such as 3306) can only be accessed within the container. Port mapping establishes a mapping between the "host port" and the "container port" through Docker's iptables rules, so that external requests to the host port are forwarded to the corresponding port inside the container, thereby enabling external access to the MySQL service.

Analogy: A container is an 'independent room,' and the MySQL service provides service on port 3306 inside the room; port mapping is equivalent to putting a 'door number (host port 3306)' on the door of the room. External visitors knock according to the door number and will be directed to port 3306 inside the room.

Bash
# 宿主机 3306 端口 → 容器 3306 端口(外部通过 http://宿主机IP:3306 访问)
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3307:3306 mysql:5.7

# 宿主机随机端口 → 容器 3306 端口
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306 mysql:5.7

# 仅 192.168.80.185 这个网卡的 3306 端口映射到容器 3306
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -p 192.168.80.185.100:3306:3306 mysql:5.7

# 映射 多个端口
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3307:3306 -p 3306:3306 mysql:5.7


Services within the container must listen on 0.0.0.0 (not 127.0.0.1), otherwise they can only be accessed inside the container and cannot be accessed externally through port mapping (a key pitfall to avoid).

For example, Go's web service

Go
// 错误:仅容器内可访问
http.ListenAndServe("127.0.0.1:8080", nil)
// 正确:外部可通过端口映射访问
http.ListenAndServe(":8080", nil)  // 等价于 0.0.0.0:8080

Table of Contents Mapping

The file system of a container is a 'temporary layer' — a writable layer created on top of the read-only layers based on the image. After the container is deleted, the files in the writable layer (such as logs, configuration changes, database data) will be lost. Directory mapping (also called 'mounting') establishes an association between 'directories/files on the host machine' and 'directories/files inside the container' to achieve:

  • Data persistence: Logs and data written by the program are stored on the host machine, so data is not lost after the container is deleted;
  • File sharing: When configuration files are modified on the host machine, changes take effect in the container in real time (no need to restart the container);
  • Avoiding image bloat: Large files (such as logs and databases) do not need to be packaged into the image.

Docker supports two directory mapping methods: Bind Mount and Volume. In Go scenarios, the former is used for configuration files/logs, while the latter is used for important data (such as databases).

Bind Mount

Directly mount the host's custom directories/files into the container, suitable for scenarios where manual modification and viewing are needed (such as configuration files and log directories).

Bash
docker run -v <宿主机路径>:<容器内路径>[:权限] <镜像名>
# ro:只读(容器内只能读取,不能修改宿主机文件);
# rw:读写(默认,容器内可修改宿主机文件)。

Bash
# 宿主机 ./mysql_data 目录 → 容器 /var/lib/mysql 目录(读写权限)
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -v ./mysql_data:/var/lib/mysql mysql:5.7

# 目录映射之后,删除容器再执行运行命令,数据依然还在


# 宿主机 ./xxx.txt 文件 → 容器 /etc/mysql/xxx.txt 文件(只读权限,防止容器修改)
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456  -v ./xxx.txt:/xxx.txt:ro mysql:5.7


Be careful, directly using vi or vim to edit files might not sync properly, because vi edits by creating a new file, then deleting the old file, and replacing it with the new file, which can break Docker's synchronization mechanism.

Data Volume (Volume)

Docker-managed persistent storage

A data volume is a persistent directory specially created by Docker (stored under /var/lib/docker/volumes/ on the host), automatically managed by Docker, and does not require manual maintenance of the host path, making it suitable for storing important data.

Core Advantage

  • Good cross-platform compatibility (Docker manages paths uniformly, unaffected by the host directory structure);
  • Supports permission control, data volume backup / restore;
  • Can share data across multiple containers (e.g., multiple services sharing the same data volume).
Bash
# 创建名为 mysql_data 的数据卷
docker volume create mysql_data

# 数据卷 mysql_data → 容器 /var/lib/mysql 目录
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -v mysql_data:/var/lib/mysql mysql:5.7

# 查看所有数据卷
docker volume ls

# 查看数据卷详情(如存储路径)
docker volume inspect mysql_data

# 删除数据卷(需先解绑所有容器)
docker volume rm mysql_data

# 清理所有未使用的卷
docker volume prune


Common Issues with Containers

Does the container report an error as soon as it starts?

  1. First, check the logs with docker logs. If there are error outputs in the logs, you will basically know how to fix it.
  2. No logs? Run the container again with docker run ... sh; it will definitely start. Once it's running, enter the container and manually execute the original startup command to see what happens.

After the container starts, the original files in the mounted directory inside the container disappear

If the host machine's mount directory is empty, it will overwrite the existing files in the directory inside the container (Docker mounting rule: the host machine directory has higher priority than the container directory);

Did the files mounted on the host machine turn into directories?

If the "source path" mounted by Docker does not exist on the host, Docker will by default create a "directory" rather than a "file"—even if you specify a file at the target path inside the container, it will be overwritten by this newly created directory, and what you end up seeing inside the container is a directory, not the expected file.

Image Building

After learning about the above Docker images and Docker containers, you can cover 50% of your Docker application scenarios.

For some complex operations, such as deploying Go projects, Python, and these personal projects

Or install some software on top of some base images

Then you have to write a Dockerfile.

First, look at an example Dockerfile for deploying a Go project

Docker
# 注释:指定基础镜像(必填,所有指令的起点)
FROM golang:alpine AS builder

# 设置环境变量
ENV CGO_ENABLED 0
ENV GOPROXY https://goproxy.cn,direct
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

# 设置工作目录
WORKDIR /build

# 复制文件
ADD go.mod .
COPY go.sum .
ADD main.go .

# 执行命令
RUN go build -o main

FROM alpine

WORKDIR /app

# 维护者信息
LABEL maintainer="fengfeng@xx.com"
LABEL version="1.0"
LABEL description="A demo Docker image for go app"
# 元数据可通过 docker inspect <镜像名>  便于镜像管理

# 多阶段构建
COPY --from=builder /build/main /app
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
RUN apk add bash

# 容器启动时执行的命令(必填,仅最后一个生效)
CMD ["./main"]

# 暴露端口(仅声明,不实际映射,用于文档说明)
EXPOSE 8080

Build command

Bash
# 完整命令
docker build -f Dockerfile -t demo-app:v1.0  .
# 可省略-f
docker build  -t demo-app:v1.0  .

Building Context

The last parameter (such as ., /home/user/project) specifies the path, which is the 'build context'. The Docker client will package all files/directories under that path and send them to the Docker daemon for the COPY/ADD instructions in the Dockerfile to read the files.

Requires additional understanding

COPY and ADD

Copy local files/directories to a specified path in the image. The main difference: ADD supports automatic decompression of compressed files and downloading files from URLs (not recommended, it is recommended to use RUN wget instead).

Docker
# 复制本地 项目的所有文件到 到镜像的 /app 目录
COPY .  .

# ADD 自动解压本地压缩包到镜像(如 tar.gz、zip)
ADD .  /app/

RUN, CMD, and ENTRYPOINT

run: Execute commands (such as installing dependencies, extracting files, creating directories) during the image build process, and the results of execution will be solidified into the layers of the image.

Two formats

Docker
# Shell 格式:安装 nginx(合并命令减少镜像分层)
RUN apt update && apt install -y nginx && rm -rf /var/lib/apt/lists/*

# Exec 格式:创建目录(无 Shell 环境,不支持变量替换)
RUN ["mkdir", "-p", "/app/logs"]

cmd: Default startup command, can be overridden by the parameters following docker run.

ENTRYPOINT: Entry command, the parameters following docker run will be appended as its arguments and cannot be overwritten (unless forcibly replaced using the --entrypoint parameter).

Docker
# ENTRYPOINT:固定启动命令
ENTRYPOINT ["./main"]

# CMD:默认启动参数
# 这里默认指定 --env=dev 和 --port=8080,运行时可替换
CMD ["--env", "dev", "--port", "8080"]

docker networks

Docker networking is the core component for enabling communication between containers and between containers and the outside world (host machine/internet). Essentially, it achieves container network isolation through Linux network namespaces and then opens communication channels using techniques such as bridging, routing, and port mapping.

After installing Docker, three default networks are automatically created.

Bash
docker network ls

NETWORK ID     NAME      DRIVER    SCOPE
abc123xyz     bridge    bridge    local  # 默认桥接网络
def456uvw     host      host      local  # 主机模式网络
ghi789rst     none      null      local  # 无网络模式

Bridged Network

When the container starts, Docker automatically allocates:

  • Independent IPs (such as 172.17.0.2, 172.17.0.3, default subnet 172.17.0.0/16);
  • Gateway (host docker0 bridge IP, such as 172.17.0.1);

Containers communicate with each other via IP, and external access to services within the containers is through port mapping (-p).

Limitations:

  • The default bridge network does not support container name resolution (communication can only occur via IP);
  • All containers in the default bridge mode are on the same subnet, with poor isolation (suitable for single services, not suitable for multi-service clusters).

Self-Built Bridge Network

Manually created bridge networks have two core advantages compared to the default bridge:

  • Supports container name resolution (containers can communicate using container names as hostnames without needing to know the IP);
  • Network isolation (containers on different custom networks cannot communicate, providing higher security).
Bash
# 创建名为 go-microservice 的自定义桥接网络
docker network create go-microservice

# 启动依赖容器(Redis)并加入网络
docker run -d --name redis --network go-microservice redis:alpine

# 另一个容器也加入这个网络
docker run -d --name go-server --network go-microservice -p 8081:8080 go-demo:1.0

# 然后在这个容器里面,就可以直接容器名访问对应的ip




Custom container network subnet and container IP

Bash
# 创建网段为 172.20.0.0/16、网关为 172.20.0.1 的自定义网络
docker network create --subnet 172.20.0.0/16 --gateway 172.20.0.1 go-fixed-ip-network

# 查看网络详情(确认网段和网关)
docker network inspect go-fixed-ip-network

# 指定固定 IP 172.18.0.10(需在自定义网络子网内)
docker run -d --name go-server --network go-fixed-ip-network --ip 172.20.0.10 go-demo:1.0


Host Mode

Containers share the host's network namespace, which means:

  • The container does not have an independent IP and uses the host's IP directly;
  • Ports inside the container are directly exposed on the host (no port mapping needed);
  • The network configuration inside the container (such as routing and DNS) is exactly the same as the host's.

Limitations

  • Port conflict risk: Conflicts between container ports and host/other container ports may cause startup failure;
  • Lower security: Containers are directly exposed to the host network, without isolation;
  • Cross-platform incompatibility: Host mode has compatibility limitations on Windows/Mac systems (recommended for use only on Linux).
Bash
# 启动 Go 容器,使用 host 模式,监听宿主机 8080 端口
docker run -d --name go-server --net=host go-demo:1.0 --port 8080


docker compose

Docker Compose is an official multi-container application orchestration tool provided by Docker. Its core function is to define and manage multiple related Docker containers through a unified configuration file (default docker-compose.yml), allowing for "one-click start/stop/destroy" of the entire application cluster, solving the tedious problem of manually operating containers one by one (such as network configuration, dependency order, and port mapping).

When your application depends on multiple services (for example: web services + database + cache + message queue), manual operations will face the following pain points:

  1. Each docker run command needs to be run individually, with lengthy parameters (ports, networks, data volumes, environment variables, etc.);
  2. Network connectivity between containers must be manually maintained (for example, making the Web container access the DB container);
  3. Container startup order has dependencies (the DB must be started before the Web);
  4. Scaling, restarting services, and viewing logs require individual operations.

And Docker Compose can:

  • Declare all service configurations with a YAML file;
  • Start/stop all services with one click (docker-compose up/down);
  • Automatically create a separate network so containers can communicate via service names;
  • Maintain container dependencies, data volume persistence, and environment variable isolation;
  • View logs of all services in a unified way and scale service instances.

Basic Structure

YAML
# 版本声明(推荐 v3,兼容 Docker 17.06+)
version: '3'

# 定义所有服务(核心模块,每个服务对应一个容器)
services:
  服务1名称:
    # 镜像(必填):来自 Docker Hub 或自定义镜像
    image: 镜像名:标签
    # 容器名称(可选,默认自动生成)
    container_name: 容器名
    # 端口映射(可选):主机端口:容器端口
    ports:
      - "主机端口1:容器端口1"
      - "主机端口2:容器端口2"
    # 环境变量(可选):两种写法
    environment:
      - 键=值  # 直接写
      - 键2=值2
    env_file:  # 从文件读取(优先级低于 environment)
      - .env
    # 数据卷(可选):持久化数据或挂载主机目录
    volumes:
      - 主机目录:容器目录  # 绑定挂载
      - 数据卷名称:容器目录  # 命名数据卷
    # 依赖服务(可选):启动顺序(先启动依赖的服务)
    depends_on:
      - 服务2名称
      - 服务3名称
    # 网络(可选):指定服务加入的网络
    networks:
      - 自定义网络名
    # 重启策略(可选):容器退出后的重启规则
    restart: always  # 可选:no/on-failure/unless-stopped

# 定义网络(可选,默认会创建一个默认网络)
networks:
  自定义网络名:
    driver: bridge  # 网络驱动(默认 bridge,支持 overlay 等)

# 定义数据卷(可选,用于持久化服务数据)
volumes:
  数据卷名称:
    driver: local  # 数据卷驱动(默认 local)

Example

YAML
# 版本声明(推荐 v3,兼容 Docker 17.06+)
version: '3'

# 定义所有服务(核心模块,每个服务对应一个容器)
services:
  web:
    # 镜像(必填):来自 Docker Hub 或自定义镜像
    image: web:v1
    # 容器名称(可选,默认自动生成)
#    container_name: 容器名
    # 端口映射(可选):主机端口:容器端口
    ports:
      - "8081:8080"
    # 环境变量(可选):两种写法
    environment:
      - xxx=dev  # 直接写
    # 网络(可选):指定服务加入的网络
    networks:
      - xx_net
    # 重启策略(可选):容器退出后的重启规则
    restart: always  # 可选:no/on-failure/unless-stopped
  web1:
    image: web:v1
    ports:
      - "8082:8080"
    networks:
      - xx_net
    restart: always

# 定义网络(可选,默认会创建一个默认网络)
networks:
  xx_net:
    driver: bridge  # 网络驱动(默认 bridge,支持 overlay 等)

Common Commands

Bash
# 后台启动所有服务
docker compose up -d

# 查看 web 服务的实时日志
docker compose logs -f web

# 进入 db 服务容器(如 MySQL)
docker compose exec db bash

# 停止所有服务(保留容器和数据卷)
docker compose stop

# 停止并删除所有服务、网络、容器(保留数据卷)
docker compose down

# 停止并删除所有(包括数据卷)
docker compose down -v

Practical: go+mysql Deployment

YAML
services:
  blog:
    image: web:v3
    networks:
      - blog
    restart: always
    volumes:
      - ./settings.yaml:/app/settings.yaml
    depends_on:
      - mysql
  mysql:
    image: mysql:5.7
    environment:
      - MYSQL_ROOT_PASSWORD=123456
      - MYSQL_DATABASE=blog
    volumes:
      - ./mysql_data:/var/lib/mysql
    networks:
      - blog
    restart: always

# 定义网络(可选,默认会创建一个默认网络)
networks:
  blog:
    driver: bridge  # 网络驱动(默认 bridge,支持 overlay 等)

Go Language Integration with Docker API

In some cases, it is necessary to manipulate containers through code.

For example, getting the container list, getting the image list, creating a container, deleting a container

Go
package main

import (
  "context"
  "fmt"
  "github.com/docker/docker/api/types/container"
  "github.com/docker/docker/api/types/image"
  "github.com/docker/go-connections/nat"
  "log"

  "github.com/docker/docker/client"
)

var cli *client.Client

func init() {
  // 初始化 Docker 客户端(使用默认端点)
  // 如需自定义端点(如远程 Docker 服务),可通过 client.WithHost("tcp://192.168.1.100:2375") 指定
  _cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  if err != nil {
    log.Fatalf("创建 Docker 客户端失败:%v", err)
  }
  //defer cli.Close() // 退出时关闭客户端连接

  fmt.Println("Docker 客户端连接成功!")

  cli = _cli
}

func imageList() {
  list, _ := cli.ImageList(context.Background(), image.ListOptions{})
  for _, summary := range list {
    fmt.Printf("%s %s\n", summary.ID[7:19], summary.RepoTags)
  }
}

func containerList() {
  list, _ := cli.ContainerList(context.Background(), container.ListOptions{})
  for _, summary := range list {
    fmt.Println(summary.ID[7:19], summary.Names, summary.State, summary.Image)
  }
}

//func (cli *Client) ContainerCreate(
//  ctx context.Context,          // 上下文(控制超时、取消等)
//  config *container.Config,      // 容器核心配置(对应之前你问的 Config 结构体)
//  hostConfig *container.HostConfig,  // 主机资源配置(与宿主机交互相关)
//  networkingConfig *network.NetworkingConfig,  // 网络配置(容器网络栈、端口映射等)
//  platform *ocispec.Platform,    // 目标平台(跨架构场景用,如 arm64/amd64)
//  containerName string           // 容器名称(可选,如不指定则自动生成)
//) (container.CreateResponse, error)
func containerCreate() {
  response, err := cli.ContainerCreate(
    context.Background(),
    &container.Config{
      AttachStdin:  true,
      AttachStdout: true,
      OpenStdin:    true,
      StdinOnce:    true,
      Image:        "alpine:latest",
      Cmd:          []string{"sh"},
    },
    &container.HostConfig{
      PortBindings: nat.PortMap{
        "80": []nat.PortBinding{
          {
            HostIP:   "0.0.0.0",
            HostPort: "80",
          },
        },
      },
    },
    nil,
    nil,
    "alpine",
  )
  if err != nil {
    fmt.Println("创建容器失败", err)
    return
  }
  fmt.Println("容器创建成功", response.ID)
  err = cli.ContainerStart(context.Background(), response.ID, container.StartOptions{})
  if err != nil {
    fmt.Println("容器启动失败", err)
    return
  }
  fmt.Println("容器启动成功")
}

func main() {
  containerCreate()
}


Docker Self-Hosted Repository

In an intranet environment, if many servers need to download images, configuring the Docker proxy on each one would not be very convenient.

So, more often, you can store images centrally on one server, run the Docker registry service on that server, and create a Docker image repository.

Other servers can directly pull the image from this machine.

Docker
docker pull registry

Modify the configuration file

Docker officially requires that image registries (Registry) must communicate using the HTTPS protocol (to ensure transmission encryption and authentication). However, in practice, many companies or individuals set up private image registries (for example, using Docker's official registry image to set them up). These private registries may only enable the HTTP protocol (without configuring HTTPS certificates) due to cost or environmental constraints.

insecure-registries (Chinese: 'Insecure Registry'): tells Docker 'the following registry is trusted, allowing communication over HTTP protocol without verifying the HTTPS certificate.'

Bash
vim /etc/docker/daemon.json
{
  "insecure-registries": ["192.168.80.185:5000"]
}

systemctl restart docker

Run the registry service

Bash
docker run -itd -v /data/registry:/var/lib/registry -p 5000:5000 --restart=always --name registry registry:latest

Upload Image

Bash
# 给镜像打tag
docker tag alpine:latest 192.168.80.185:5000/alpine:latest
# 上传到私有仓库
docker push 192.168.80.185:5000/alpine:latest


Pull image

To configure insecure-registries

Docker
docker pull 192.168.80.185:5000/alpine