在构建图像时使用docker --squash在docker-compose中

iba*_*alf 9 docker dockerfile docker-compose

--squash在构建新的docker镜像时,有没有办法在docker-compose中使用该选项?现在他们已经--squash在6个月前在docker中实现了,但我还没有看到任何关于如何在docker-compose.yml中使用它的文档.

这附近有工作吗?(我看到提交请求此功能的未决问题)

Nic*_*tje 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
Run Code Online (Sandbox Code Playgroud)

为了使用此文件构建不同的图像,我们--target需要docker build. 的参数应在 Dockerfile 中的关键字--target之后命名图像的名称。AS

构建基础镜像:

docker build --target base --tag base .

构建测试图像:

docker build --target testing --tag testing .

构建文档图像:

docker build --target documentation --tag documentation .

这使您可以构建从同一基础映像分支的映像,这可以显着减少较大映像的构建时间。

您还可以在 Docker Compose 中使用多阶段构建。从 3.4 版本开始,您可以在 YAML 中docker-compose.yml使用关键字。target

这是docker-compose.yml引用Dockerfile上述内容的文件:

version: '3.4'

services:
    testing:
        build:
            context: .
            target: testing
    documentation:
        build:
            context: .
            target: documentation
Run Code Online (Sandbox Code Playgroud)

如果您docker-compose build使用它运行,docker-compose.yml它将testing在. 与任何其他 一样,您还可以添加端口、环境变量、运行时命令等。documentationDockerfiledocker-compose.yml