Docker Multi-Stage:如何拆分为多个Dockerfile [英] Docker Multi-Stage: How to split up into multiple Dockerfiles

查看:125
本文介绍了Docker Multi-Stage:如何拆分为多个Dockerfile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已成功使用Docker的Multi-Stage功能构建了一些代码,然后将生成的工件复制到最终映像中.

I am successfully using Docker's Multi-Stage feature to build some code and then copy the resulting artifacts into a final image.

是否可以将这一个大型Dockerfile拆分为多个文件?

Is it possible to split this one big-ish Dockerfile into multiple files?

我想提高各个阶段的可读性.当添加更多阶段时,这将变得更加重要.

I would like to improve the readability of the individual stages. Which will become more important when more stages are added.

我知道我可以编写一个Makefile(或类似文件),在该文件中我首先构建一个名为"myproject-stage1"的映像,然后使用 FROM myproject-stage1 AS构建.但是,如果可能的话,我宁愿避免使用外部构建工具.

I am aware that I could write a Makefile (or similar) where I first build an image named "myproject-stage1" and then use FROM myproject-stage1 AS build. However, I'd rather avoid the external build tool if possible.

推荐答案

如果您的Dockerfile当前看起来像这样:

If your Dockerfile currently looks something like:

FROM ubuntu:16.04 AS builder
RUN apt-get install build-essential
COPY . ./
RUN ./build_all_the_things \
 && make install PREFIX=/usr DESTDIR/out

FROM alpine:3.8
COPY --from=builder /out/ /
CMD the_app

您可以按原样将第一部分拆分成自己的Dockerfile并进行构建

You can readily split out the first part into its own Dockerfile, as is, and build it

docker build -f Dockerfile.builder -t me/builder .

COPY --from 必须在Dockerfile中命名前一个阶段,但是该阶段不需要做很多事情;然后可以将其后半部分更改为

COPY --from has to name some previous stage in your Dockerfile, but the stage doesn’t need to do much; you can then change the second half of this to

FROM me/builder AS builder
FROM alpine:3.8
COPY --from=builder /out/ /
CMD the_app

最大的缺点是您需要两个单独的 docker build 命令来实际构建最终映像.您可以编写一个Shell脚本来同时完成这两个任务.

The big downside of this is that you need two separate docker build commands to actually build the final image. You could write a shell script to do both of them together.

这篇关于Docker Multi-Stage:如何拆分为多个Dockerfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆