本文目录导读:

- 优化Dockerfile层数
- 利用构建缓存
- 多阶段构建
- 使用.dockerignore
- 优化apt/yum安装
- 并行化构建
- 使用构建缓存代理
- 减少不必要的依赖
- 使用更小的基础镜像
- 完整的优化示例
- 使用docker buildx加速
- 监控构建时间
在Shell脚本中优化镜像构建时间,可以从以下几个关键方面入手:
优化Dockerfile层数
# ❌ 不推荐:每行一个RUN命令
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y nginx
RUN rm -rf /var/lib/apt/lists/*
# ✅ 推荐:合并命令,减少层数
RUN apt-get update && \
apt-get install -y curl nginx && \
rm -rf /var/lib/apt/lists/*
利用构建缓存
# ✅ 将变化少的放在前面 COPY package.json package-lock.json ./ RUN npm install COPY . ./
多阶段构建
# 构建阶段 FROM node:18 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
使用.dockerignore
# .dockerignore node_modules .git *.log .cache dist
优化apt/yum安装
# apt优化
RUN apt-get update && \
apt-get install -y --no-install-recommends \
pkg1 pkg2 && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# yarn优化
RUN yarn install --frozen-lockfile --production
并行化构建
# 在shell脚本中使用后台进程
#!/bin/bash
{
apt-get update
apt-get install -y curl
} &
{
pip install numpy
} &
wait # 等待所有后台任务完成
使用构建缓存代理
# 配置npm代理缓存 RUN npm config set registry https://registry.npmmirror.com # 或使用本地缓存 COPY --from=cache /root/.npm /root/.npm
减少不必要的依赖
# 只安装生产依赖 RUN npm ci --only=production # 或使用npm prune清理 RUN npm install && npm prune --production
使用更小的基础镜像
# ❌ 不推荐 FROM node:18 # ✅ 推荐 FROM node:18-alpine # 或使用slim版本 FROM node:18-slim
完整的优化示例
# 多阶段构建 + 缓存优化
FROM node:18-alpine AS builder
# 配置国内镜像源加速
RUN npm config set registry https://registry.npmmirror.com
WORKDIR /app
# 先复制依赖文件,利用缓存
COPY package.json package-lock.json ./
RUN npm ci --only=production
# 复制源代码
COPY . .
# 构建
RUN npm run build
# 最终镜像
FROM nginx:alpine
# 复制构建产物
COPY --from=builder /app/dist /usr/share/nginx/html
# 清理不必要的文件
RUN rm -rf /etc/nginx/conf.d/default.conf && \
echo 'server { listen 80; location / { root /usr/share/nginx/html; index index.html; } }' > /etc/nginx/conf.d/default.conf
使用docker buildx加速
# 使用BuildKit加速 DOCKER_BUILDKIT=1 docker build -t myapp . # 使用缓存挂载 docker build --build-arg BUILDKIT_INLINE_CACHE=1 \ --cache-from myapp:cache \ -t myapp:latest .
监控构建时间
# 在shell脚本中添加计时功能 #!/bin/bash START_TIME=$(date +%s) docker build -t myapp . END_TIME=$(date +%s) echo "Build took $((END_TIME - START_TIME)) seconds"
- 减少层数:合并RUN命令
- 利用缓存:变化少的文件先复制
- 多阶段构建:分离构建和运行环境
- 减小镜像体积:使用Alpine基础镜像
- 使用缓存代理:配置国内镜像源
- 并行化:合理使用后台进程
- 清理无用文件:apt clean等
通过这些优化,通常可以减少50%-80%的镜像构建时间。