# 基本构建命令
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
# 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;"]
# 编译阶段
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 . .
--no-cache强制重新构建# 查看镜像构建历史
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