Docker Compose: Specify a Dockerfile with a custom name

Date: 2021-05-15 | docker | docker-compose | dockerfile |

Problem

Typically when you run docker commands like docker or docker-compose on a directory, it will look for files with default names like Dockerfile or docker-compose.yml. This is simple and easy to understand but can lead to some problems if we want to configure multiple of these Docker files in the same directory.

Here's how you can have multiple Dockerfiles in the same directory with different names and specify them for usage in a docker-compose.yml

Solution

Okay so let's say we've got a directory with a docker-compose.yml and a few Dockerfiles like so:

docker-compose.yml
test.Dockerfile
Dockerfile

We can specify that we want to run these by using docker-compose's build configuration. Here's an example:

# docker-compose.yml

version: "3"
services:
  tests:
    build: 
      context: ./
      dockerfile: ./test.Dockerfile
    container_name: tests
  source:
    build: ./

In this example source is building from the current directory (./) and since we didn't give it any explicit instructions to look for a different Dockerfile will look for the default: Dockerfile that we have in our directory.

For tests however, we provide a context (a folder from which to run the Dockerfile) and a dockerfile which specifies which Dockerfile we want run and allows us to use a different name.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.