- 减少镜像层
- 减少 Dockerfile 中的层数,合并多个命令以减少层数。
- 示例:
FROM ubuntu:latest
RUN apt update -y && \
apt install unzip -y && \
apt install curl -y && \
apt install python3 -y
- 使用 Docker Squash 减小镜像大小
- 使用
docker-squash工具来减小镜像大小。 - 安装命令:
- 使用
pip install docker-squash
- 使用命令:
docker-squash image:old -t image:new
-
使用较小的基础镜像
选择较小的基础镜像,如
python:3.9-slim或python:3.9-alpine。 -
使用多阶段构建来减小大小
- 使用多阶段构建,将构建和运行环境分开,减少最终镜像大小。
- 示例:
# Stage-1
FROM node:14.17-alpine3.14 as build
COPY public /home/app/public/
COPY src /home/app/src/
RUN apk add g++ make python2
RUN npm install --silent
RUN npm run build
RUN apk --purge del python2
# Stage-2
FROM nginx:stable-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /home/app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
- apt 安装中使用 --no-install-recommends 标志
- 使用
--no-install-recommends标志来避免安装不必要的推荐包。 - 示例:
- 使用
FROM ubuntu:latest
RUN apt update -y && \
apt install unzip -y --no-install-recommends && \
apt install curl --no-install-recommends -y && \
apt install python3 -y --no-install-recommends
- 在 apt install 命令后添加 rm -rf /var/lib/apt/lists/*
- 清理 apt 缓存以减小镜像大小。
- 示例:
FROM ubuntu:latest
RUN apt update -y && \
apt install unzip -y --no-install-recommends && \
apt install curl --no-install-recommends -y && \
apt install python3 -y --no-install-recommends && \
rm -rf /var/lib/apt/lists/*
- 使用 .dockerignore 文件
- 创建
.dockerignore文件来排除不需要的文件和目录。 - 示例
.dockerignore文件内容:
- 创建
ignorethisfile.txt
logs/
ignorethisfolder/
.git
.cache
*.md
- 在 RUN 之后放置 COPY
- 将
COPY命令放在RUN命令之后,以利用 Docker 构建缓存。 - 示例:
- 将
FROM ubuntu:latest
RUN apt update -y && \
apt install unzip -y --no-install-recommends && \
apt install curl --no-install-recommends -y && \
apt install python3 -y --no-install-recommends && \
rm -rf /var/lib/apt/lists/*
COPY file /home/ubuntu
- 安装后删除软件包
- 安装完软件包后,删除不再需要的安装包和文件。
- 示例:
FROM ubuntu:latest
RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" && \
unzip awscliv2.zip && \
sudo ./aws/install && \
rm awscliv2.zip