Ravexina
Ravexina

Reputation: 2848

What is the purpose of building a docker image inside a compose file?

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:

Upvotes: 0

Views: 802

Answers (1)

David Maze
David Maze

Reputation: 158956

There's no technical difference between docker build an image and specifying an image: in the docker-compose.yml file, and specifying the build: metadata directly in the docker-compose.yml.

The benefits to using docker-compose build to build images are more or less the same as using docker-compose up to run containers. If you have a complex set of -f path/Dockerfile --build-arg ... options, you can write those out in the build: block and not have to write them repeatedly. If you have multiple custom images that need to be built then docker-compose build can build them all in one shot.

In practice you'll frequently be iterating on your containers, which means you will need to run local unit tests, then rebuild images, then relaunch containers. Being able to drive the Docker end of this via docker-compose down; docker-compose up --build will be easier will be more convenient than remembering all of the individual docker build commands you need to run.

The one place where this doesn't work well is if you have a custom base image. So if you have a my/base image, and your application image is built FROM my/base, you need to explicitly run

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

Compose doesn't help with the multi-level docker-build sequence; you'll have to explicitly docker build the base image.

Upvotes: 2

Related Questions