在使用docker-compose构建镜像时,使用--squash参数。

15

在构建新的Docker镜像时,是否有一种方法可以在docker-compose中使用--squash选项?现在,他们已经在6个月前实现了--squash,但我没有看到任何关于如何在docker-compose.yml中使用它的文档。

这里是否有一种解决方法?(我看到有一个开放的问题请求此feature


很不幸,由于这个请求,他们打算从Docker中彻底移除这个功能。https://github.com/moby/moby/issues/34565 - ISanych
2个回答

2

您可以使用一些技巧来实现挤压结果,例如:

FROM oracle AS needs-squashing
ENV NEEDED_VAR some_value
COPY ./giant.zip ./somewhere/giant.zip
RUN echo "install giant in zip"
RUN rm ./somewhere/giant.zip

FROM scratch
COPY --from=needs-squashing / /

7
请注意,当您执行此操作时,将丢失环境变量设置、入口点定义以及其他元数据,您复制的只是文件系统。 - BMitch

2
代替使用--squash,您可以使用Docker多阶段构建

这是一个简单的示例,用于展示使用Django web框架的Python应用程序。我们想将测试依赖项分离到不同的镜像中,以便在生产环境中不部署测试依赖项。此外,我们还想将自动化文档工具与测试工具分开。

以下是 Dockerfile 代码:

# the AS keyword lets us name the image
FROM python:3.6.7 AS base
WORKDIR /app
RUN pip install django

# base is the image we have defined above
FROM base AS testing
RUN pip install pytest

# same base as above
FROM base AS documentation
RUN pip install sphinx

为了使用此文件构建不同的镜像,我们需要在docker build中使用--target标志。 --target的参数应该是Dockerfile中AS关键字后面的镜像名称。
构建基础镜像: docker build --target base --tag base . 构建测试镜像: docker build --target testing --tag testing . 构建文档镜像: docker build --target documentation --tag documentation . 这使您可以构建从同一基础镜像分支的镜像,这可以显着减少较大镜像的构建时间。
您还可以在Docker Compose中使用多阶段构建。截至版本3.4的docker-compose.yml,您可以在YAML中使用target关键字。
这是一个引用上面Dockerfiledocker-compose.yml文件:
version: '3.4'

services:
    testing:
        build:
            context: .
            target: testing
    documentation:
        build:
            context: .
            target: documentation

如果你使用这个docker-compose.yml文件运行docker-compose build命令,它将会在Dockerfile中构建testing和documentation的镜像。和其他任何docker-compose.yml一样,你也可以添加端口、环境变量、运行命令等等。"最初的回答"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接