python:slim
、node:alpine
# 不推荐
FROM ubuntu:latest
# 推荐
FROM alpine:latest
# 或
FROM gcr.io/distroless/base
# 第一阶段:构建环境
FROM golang:1.16 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp .
# 第二阶段:运行环境
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]
# 不推荐
RUN apt-get update
RUN apt-get install -y package1
RUN apt-get install -y package2
RUN rm -rf /var/lib/apt/lists/*
# 推荐
RUN apt-get update && \
apt-get install -y package1 package2 && \
rm -rf /var/lib/apt/lists/*
RUN apt-get update && \
apt-get install -y --no-install-recommends package1 && \
apt-get clean && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
.git
node_modules
*.log
*.tmp
Dockerfile
README.md
# 不推荐
COPY . .
# 推荐
COPY package.json .
COPY src/ src/
FROM node:alpine AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
RUN gzip -k /usr/share/nginx/html/*
FROM python:3.9-slim
# 使用虚拟环境
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
# 先安装依赖,再复制代码
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
FROM node:alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
FROM node:alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
FROM maven:3.6-jdk-11 AS build
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn package
FROM openjdk:11-jre-slim
COPY --from=build /app/target/app.jar /app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
Dive:分析镜像各层内容
dive <image-name>
docker history:查看镜像构建历史
docker history <image-name>
docker-slim:自动优化镜像
docker-slim build --target <image-name>
通过综合应用这些技巧,通常可以将镜像体积减小50%-90%,同时保持应用功能的完整性。