Bogdan
Bogdan

Reputation: 77

Cannot connect to the MongoDB server from node by using the environmental system variables set in Docker

I am trying to build a Docker image using a node and a mongodb image but I cannot set the environmental variables from the Dockerfile or docker-composer.

Dockerfile:

FROM node

RUN mkdir /app WORKDIR /app COPY package.json /app

RUN npm install COPY . /app

ENV MONGODB_URI 192.168.99.100/myapp

EXPOSE 3030

CMD ["npm", "start"]

docker-compose.yml:

version: "2"

services:

web:

build: .

volumes:

  - ./:/app

ports:

  - "3030:3030"

environment:

  - MONGODB_URI="192.168.99.100/myapp"

links:

  - "mongo"

mongo:

image: "mongo"

ports:

  - "27017:27017"

volumes_from:

  - mongodata

mongodata:

image: tianon/true

volumes:

  - /data/db

I am trying to get the MONGODB_URI from inside a config object. The console.log returns the expected result but I still get an error.

class Config {

constructor() {
    this.port = process.env.PORT || 3030;
    console.log(process.env.MONGODB_URI);
    this.databaseUrl = process.env.MONGODB_URI || 'localhost/myapp';
}

The error I get is:

Error: no hostname or hostnames provided in connection string web_1 | at module.exports (/app/node_modules/mongodb/lib/url_parser.js:24:11)

If I try to use the URL directly, without relying on environmental variables, it works fine and I get a connection.

Upvotes: 2

Views: 897

Answers (1)

Bogdan
Bogdan

Reputation: 77

Well, apparently I just got my rubber duck style answer.

The issue was with the '- MONGODB_URI="192.168.99.100/myapp"'. The value should not be wrapped in quotes.

I set it to "MONGODB_URI=192.168.99.100/myapp" and it works fine.

Upvotes: 3

Related Questions