Docker

Docker Compose Environment Variable and Quotes

TLDR: Do not put any double quotes or single quotes into the environment parameter in the docker-compose.yml file. Do we really need the long version of the story?

Instead of this:

version: '3.2'
services:
  mongo:
    image: mongo:4.1.13-bionic
    environment:
      - MONGO_DATABASE=market-inventory
    ports:
      - "27017:27017"
    networks:
      - service-local
  web:
    build: .
    expose:
      - "3000"
    ports:
      - "3000:3000"
    environment:
      - MONGO_URL="mongodb://mongo/market-inventory"
    depends_on:
      - mongo
    networks:
      - service-local
networks:
  service-local:
    driver: bridge

Use this instead:

version: '3.2'
services:
  mongo:
    image: mongo:4.1.13-bionic
    environment:
      - MONGO_DATABASE=market-inventory
    ports:
      - "27017:27017"
    networks:
      - service-local
  web:
    build: .
    expose:
      - "3000"
    ports:
      - "3000:3000"
    environment:
      - MONGO_URL=mongodb://mongo/market-inventory
    depends_on:
      - mongo
    networks:
      - service-local
networks:
  service-local:
    driver: bridge

Now this is odd as I don’t present the problem first. I usually starts with a problem, then the solution. So my problem was that my app is not able to connect to my MongoDB server due to some connection refused error. I tried to debug it by logging in into the container and pinged the MongoDB server and it actually responded.

It turns out that my NestJS app captured the environment variable MONGO_URL with double quotes after I tried to log it. I just removed the double quotes and it already works. Now, there is actually an alternative syntax that will prevent that issue.

environment:
  MONGO_INITDB_ROOT_USERNAME: root
  MONGO_INITDB_ROOT_PASSWORD: example

However, I didn’t changed my config anymore. Maybe later. Maybe never. Will find out.

Leave a reply

Your email address will not be published. Required fields are marked *