dockerdocker-compose

Build docker image that depends on a local "Dockerfile"


I have the following folder structure:

my_package
|- docker_compose.yml
|- a
   |- Dockerfile
|- b
   |- Dockerfile

Here, my docker-compose.yml is:

version: '2'
services:
  a:
    build: 
      context: a
      dockerfile: Dockerfile
  b:
    build: 
      context: b 
      dockerfile: Dockerfile

When I run docker-compose build I expect two output images, one for a and one for b.

Here's a/Dockerfile

FROM ubuntu
RUN touch AAA

Here's b/Dockerfile

FROM <a> # NOT SURE WHAT TO PUT HERE
RUN touch BBB

I would like the b image to contain two files in the rootdir, AAA and BBB, which requires one Dockerfile to depend on another.

Is this possible? Is there any workaround to make two Docker images (with a dependency between them) build in one docker-compose build command?

I'm stuck with Docker version 1.12.6, build 78d1802 (which is compatible with version 2 syntax only).


Solution

  • You can use depends_on in your docker-compose.yml, I know it is available in docker-compose YAML version 3, to express that service B depends on A and docker-compose will follow the dependency chain you express and build A first. See an explanation of depends_on here.

    Since B is FROM A as your Dockerfile for B expresses both files AAA and BBB will be available in service B as long as the permissions for file AAA and file BBB are the same and in the this case you are running as root in both service A and service B when you execute the touch command.

    version: '3'
    services:
      a:
        build: 
          context: a
          image: a
          dockerfile: Dockerfile
      b:
        build: 
          context: b 
          image: b
          dockerfile: Dockerfile
        depends_on: 
        - a
    

    Edit (by OP):

    1. You can use depends_on in v2 too, but using an array.
    2. Make sure to add the image in the docker-compose.yml to specify the generated image, so that b can be generated FROM a