Working with Multiple Dockerfiles

A guide for using multiple Dockerfiles

Multiple Dockerfile use cases

There might be a situation where we need to have multiple Dockerfiles for different services.

Examples could be:

  • Creating a microservices app
  • Dockerfile for different environments such as development, production

In these cases, you have to tell docker-compose the Dockerfile it should consider for creating that specific service.

By default, docker-compose looks for a file named Dockerfile. Dockerfiles can have any name. It’s just a file without any extension. We can override the default behaviour using dockerfile:'custom-name' directive inside the build section.

Implementation

Let’s see this in action. We will add a new file called Dockerfile-db in the DB folder and make some changes in the docker-compose.yml file.

In the build section, we have

context: ./db
dockerfile: Dockerfile-db

context: Use this to specify the directory of Dockerfile or alternate Dockerfile relative to docker-compose.yml file

dockerfile: As mentioned in the note above, specify the name of alternate Dockerfile if it is not named as Dockerfile

Get hands-on with 1400+ tech skills courses.