thatguy
thatguy

Reputation: 410

Environment variables not loading inside docker container

I have two services which are dockerized. The first service is the api service which depends on the mongo service. However, for some reason, the api service can't connect to the mongo service because the environment variables inside the container are not been passed around well. I have two variables in my .env namely JWT_SECRET=somesecret DB_URL_LOCAL=mongodb://mongo:27017/apii I tried setting the environment variables in the docker-compose file, when I run docker-compose config I see the variables and their values displayed, but my application can't detect these variables. MongoDB keeps throwing UnhandledPromiseRejectionWarning: MongoParseError: URI malformed, cannot be parsed error.

I also tried to set the environment variables in the main Dockerfile but it still didn't work. Please I need some assistance. Here is a copy of my Dockerfile and docker-compose.yml file.

This is the Dockerfile

FROM node:12-alpine AS base

WORKDIR /usr/src/app

FROM base AS build

COPY package*.json .babelrc ./
RUN npm install
COPY ./src ./src
RUN npm run build
RUN npm prune --production


FROM base AS release

COPY --from=build /usr/src/app/node_modules ./node_modules
COPY --from=build /usr/src/app/dist ./dist
USER node
EXPOSE 4000

CMD [ "node", "./dist/server/server.js" ]

This is the docker-compose.yml file

version: '3.8'
services:
  api:
    build: .
    image: api
    working_dir: /usr/src/app
    expose:
      - 4000
    ports:
      - '4000:4000'
    depends_on:
      - mongo
  mongo:
    container_name: mongo
    env_file:
      - .env
    environment:
      - DB_URL_LOCAL=$DB_URL_LOCAL
      - JWT_SECRET=$JWT_SECRET
    image: mongo
    volumes:
      - './data:/data/db'
    ports:
      - 27017:27017
    restart: always

Thank you.

Upvotes: 0

Views: 1602

Answers (1)

Akinjide
Akinjide

Reputation: 2763

In docker-compose.yml, environment variables should be declared in api service not mongo service with something like this MONGO_INITDB_DATABASE=${DATABASE}

Use this, env_file is an alternative, read more:

version: '3.8'
services:
  api:
    build: .
    image: api
    working_dir: /usr/src/app
    expose:
      - 4000
    ports:
      - '4000:4000'
    env_file:
      - ./secret.env
    environment:
      - DB_URL_LOCAL=${DB_URL_LOCAL}
      - JWT_SECRET=${JWT_SECRET}
    depends_on:
      - mongo

  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - './data:/data/db'
    ports:
      - 27017:27017
    restart: always

Upvotes: 1

Related Questions