Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 754
delux Avatar asked Oct 04 '18 15:10

delux


People also ask

Does Docker compose pass environment variables?

Docker Compose allows us to pass environment variables in via command line or to define them in our shell. However, it's best to keep these values inside the actual Compose file and out of the command line.


1 Answers

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"
like image 189
prisar Avatar answered Oct 04 '22 09:10

prisar