DEV Community

Alexander Chichigin
Alexander Chichigin

Posted on

3 2

Setting Docker build context to CWD with Compose

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:

project
  |- 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"
services:
  assignment:
    build:
      context: $PWD
      dockerfile: ../Dockerfile
    ports:
      - "8080:8080"
    depends_on:
      - "database"
  database:
    image: "mariadb:10.5"
    restart: "always"
    environment:
      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
WORKDIR /app

RUN npm install -g http-server

# Bundle app source
COPY . .

EXPOSE 8080
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. 😃

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay