title: Cannot connect to MongoDB via node.js in Docker
body: <p>My node.js express app cannot connect to the MongoDB in a Docker. <em>I'm not that familiar with Docker.</em></p>
  
  <p>node.js connection:</p>
  
  <pre><code>import mongodb from 'mongodb';
  ...
  mongodb.MongoClient.connect('mongodb://localhost:27017', ... );
  </code></pre>
  
  <p>Dockerfile:</p>
  
  <pre><code>FROM node:argon
  RUN mkdir /app
  WORKDIR /app
  COPY package.json /app
  RUN npm install
  COPY . /app
  EXPOSE 3000
  CMD ["npm", "start"]
  </code></pre>
  
  <p>docker-compose.yml</p>
  
  <pre><code>version: “2”
   services:
    web:
     build: .
     volumes:
       — ./:/app
     ports:
     — “3000:3000”
     links:
      — mongo
     mongo:
      image: mongo
      ports:
        — “27017:27017”
  </code></pre>
  
  <p>Build command: <code>docker build -t NAME .</code></p>
  
  <p>Run command: <code>docker run -ti -p 3000:3000 NAME</code></p>
  
  <p>Connection error:</p>
  
  <pre><code>[MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]]
    name: 'MongoError',
    message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]'
  </code></pre>