如何创建最小的容器镜像

发布于 2023-03-01 22:54:16 字数 1946 浏览 82 评论 0

优化容器镜像尺寸的方法一般是使用 alpine 或者 busybox 这类超轻量级的 linux 作为 base image,然而,所谓容器说到底不过就是一堆进程而已,之所以要引入这些 base image 不过是为进程提供依赖的动态库而已。

也就是说,如果采取静态方式来编译程序的话,那么就可以完全省略掉 base image,从而节省出一些空间。

比如,我们可以先创建一个示例程序:

#include<iostream>
using namespace std;
int main(){
cout << "Hello World \n ";
return 0;
}

我们对它进行静态编译:

g++ -o hello -static hello.cpp

现在编写 Dockerfile

FROM scratch
ADD hello /
CMD ["/hello"]

其中第一句 FROM scratch 中的 scratch 并不是parent镜像的名字,它表示 Docker 在构建该镜像时并不基于任何其他的镜像。现在我们试一下,构建该镜像

docker build --tag scratch .
Sending build context to Docker daemon  557.1kBSending build context to Docker daemon   11.7MBSending build context to Docker daemon   23.4MBSending build context to Docker daemon  34.54MBSending build context to Docker daemon  42.36MB
Step 1/3 : FROM scratch
 ---> 
Step 2/3 : COPY hello /
 ---> 645b80b836a7
Step 3/3 : CMD ["/hello"]
 ---> Running in 762c0cb569cb
Removing intermediate container 762c0cb569cb
 ---> b63cd83c8576
Successfully built b63cd83c8576
Successfully tagged scratch:latest

我们来运行一下这个容器

docker run --rm scratch
Hello World 
 

容器能正常运行。现在我们来看一下 Docker 镜像的大小

docker images
REPOSITORY                     TAG                 IMAGE ID            CREATED             SIZE
scratch                        latest              b63cd83c8576        4 minutes ago       2.15MB
lujun9972/archlinuxcn.docker   latest              9462714d994c        46 hours ago        628MB
silex/emacs                    master              05a842271d75        2 months ago        439MB
alpine                         latest              3fd9065eaf02        5 months ago        4.15MB
richxsl/rhel7                  latest              9c7b3825758a        3 years ago         245MB

你会发现,scratch 镜像只有 2.15M,而相比之下 alpine 则有 4.15M 大小

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

滥情空心

暂无简介

文章
评论
809 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文