Nestjs monorepo with relative environment variables in docker-compose

Viewed 1801

I am creating Nestjs based microservices & used nestjs cli to create monorepo. After creating monorepo, I created Dockerfile and docker-compose files both in root path of project. Then I created .env file inside each nest app & referenced it in docker-compose file against respective services. Because of relative .env files, docker-compose won't run from root path rather from where the .env file is placed i.e. nest app & it works perfectly. Services startup & I can play around with the app fine. Now the problem is that I cannot make it hot-reload or live-reload docker service from host even though I have setup volumes correctly, I believe.

The basic directory structure is given below:

apps/
    nest-auth/.env
    queues/.env
package.json
Dockerfile
docker-compose.yaml

And here are respective Dockerfile & docker-compose files following above structure.

FROM node:14.16.0 As development

ARG APP_TO_BUILD

WORKDIR /demo/app

COPY package*.json ./

RUN npm install --only=development
RUN npm install argon2 --build-from-source

COPY . .

RUN npm run build -- ${APP_TO_BUILD}

CMD ["sh", "-c", "npm start -- ${APP_TO_BUILD}"]
version: "3.7"

services:
  api:
    image: "demo-main-app:${IMAGE_TAG}"
    container_name: main_app
    build:
      context: .
      target: ${NODE_ENV}
      args:
        APP_TO_BUILD: ${APP_TO_BUILD}
    volumes:
      - ./apps/nest-auth:/demo/app/apps/nest-auth
      - /demo/app/node_modules
    ports:
      - 3000:3000
    env_file:
      - ./apps/nest-auth/.env
      - ./apps/nest-auth/docker.env
    networks:
      - demo

  worker:
    image: "demo-worker:${IMAGE_TAG}"
    container_name: worker_app
    build:
      context: .
      target: ${NODE_ENV}
      args:
        APP_TO_BUILD: ${APP_TO_BUILD}
    volumes:
      - ./apps/queues:/demo/app/apps/queues
      - /demo/app/node_modules
    env_file:
      - ./apps/queues/.env
      - ./apps/queues/docker.env
    networks:
      - demo
    depends_on:
      - redis

  redis:
    container_name: redis
    image: redis:6
    ports:
      - 6379:6379
    networks:
      - demo

networks:
  demo:
    external: false
    name: demo-network

1 Answers

Not sure if I understood your question (I see no question though...) but, you can trick the environment by doing:

apps/
    nest-auth/.env
    queues/.env
.env <------------- add this file
package.json
Dockerfile
docker-compose.yaml

then in .env you can have the path defined for each environemnt:

# content of .env file
QUEUES_ENV=./queues/.env
AUTH_ENV=./nest-auth/.env

and last, in docker-compose.yml you would use it:

# ... stuff here ...:

  api:
    # ... stuff here ...
    env_file:
      ${AUTH_ENV}

  worker:
    # ... stuff here ...
    env_file:
      ${QUEUES_ENV}
Related