在构建新的 docker 镜像时,有没有办法在 docker-compose 中使用 --squash
选项?现在他们已经在 6 个月前在 docker 中实现了 --squash
,但我还没有看到任何关于如何在 docker-compose.yml 中使用它的文档。
这里有工作吗? (我看到一个 Unresolved 问题提出请求 feature)
最佳答案
您可以使用 Docker multi-stage builds 而不是使用 --squash
.
这是一个使用 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 文档 --tag 文档。
这使您可以构建从同一基础镜像分支的镜像,从而显着减少较大镜像的构建时间。
您还可以在 Docker Compose 中使用多阶段构建。从 docker-compose.yml
3.4 版开始,您可以在 YAML 中使用 target
关键字。
这是一个引用上述Dockerfile
的docker-compose.yml
文件:
version: '3.4'
services:
testing:
build:
context: .
target: testing
documentation:
build:
context: .
target: documentation
如果您使用此 docker-compose.yml
运行 docker-compose build
,它将构建 testing
和 documentation
Dockerfile
中的图像。与任何其他 docker-compose.yml
一样,您还可以添加端口、环境变量、运行时命令等。
关于docker - 构建镜像时在 docker-compose 中使用 docker --squash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45240239/