10

Having a base docker-compose.yml like the following:

version: '2'
services:
  web:
    build: .
...

How can I extend it to use an image instead?

docker-compose.prod.yml

version: '2'
services:
  web:
    image: username/repo:tag

Running it with docker docker-compose -f docker-compose.yml -f docker-compose.prod.yml up still promps:

Building web
Step 1/x : FROM ...

I tried with docker-compose -f docker-compose.yml -f docker-compose.prod.yml up --no-build:

ERROR: Service 'web' needs to be built, but --no-build was passed.

I'm expecting the "Pulling from name/repo message" instead. Which options do I have? Or do I need to create a complete duplicate file to handle this slight modification?

zurfyx
  • 27,640
  • 18
  • 109
  • 139

3 Answers3

11

Omit the build on the base docker-compose.yml, and place it in a docker-compose.override.yml file.

When you run docker-compose up it reads the overrides automatically.

Extracted from the Docker Compose Documentation.

Since your docker-compose.yml file must have either build or image, we'll use image that has less priority, resulting in:

version: '2'
services:
  web:
    image: repo
[...]

Now let's move onto docker-compose.override.yml, the one that will run by default (meaning docker-compose up or docker-compose run web command).

By default we want it to build the image from our Dockerfile, so we can do this simply by using build: .

version: '2'
services:
  web:
    build: .

The production one docker-compose.prod.yml run by using docker-compose -f docker-compose.yml -f docker-compose.prod.yml up will be similar to this one, excepting that in this case we want it to take the image from the Docker repository:

version: '2'
services:
  web:
    image: repo

Since we already have the same image: repo on our base docker-compose.yml file we can omit it here (but that's completely optional).

zurfyx
  • 27,640
  • 18
  • 109
  • 139
1

To use build instead image in docker-compose.override.yml you should replace image with local image name and then build this image with target.

In docker-compose.override.yml:


    image: username-repo-tag
    build:
      context: .
      target: username-repo-tag

In your Dockerfile you should add target to FROM tag:

FROM username/repo:tag as username-repo-tag
...
your instructions
...
Alexey Stepanov
  • 128
  • 1
  • 6
0

Had the same problem, i solved it in an other way. I find this the simple way:

version: "3"
services:
  api-gateway:
    build:
      dockerfile: ./path/to/your/Dockerfile

Leaving this here, maybe it helps some one ^^

frieren
  • 3
  • 3