Thursday, October 20, 2022

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

Issue

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?

Solution

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"


Answered By - prisar
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.