airdata
airdata

Reputation: 641

Docker-compose for multi-stage build?

Let's say that we have docker-compose.yml which build few services with Dockerfile's in different locations like this:

version: '3.4'

services:
  service1:
    build: ./service1-dir

  service2:
    build: ./service2-dir

Let's say that in Dockerfile of service1 we have some folder that we already copy. Can I pass this folder to docker file of service2?

With another words - can I use multi-stage build technique to pass layers between different Dockerfiles or multi-stage build should be only in one Dockerfile?

Upvotes: 1

Views: 5266

Answers (1)

David Maze
David Maze

Reputation: 158696

You can split things up the way you describe; it'll probably be more robust to do things in two stages in a single Dockerfile, or to do the primary part of your build using host tools.

There are two essential parts to this. The first is that, in your docker-compose.yml file, if you specify both a build: description and an image: name, then Docker Compose will tag the built image for you. The second is that the Dockerfile COPY directive can copy content --from a preceding build stage or from an arbitrary other image. So if your docker-compose.yml says

version: '3'
services:
  service1:
    build: ./service1-dir
    image: me/service1
  service2:
    build: ./service2-dir

and service2-dir/Dockerfile says

COPY --from=me/service1 /app/somefile .

it will copy content from one image to the other.

The one challenge here is that docker-compose build doesn't specify the order the images are built in. If it builds service2 first, it will get old content from the previous build of service1 (or fail if it's the initial build). To do this reliably, you need to do something like

docker-compose build service1
docker-compose build
docker-compose up -d

If the build sequence isn't too complex, just including it in both Dockerfiles could make sense. It can also work to built whatever artifacts you need on the host, and have your Dockerfiles copy that in as-is instead of building it themselves; this works well especially if that content is platform-neutral (Java .jar files, HTML/Javascript/CSS files from a Webpack build for a browser application).

Upvotes: 2

Related Questions