FROM another Dockerfile" in your Dockerfile


I have two services in my docker-compose.yml file that are built from two different Dockerfiles, Dockerfile.foo and Dockerfile.bar. However, both Dockerfile.{foo, bar} share the same first half, and only differ in the latter parts.

Is it possible to build the two services using a single base Dockerfile.common to avoid unnecessary duplicate builds and maintenance?

# ...
services:
  service1:
    build:
      context: .
      dockerfile: Dockerfile.foo
  service2:
    build:
      context: .
      dockerfile: Dockerfile.bar
# ...

Update:

I want to use docker-compose to automate the build process, where first docker build -f Dockerfile.common -t common . is executed, and then docker build -f Dockerfile.foo -t foo . && docker build -f Dockerfile.bar -t bar . so that Dockerfile.{foo, bar} can refer to the common image.

Yes, it is possible to use a single base Dockerfile.common to build both services and avoid duplicate builds and maintenance.

Here’s how you can achieve this:

  1. Create a Dockerfile.common file that contains the shared first half of the Dockerfile:
# Dockerfile.common
# Shared base Dockerfile contents
  1. Update your docker-compose.yml file to specify the Dockerfile.common as the dockerfile for both services:
# ...
services:
  service1:
    build:
      context: .
      dockerfile: Dockerfile.common
  service2:
    build:
      context: .
      dockerfile: Dockerfile.common
# ...
  1. Update your Dockerfile.foo and Dockerfile.bar files to include the remaining specific parts after the shared base:
# Dockerfile.foo
FROM common

# Remaining foo-specific instructions
# Dockerfile.bar
FROM common

# Remaining bar-specific instructions
  1. Finally, run the following commands to automate the build process using docker-compose:
docker-compose build --build-arg common_image=common

This will first build the common image using Dockerfile.common and tag it as common. Then, it will build the service1 and service2 images using the respective Dockerfile.foo and Dockerfile.bar, which both reference the common image.

Note: In your Dockerfile.foo and Dockerfile.bar, make sure to use the common image as the base image by specifying FROM common.