入门
基本命令
docker run 创建并启动容器。-d 在后台运行,-p 将主机端口映射到容器端口。pull 从镜像仓库(默认 Docker Hub)下载镜像。
# check version
docker --version
# pull an image
docker pull nginx:latest
# run a container
docker run -d --name mynginx -p 8080:80 nginx
# list running containers
docker ps
# list all containers (including stopped)
docker ps -a
# stop and remove a container
docker stop mynginx
docker rm mynginx
# list images
docker images容器生命周期
create + start 就是 run 在底层所做的操作。stop 发送 SIGTERM 进行优雅关闭;kill 立即发送 SIGKILL。pause 使用 cgroup 冻结器——适用于在不停止进程的情况下进行快照。
# create a container without starting it
docker create --name web nginx
# start a created (or stopped) container
docker start web
# stop gracefully (SIGTERM then SIGKILL after 10s)
docker stop web
# force kill immediately
docker kill web
# restart a container
docker restart web
# pause/resume (freezes process with cgroups)
docker pause web
docker unpause web镜像基础
镜像是只读的层。rmi 在容器仍引用该镜像时会失败——先移除容器。history 显示创建每一层的指令及其大小,对优化构建很有用。
# list local images
docker images
docker image ls
# remove an image
docker rmi nginx:latest
docker image rm nginx
# remove all dangling (untagged) images
docker image prune
# remove all unused images
docker image prune -a
# show image history (each layer)
docker history nginx:latest系统信息
docker info 显示守护进程配置:存储驱动、运行时、镜像仓库、Swarm 状态。system df 显示可回收空间——悬空镜像和已停止的容器会浪费磁盘。--format 标志使用 Go 模板进行结构化输出。
# docker system-wide info
docker info
docker version
# disk usage breakdown (images, containers, volumes)
docker system df
# detailed disk usage with reclaimable space
docker system df -v
# running containers count
docker ps -q | wc -l
# show docker root directory and storage driver
docker info --format '{{.DockerRootDir}} {{.Driver}}'清理与裁剪
prune 安全地移除已停止/悬空的资源。system prune -a 还会移除未被任何容器引用的镜像。添加 --volumes 会删除未被任何容器使用的卷——不可逆的数据丢失,在生产环境中谨慎使用。
# remove stopped containers
docker container prune
# remove dangling images
docker image prune
# remove unused volumes (CAUTION: data loss)
docker volume prune
# remove unused networks
docker network prune
# remove everything unused at once
docker system prune
# also remove volumes (very aggressive)
docker system prune -a --volumes获取帮助
Docker 将命令分组到管理命名空间(docker image、docker container、docker network、docker volume)下。旧形式(docker rmi)和新形式(docker image rm)都可以使用。在任何子命令上使用 --help 可查看标志和用法。
# list all commands
docker --help
docker help
# help for a specific command
docker run --help
docker image --help
# list management commands (grouped)
docker image --help
docker container --help
docker network --help
# show daemon config
docker info
# command reference online
# https://docs.docker.com/reference/镜像管理
拉取镜像
标签是可变的标签——同一个标签随时间可以指向不同的镜像。对于可重现的部署,通过摘要(@sha256:...)固定。通过 --platform 拉取可获取不同架构的镜像,适用于在 x86 主机上构建 ARM 镜像。
# pull latest tag
docker pull nginx
# pull specific tag
docker pull nginx:1.25-alpine
# pull all tags of a repository
docker pull -a alpine
# pull from a different registry
docker pull ghcr.io/user/repo:tag
# pull by digest (immutable, reproducible)
docker pull nginx@sha256:abc123...
# pull multiple platforms (multi-arch)
docker pull --platform linux/arm64 nginx构建镜像
最后的 . 是构建上下文——发送给守护进程的文件。用 .dockerignore 保持上下文小以加速构建。--no-cache 在调试时强制刷新层。BuildKit 启用多阶段缓存、SSH 挂载和密钥挂载。
# build from Dockerfile in current dir, tag it
docker build -t myapp:1.0 .
# build with a different Dockerfile name
docker build -f Dockerfile.prod -t myapp:prod .
# build with build args
docker build --build-arg VERSION=1.2.3 -t myapp .
# build with no cache
docker build --no-cache -t myapp .
# build for a different platform
docker build --platform linux/arm64 -t myapp:arm .
# build using BuildKit (advanced features)
DOCKER_BUILDKIT=1 docker build -t myapp .标记镜像
标签是指向同一镜像 ID 的别名。常见的工作流是用版本标签构建,然后添加 latest 和主版本标签。用镜像仓库 URL 标记可为推送到该仓库做准备。
# tag a local image
docker tag myapp:1.0 myapp:latest
# tag for pushing to Docker Hub
docker tag myapp:1.0 username/myapp:1.0
# tag for a private registry
docker tag myapp:1.0 registry.local:5000/myapp:1.0
# tag with multiple tags at once
docker tag myapp:1.0 myapp:stable
docker tag myapp:1.0 myapp:1
# tag by digest reference
docker tag myapp@sha256:abc... myapp:pinned推送镜像
推送前必须用镜像仓库目的地标记镜像。push 只上传镜像仓库中尚不存在的层。对于使用自签名证书的私有仓库,在 /etc/docker/daemon.json 中配置 insecure-registries。
# login to Docker Hub
docker login
# login to a private registry
docker login registry.local:5000 -u user -p pass
# push to Docker Hub
docker push username/myapp:1.0
# push all tags in a repository
docker push -a username/myapp
# push to private registry
docker push registry.local:5000/myapp:1.0
# logout when done
docker logout检查镜像
inspect 返回详细的 JSON:架构、操作系统、层、环境变量、入口点、配置。history 显示每层的命令和大小——镜像优化的基础。manifest inspect 无需拉取即可检查远程仓库。
# low-level image metadata (JSON)
docker inspect nginx:latest
# specific field via Go template
docker inspect --format '{{.Arch}} {{.Os}}' nginx
# show image layers and sizes
docker history nginx:latest
# no-trunc to see full command for each layer
docker history --no-trunc nginx:latest
# inspect an image in a registry (manifest)
docker manifest inspect nginx:latest保存与加载镜像
save/load 保留镜像层和历史——是离线传输镜像的正确选择。export/import 展平为单层,丢失历史。对于在线传输,优先使用仓库推送/拉取而非 tar 文件。
# save an image to a tar file
docker save -o myapp.tar myapp:1.0
# save multiple images
docker save -o bundle.tar myapp:1.0 nginx:latest
# load an image from a tar file
docker load -i myapp.tar
# pipe between hosts (no intermediate file)
docker save myapp:1.0 | gzip | ssh host 'gunzip | docker load'
# export a container filesystem (not an image)
docker export mycontainer | gzip > fs.tar.gz容器管理
运行容器
-it 组合 -i(保持 stdin 打开)和 -t(分配 tty)用于交互式会话。--rm 在退出后清理——非常适合一次性命令。--restart unless-stopped 在重启后存活但尊重手动停止。
# run in background with a name and port mapping
docker run -d --name web -p 8080:80 nginx
# run interactively with a terminal
docker run -it --name shell alpine sh
# run and auto-remove on exit
docker run --rm alpine echo hello
# run with a volume
docker run -d -v mydata:/data alpine
# run with environment variables
docker run -d -e MYSQL_ROOT_PASSWORD=secret mysql
# run with a restart policy
docker run -d --restart unless-stopped nginx执行命令(exec)
exec 在已运行的容器内运行新进程——原始入口点继续运行。用于调试、管理任务或运行一次性脚本。默认用户是镜像的 USER;用 -u 覆盖。
# open an interactive shell in a running container
docker exec -it web sh
# run a command and return
docker exec web ls /usr/share/nginx/html
# run as a specific user
docker exec -u root web whoami
# set environment variables for the command
docker exec -e DEBUG=1 web env
# run with a working directory
docker exec -w /tmp web pwd
# run as detached (rarely useful)
docker exec -d web touch /tmp/marker查看日志
logs 显示容器日志驱动捕获的 stdout/stderr。应用程序应记录到 stdout 而非文件,以与 docker logs 集成。--since/--until 接受 RFC3339 时间戳或 Go 持续时间(30m、2h)。
# follow (tail) logs
docker logs -f web
# show last 100 lines
docker logs --tail 100 web
# show logs since a timestamp
docker logs --since 2024-01-01T00:00:00 web
# show logs from the last 30 minutes
docker logs --since 30m web
# add timestamps to each line
docker logs -t web
# show logs for a specific timeframe
docker logs --since 10m --until 5m web容器检查
inspect 返回涵盖配置、状态、网络和挂载的丰富 JSON。Go 模板提取特定字段——对脚本编写非常有用。LogPath 揭示 json-file 驱动在主机上存储日志的位置。
# full JSON metadata
docker inspect web
# container IP address
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' web
# container log path (json-file driver)
docker inspect --format '{{.LogPath}}' web
# mounts and volumes
docker inspect --format '{{json .Mounts}}' web
# container state (running, exited, etc.)
docker inspect --format '{{.State.Status}} {{.State.ExitCode}}' web
# all container ports
docker inspect --format '{{json .NetworkSettings.Ports}}' web启动、停止与重启
start 以原始配置恢复已停止的容器。update 修改运行中容器的约束和重启策略而无需重新创建——适用于在生产环境中收紧资源限制。
# start a stopped container
docker start web
# stop with a custom timeout (seconds)
docker stop -t 30 web
# restart (keeps container intact)
docker restart web
# rename a container
docker rename web webserver
# update container config (e.g. restart policy)
docker update --restart unless-stopped web
# pause/resume (cgroup freezer)
docker pause web
docker unpause web复制文件
cp 在两个方向都可用,也可用于已停止的容器——便于注入热修复或提取日志。它不适用于高频同步;开发工作流请使用绑定挂载或数据卷。tar+exec 技巧可高效传输大型目录树。
# copy a file from host to container
docker cp file.txt web:/tmp/
# copy from container to host
docker cp web:/etc/nginx/nginx.conf ./nginx.conf
# copy a directory
docker cp ./app web:/usr/src/app
# copy with archive mode (preserves perms)
docker cp -a ./config web:/etc/app
# copy to a stopped container (works too)
docker cp script.sh web:/script.sh
# tar stream from host to container stdin
docker exec -i web tar xzf - -C /app < app.tar.gzDockerfile 基础
FROM — 基础镜像
FROM 是第一条指令,定义基础层。选择最小基础镜像(alpine、distroless、scratch)以减少攻击面和大小。通过摘要固定可保证可重现构建,因为标签可能变化。
# use an official base image
FROM ubuntu:22.04
# pin a specific digest for reproducibility
FROM ubuntu@sha256:abc123def...
# multi-arch build (buildx picks the host arch)
FROM --platform=$BUILDPLATFORM golang:1.21 AS builder
# use a minimal image
FROM alpine:3.18
# scratch = empty image, for static binaries
FROM scratch
# use a previous build stage
FROM builder AS finalRUN — 执行命令
每个 RUN 创建一层。用 && 组合相关命令并在同一层清理以保持镜像小。exec 形式(JSON 数组)不调用 shell,因此没有变量展开或链接——但它能正确处理信号。
# install packages
RUN apt-get update && apt-get install -y curl
# clean up in the same layer to reduce size
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
# combine commands with && to reduce layers
RUN mkdir -p /app/config && chown 1000:1000 /app/config
# use exec form (preferred) to ensure signals
RUN ["npm", "install"]
# use a shell for variables and chaining
RUN VERSION=1.0 && wget https://example.com/v${VERSION}.tar.gzCOPY 与 ADD
COPY 是本地文件的首选——它是显式且可预测的。ADD 增加了魔法:URL 获取和 tar/zip 压缩包的自动解压。这种魔法可能让您意外;仅在需要解压时才使用 ADD。两者都创建一层。
# copy a file into the image
COPY package.json /app/
# copy a directory
COPY src/ /app/src/
# copy with ownership
COPY --chown=node:node package.json /app/
# copy from a previous build stage
COPY --from=builder /app/dist /app/dist
# ADD can fetch URLs and extract archives
ADD https://example.com/app.tar.gz /tmp/
# ADD extracts local tar archives automatically
ADD app.tar.gz /usr/src/工作目录(WORKDIR)
WORKDIR 设置后续指令和容器默认的工作目录。如果目录不存在则创建。始终优先使用 WORKDIR 而非 RUN 中的 cd——cd 不会跨层持久化。使用绝对路径更清晰。
# set the working directory
WORKDIR /usr/src/app
# subsequent RUN, CMD, COPY use this dir
COPY . .
RUN npm install
# WORKDIR creates the directory if it does not exist
WORKDIR /opt/data/logs
# use a relative path (relative to previous WORKDIR)
WORKDIR sub
# avoid this anti-pattern (use absolute paths)
WORKDIR /app
RUN cd /app && do_something # cd is lost after RUN用户(USER)
USER 为 RUN、CMD 和 ENTRYPOINT 设置用户(和可选的组)。以非 root 运行是关键的安全最佳实践。用户必须在镜像中存在。数字 UID 跨镜像可移植,避免名称查找问题。
# create a non-root user and switch to it
RUN groupadd -r app && useradd -r -g app appuser
USER appuser
# run subsequent instructions as this user
RUN whoami # appuser
# use a numeric UID for portability
USER 1000
# USER in compose/runtime overrides this
USER 1000:1000
# common pattern: node image ships a 'node' user
FROM node:20-alpine
USER node.dockerignore
.dockerignore 减少发送给守护进程的构建上下文——更快的构建、更小的上下文,并防止 .env 等密钥泄露到镜像层中。它使用与 .gitignore 类似的语法。始终排除在构建期间重新创建的 node_modules 和构建产物。
# .dockerignore — exclude files from the build context
# version control
.git
.gitignore
# dependencies (fetched inside the image)
node_modules
npm-debug.log
# build artifacts
dist
build
*.log
# local env files (NEVER bake secrets)
.env
.env.local
# docker files themselves
Dockerfile
docker-compose*.yml
# OS files
.DS_Store
Thumbs.dbDockerfile 进阶
CMD 与 ENTRYPOINT
ENTRYPOINT 定义可执行文件;CMD 提供可覆盖的默认参数。使用 exec 形式(JSON 数组)使进程直接接收信号——shell 形式将命令包装在 /bin/sh -c 中,破坏优雅关闭。常见模式:ENTRYPOINT 脚本 + CMD 默认参数。
# CMD: default command, easily overridden
CMD ["nginx", "-g", "daemon off;"]
# override at runtime
# docker run myimage nginx -v
# ENTRYPOINT: fixed command, CMD becomes args
ENTRYPOINT ["nginx"]
CMD ["-g", "daemon off;"]
# runtime args append to ENTRYPOINT
# docker run myimage -v -> nginx -v
# shell form (avoid — no signal handling)
CMD nginx -g "daemon off;"
# script as entrypoint that accepts args
ENTRYPOINT ["./entrypoint.sh"]
CMD ["--help"]ENV — 环境变量
ENV 创建镜像级变量,在构建和运行时可见。使用 ARG 仅用于构建时值, 以避免将配置泄露到最终镜像。在 exec 形式的 CMD/ENTRYPOINT 中,${VAR} 不会被 shell 展开——用 sh -c 包装以展开。
# set a persistent env var (baked into image)
ENV NODE_ENV=production
ENV PATH=/app/node_modules/.bin:$PATH
# use in subsequent RUN instructions
ENV VERSION=1.2.3
RUN wget https://example.com/v${VERSION}.tar.gz
# multiple in one line
ENV NODE_ENV=production PORT=3000 LOG_LEVEL=info
# override at runtime
# docker run -e NODE_ENV=development myapp
# view env vars of a container
docker exec web env
# reference env vars in CMD
ENV APP_PORT=3000
CMD ["sh", "-c", "node server.js ${APP_PORT}"]ARG — 构建参数
ARG 值仅在声明它的阶段构建期间存在。它们不会持久化到运行时容器——使用 ENV 将值传递到运行时。在 FROM 之前声明的 ARG 是'全局的',但必须在使用它的每个阶段中重新声明。
# declare a build argument with a default
ARG VERSION=latest
FROM base:${VERSION}
# use ARG only during build (not at runtime)
ARG NODE_ENV=production
RUN echo "Building for ${NODE_ENV}"
# multi-stage: ARG must be redeclared per stage
ARG VERSION
FROM base:${VERSION}
ARG VERSION
RUN echo ${VERSION}
# pass at build time
# docker build --build-arg VERSION=1.0 .
# ARG not available in CMD (use ENV to pass through)
ARG PORT=3000
ENV PORT=${PORT}
CMD ["sh", "-c", "serve --port ${PORT}"]EXPOSE
EXPOSE 是文档说明——它不发布端口。发布在运行时用 -p(主机:容器)或在 Compose 中用 ports: 进行。EXPOSE 帮助工具了解预期端口,并在遗留网络中启用自动链接。
# document which port the container listens on
EXPOSE 80
# expose multiple ports
EXPOSE 80 443
# expose with protocol
EXPOSE 53/udp
# EXPOSE does NOT publish the port
# you still need -p at runtime
# docker run -p 8080:80 myapp
# in compose, expose vs ports
# expose: only to linked services
# ports: published to the host
# view exposed ports
docker inspect --format '{{json .Config.ExposedPorts}}' myappLABEL 与元数据
LABEL 为镜像附加键值对元数据。采用 OCI org.opencontainers.image.* 标签以与镜像仓库和工具互操作。标签对跟踪版本、源代码、许可和 CI 构建信息很有用。
# add a label (key=value metadata)
LABEL maintainer="[email protected]"
LABEL version="1.0"
LABEL description="My web app"
# multiple labels in one instruction
LABEL org.opencontainers.image.title="myapp" \
org.opencontainers.image.version="1.0" \
org.opencontainers.image.source="https://github.com/me/myapp"
# view labels
docker inspect --format '{{json .Config.Labels}}' myapp
# filter images by label
docker images --filter "label=version=1.0"
# deprecated: MAINTAINER (use LABEL maintainer instead)
# MAINTAINER Alice <[email protected]>Dockerfile 中的 VOLUME
VOLUME 声明挂载点;Docker 在首次运行时创建匿名卷,除非您绑定主机路径。它表示该目录包含有状态数据。一个陷阱:在 COPY 之后声明 VOLUME 可能会用空卷覆盖您复制的文件。
# declare an anonymous volume mount point
VOLUME /data
# multiple mount points
VOLUME /data /config /logs
# at runtime, Docker creates an anonymous volume
# docker run -v mydata:/data myapp (named instead)
# VOLUME in Dockerfile: any files copied to /data
# are copied into the new anonymous volume on first run
# inspect volumes
docker inspect --format '{{json .Mounts}}' myapp
# avoid: VOLUME after COPY can hide your data
COPY ./config /config
VOLUME /config # new empty volume shadows /config多阶段构建
基本多阶段
多阶段构建只将最终产物复制到运行时镜像——构建工具、源代码和开发依赖项留在构建器阶段。结果:一个小巧、安全的运行时镜像。用 AS 命名阶段以便在 COPY --from 中引用。
# stage 1: build
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# stage 2: runtime (small)
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]选择构建阶段
--target 只构建到命名阶段,跳过后续阶段。这使单个 Dockerfile 可用于开发、测试和生产:CI 中 target 'test',生产中 'final'。BuildKit 自动并行化独立的阶段。
# build only up to a named stage
# docker build --target builder -t myapp:dev .
FROM node:20 AS builder
RUN npm ci && npm run build
FROM node:20-alpine AS test
COPY --from=builder /app /app
RUN npm test
FROM nginx:alpine AS final
COPY --from=builder /app/dist /usr/share/nginx/html
# target a specific stage
# docker build --target test .精简运行时镜像
对于静态二进制文件(Go、Rust),scratch 生成尽可能小的镜像,攻击面为零。添加 CA 证书以支持 HTTPS。distroless 提供带有根 CA 和非 root 用户的最小基础,非常适合动态语言或需要无 shell 运行时的情况。
# build stage
FROM golang:1.21 AS builder
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o app -ldflags="-s -w" .
# scratch = empty image, only the static binary
FROM scratch
COPY --from=builder /src/app /app
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
ENTRYPOINT ["/app"]
# result: ~10MB image
# or use distroless for a minimal OS base
FROM gcr.io/distroless/static
COPY --from=builder /src/app /app
ENTRYPOINT ["/app"]编译型语言的构建器模式
在完整的 SDK 镜像中编译,然后将构件复制到仅运行时镜像(JRE)中。这大幅缩小镜像(JDK 约 600MB vs JRE 约 200MB)并从生产中移除构建工具。在 COPY 之前预取依赖项可改善层缓存。
# stage 1: compile
FROM maven:3.9 AS builder
WORKDIR /build
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn package -DskipTests
# stage 2: runtime with only the JRE
FROM eclipse-temurin:21-jre-alpine
COPY --from=builder /build/target/*.jar /app/app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
# benefits: no JDK, no source, no Maven cache in runtime从外部镜像复制
COPY --from 可以从任何镜像拉取——适用于从多个基础组装工具而无需构建阶段。阶段也可以通过索引(从 0 开始)引用,但用 AS 命名更清晰。通过摘要固定外部镜像以确保可重现性。
# copy a binary from another image (no build stage needed)
FROM alpine:3.18
COPY --from=nginx:alpine /usr/sbin/nginx /usr/sbin/nginx
COPY --from=nginx:alpine /etc/nginx /etc/nginx
RUN apk add --no-cache libpcre2
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
# use a specific digest for reproducibility
COPY --from=redis:7@sha256:abc... /usr/local/bin/redis-server /usr/local/bin/
# copy from a built stage referenced by index
COPY --from=0 /build/output /appBuildKit 特性
BuildKit 解锁缓存挂载(npm/pip 缓存在构建之间持久化而不膨胀镜像)、密钥挂载(凭证永远不会接触层)、用于私有仓库的 SSH 转发,以及更简洁的多行 RUN heredoc 语法。添加 # syntax 指令以固定 Dockerfile 前端版本。
# enable BuildKit
# DOCKER_BUILDKIT=1 docker build .
# syntax directive for latest frontend
# syntax=docker/dockerfile:1
FROM alpine
# mount a cache (persists across builds, not in image)
RUN --mount=type=cache,target=/root/.npm npm ci
# mount a secret (never written to layers)
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
# mount an SSH socket for private repos
RUN --mount=type=ssh git clone [email protected]:me/repo.git
# heredoc for multi-line scripts
RUN <<EOF
set -ex
apk add --no-cache curl
mkdir -p /app/data
EOF数据卷
创建与使用数据卷
命名卷 由 Docker 管理,是持久化数据的推荐方式。它们在容器移除后存活,并独立于主机文件系统布局。:ro 后缀以只读方式挂载。inspect 揭示 /var/lib/docker/volumes 下的磁盘路径。
# create a named volume
docker volume create mydata
# use it in a container
docker run -d -v mydata:/data alpine sh -c "sleep 1h"
# inspect the volume
docker volume inspect mydata
# mount read-only
docker run -v mydata:/data:ro alpine ls /data
# mount with a different filesystem (e.g. tmpfs)
docker run --tmpfs /cache alpine
# default volume driver: local
docker volume create --driver local mydata列出与检查数据卷
ls 列出命名卷;inspect 显示驱动和挂载点。要查找哪些容器使用某个卷,按卷过滤 ps。卷位于 Linux 主机上的 /var/lib/docker/volumes/<name>/_data 下——通过 docker exec 访问,而非直接主机编辑。