docker 镜像瘦身

使用Docker Squash

pip install docker-squash

docker-squash image:old -t image:new

使用较小的基础镜像

减小 docker 镜像大小最明显的方法是使用较小的基础镜像。

如果希望为 python 应用程序创建镜像,请考虑使用 python:3.9-slim 镜像而不是 python:3.9。

python:3.9 的大小约为 1.3 GB,而 python:3.9-slim 的大小仅为 1 GB 左右。

您可以使用 alpine 版本进一步减少镜像。alpine 镜像是专门为作为容器运行而设计的,而且体积非常小。python:3.9-alpine 镜像只有 49 MB。

使用多阶段构建来减小大小

为了显着减小大小,我们可以使用 docker 多阶段构建的概念。这里我们使用不同的 images/Dockerfile 来构建和打包应用代码。

它将 Dockerfile 分成多个阶段,并将所需的工件从一个阶段传递到另一个阶段,然后在最后一个阶段交付缩小镜像大小的最终镜像。它显着减小镜像尺寸。

# Stage-1
FROM node:14.17-alpine3.14 as build
# Copy Required files
COPY public /home/app/public/
COPY src /home/app/src/
# dockerfile install multiple packages
RUN apk add g++ make python2
RUN npm install --silent
# Create Build
RUN npm run build
RUN apk --purge del python2
#Run the build by copying the files form previous stage.
# 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;"]

这里我们使用两个阶段从 docker 文件创建镜像。在 Stage-1 中,我们复制代码并构建它,在 stage-2 中,我们使用在 stage-1 中构建的代码在 Nginx 中运行

软件包安装删除多余项目

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/*  #在 apt install 命令后添加 rm -rf /var/lib/apt/lists/*
rm awscliv2.zip  # 安装后删除软件包
COPY file /home/ubuntu # copy在run后,能减小构建时间

使用 .dockerignore 文件

.dockerignore 文件示例

ignorethisfile.txt
logs/
ignorethisfolder/
.git
.cache
*.md

使用其他缩容工具

dive : https://github.com/wagoodman/dive

fromlatest.io : https://www.fromlatest.io/

slim : https://github.com/slimtoolkit/slim


作者:spike

分类: Tool

创作时间:2023-08-31

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1