<返回目录     Powered by claude/xia兄

第5课: 镜像构建

docker build 基础

# 基本构建命令
docker build -t myapp:v1.0 .

# 指定Dockerfile路径
docker build -t myapp:v1.0 -f Dockerfile.prod .

# 不使用缓存构建
docker build --no-cache -t myapp:v1.0 .

# 指定构建参数
docker build --build-arg VERSION=1.0 -t myapp:v1.0 .

构建上下文

构建上下文是指docker build命令最后指定的路径,Docker会将该路径下的所有文件发送给Docker守护进程。

# 当前目录作为构建上下文
docker build -t myapp .

# 指定其他目录
docker build -t myapp /path/to/context

# 从Git仓库构建
docker build -t myapp https://github.com/user/repo.git

# 从标准输入构建
docker build -t myapp - < Dockerfile
优化构建上下文:

.dockerignore 文件

# 排除版本控制
.git
.gitignore
.svn

# 排除依赖目录
node_modules
venv
__pycache__

# 排除日志和临时文件
*.log
*.tmp
*.swp

# 排除文档
README.md
docs/

# 排除测试文件
tests/
*.test.js

构建参数 ARG

# Dockerfile中定义参数
FROM python:3.9
ARG VERSION=1.0
ARG ENVIRONMENT=production

LABEL version=$VERSION
ENV APP_ENV=$ENVIRONMENT

# 构建时传递参数
docker build --build-arg VERSION=2.0 --build-arg ENVIRONMENT=staging -t myapp .

多阶段构建

多阶段构建可以显著减小最终镜像大小,将编译环境和运行环境分离。

# 第一阶段:编译
FROM node:16 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# 第二阶段:运行
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Go应用多阶段构建示例

# 编译阶段
FROM golang:1.19 AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o main .

# 运行阶段
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/main .
EXPOSE 8080
CMD ["./main"]

构建缓存机制

Docker会缓存每一层的构建结果,如果指令和上下文没有变化,会直接使用缓存。

# 优化前:每次代码变化都要重新安装依赖
FROM python:3.9
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt

# 优化后:依赖文件不变时使用缓存
FROM python:3.9
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
缓存优化技巧:

查看构建历史

# 查看镜像构建历史
docker history myapp:v1.0

# 查看详细信息
docker history --no-trunc myapp:v1.0

# 查看每层大小
docker history --format "{{.Size}}\t{{.CreatedBy}}" myapp:v1.0

构建时的网络配置

# 使用主机网络
docker build --network host -t myapp .

# 使用自定义网络
docker build --network mynetwork -t myapp .

# 禁用网络
docker build --network none -t myapp .

标签管理

# 构建时添加多个标签
docker build -t myapp:v1.0 -t myapp:latest .

# 构建后添加标签
docker tag myapp:v1.0 myapp:stable
docker tag myapp:v1.0 registry.example.com/myapp:v1.0

实践练习

  1. 创建一个Node.js应用的多阶段构建Dockerfile
  2. 编写.dockerignore文件优化构建上下文
  3. 使用ARG参数构建不同环境的镜像
  4. 对比单阶段和多阶段构建的镜像大小
  5. 观察构建缓存的效果,修改代码后重新构建