我尝试将Dockerfile中的多个RUN命令合并,并观察图像大小的变化

在Dockerfile中,经常听说可以通过将RUN命令合并来减小镜像大小。
因为我以前没有实际尝试过,所以我试了一下。

我尝试比较了由两个Dockerfile创建的映像的大小。

各个Dockerfile之间的差异如下:
– dockerfile01:使用了多个RUN命令
– dockerfile02:通过&&连接多个命令来进行合并RUN命令。

FROM centos:7

# php, apacheインストール
RUN yum install -y "https://repo.ius.io/ius-release-el7.rpm"
RUN yum update -y
RUN yum install -y mod_php74 php74-cli httpd24u

CMD ["/usr/sbin/httpd", "-DFOREGROUND"]
FROM centos:7

# php, apacheインストール
RUN yum install -y "https://repo.ius.io/ius-release-el7.rpm" \
      && yum update -y \
      && yum install -y mod_php74 php74-cli httpd24u

CMD ["/usr/sbin/httpd", "-DFOREGROUND"]

执行以下命令以创建图像。

$ docker image build --no-cache -f ./Dockerfile01 -t centos7:test01 .
$ docker image build --no-cache -f ./Dockerfile02 -t centos7:test02 .
$ docker image ls
REPOSITORY   TAG      IMAGE ID       CREATED              SIZE
centos7      test02   81a7d6c540ff   About a minute ago   509MB
centos7      test01   7fdd86edf40d   4 minutes ago        761MB

只需要合并运行,可以确认镜像大小从761MB减少到509MB。

然而,需要根据具体情况来判断,毕竟并不是任何情况下都可以一概而论地说要进行RUN。

这次就到这里吧。

附加说明:
虽然没有包含在确认用的Dockerfile中,
但是如果执行以下命令:yum clean all,
可以进一步减小镜像的大小。

FROM centos:7

# php, apacheインストール
RUN yum install -y "https://repo.ius.io/ius-release-el7.rpm" \
      && yum update -y \
      && yum install -y mod_php74 php74-cli httpd24u \
      && yum clean all

CMD ["/usr/sbin/httpd", "-DFOREGROUND"]
$ docker image build --no-cache -f ./Dockerfile03 -t centos7:test03 .

$ docker image ls
REPOSITORY   TAG      IMAGE ID       CREATED          SIZE
centos7      test03   aa24f2e8f667   27 seconds ago   385MB
centos7      test02   81a7d6c540ff   6 minutes ago    509MB
centos7      test01   7fdd86edf40d   8 minutes ago    761MB
广告
将在 10 秒后关闭
bannerAds