How to pass environment variables from docker-compose into the NodeJS project?

delux picture delux · Oct 4, 2018 · Viewed 17.5k times · Source

I have a NodeJS application, which I want to docker-size.

The application consists of two parts:

  • server part, running an API which is taking data from a DB. This is running on the port 3000;

  • client part, which is doing a calls to the API end-points from the server part. This is running on the port 8080;

With this, I have a variable named "server_address" in my client part and it has the value of "localhost:3000". But here is the thing, the both projects should be docker-sized in a separate Dockerimage files and combined in one docker-compose.yml file.

So due some reasons, I have to run the docker containers via docker-compose.yml file. So is it possible to connect these things somehow and to pass the server address externally from dockerfile into the NodeJS project?

docker-composer.yml

version: "3"
services:
  client-side-app:
    image: my-client-side-docker-image
    environment:
      - BACKEND_SERVER="here we need to enter backend server"
    ports:
      - "8080:8080"
  server-side-app:
    image: my-server-side-docker-image
    ports:
      - "3000:3000"

both of the Dockerfile's looks like:

FROM node:8.11.1
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "dev"]

by having these files, I have the concern:

  • will I be able to use the variable BACKEND_SERVER somehow in the project? And if yes, how to do this? I'm not referring to the Dockerimage file, instead into the project itself?

Answer

prisar picture prisar · Oct 4, 2018

Use process.env in node.js code, like this

process.env.BACKEND_SERVER

Mention your variable in docker-compose file.

version: "3"
services:
  client-side-app:
    image: my-client-side-docker-image
    environment:
      - BACKEND_SERVER="here we need to enter backend server"
    ports:
      - "8080:8080"
  server-side-app:
    image: my-server-side-docker-image
    ports:
      - "3000:3000"