DEV Community


Setting Docker build context to CWD with Compose

Alexander Chichigin
A coder pretending to be an engineer. Learning by trying lots of different stuff: programming languages, web frameworks, data analysis... He/him.
・2 min read

The problem is rather contrived so the solution is rarely needed. But if you'll ever find yourself in this situation apparently it's easy to get out. 😃

Suppose you want to run the same docker-compose with the same Dockerfile but from several subfolders and you don't like duplication. So you fave a folder structure like this:

  |- subproject1
    |- the_file.txt
  |- subproject2
    |- the_file.txt
  |- Dockerfile
  |- compose.yml
Enter fullscreen mode Exit fullscreen mode

Now you'd like to run docker-compose -f ../compose.yml up from each of subproject1 and subproject2 and for docker-compose to set the context for the Dockerfile to each of the folders respectively.

You do it with $PWD as follows:

version: "3.9"
      context: $PWD
      dockerfile: ../Dockerfile
      - "8080:8080"
      - "database"
    image: "mariadb:10.5"
    restart: "always"
      MYSQL_ROOT_PASSWORD: "secret_pass"
Enter fullscreen mode Exit fullscreen mode

in the compose.yml file. For the sake of argument we pretend we need a separate service with a database in each case.

Then you write your Dockerfile as usual:

FROM node:15

# Create app directory

RUN npm install -g http-server

# Bundle app source
COPY . .

CMD [ "http-server", "-p", "8080" ]
Enter fullscreen mode Exit fullscreen mode

And now for the subproject1 you should have the first text file exposed over the Web interface, and for the subproject2 the second text file.

Yep, as I told you from the start this is rarely needed because you rarely have two (or more) subprojects built with exactly the same Dockerfile. In the end it turned out I myself don't need this setup. But I spent surprisingly long time figuring (Googling) out the right config, so we all have it now laid out in the case we ever need it. 😃

Discussion (0)