0

I was reading Quickstart: Compose and Django when I came across "defining a build in a compose file". Well I've seen it before but what I'm curious about here is what's the purpose of it? I just can't get it.

Why we just don't build the image once (or update it whenever we want) and use it multiple times in different docker-compose files?

Here is the Dockerfile:

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/

And here is docker-compose.yml:

version: '3'
 web:
  # <<<< 
  # Why not building the image and using it here like "image: my/django"?
  # <<<<
  build: .
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"

You might say: "well, do as you wish!" Why I'm asking is because I think there might be some benefits that I'm not aware of.

PS:

4

1 回答 1

1

docker build图像与在image:文件docker-compose.yml中指定 和build:直接在docker-compose.yml.

用于构建镜像的好处与用于运行容器的好处docker-compose build或多或少相同。docker-compose up如果您有一组复杂的-f path/Dockerfile --build-arg ...选项,您可以将它们写在build:块中,而不必重复编写它们。如果您有多个需要构建的自定义图像,那么docker-compose build可以一次性构建它们。

在实践中,您将经常迭代您的容器,这意味着您需要运行本地单元测试,然后重建映像,然后重新启动容器。能够通过此方式驱动 Docker 端docker-compose down; docker-compose up --build将比记住docker build您需要运行的所有单个命令更容易。

如果您有自定义基本映像,则此方法无法正常工作的一个地方。因此,如果您有一个my/base图像,并且您的应用程序图像已构建FROM my/base,则需要显式运行

docker build -t my/base base
docker build -t my/app app
docker run ... my/app

docker-buildCompose 对多级序列没有帮助;您必须明确docker build显示基本图像。

于 2020-07-20T14:50:01.523 回答