title: connecting to local mongodb from docker container
body: <p>I have a local mongoDB server running on mongodb://127.0.0.1:27017. My DB name is <em>localv2</em>. I have a node/express app with the Dockerfile as follows:</p>
  
  <pre><code>FROM node:7.5
  
  RUN npm install -g pm2
  
  RUN mkdir -p /usr/src/app
  WORKDIR /usr/src/app
  
  COPY package.json /usr/src/app
  RUN npm install
  
  COPY . /usr/src/app
  
  EXPOSE 3002
  
  ENV NODE_ENV local
  
  CMD pm2 start --no-daemon server.js
  </code></pre>
  
  <p>The server.js file has a connection to local mongodb with the following code:</p>
  
  <pre><code>app.db = mongoose.connect("mongodb://127.0.0.1:27017/localv2", options);
  </code></pre>
  
  <p>This doesn't work when I spin up a container from the image created using the Dockerfile above. I read somewhere that Docker creates a VLAN with a gatway IP address of its own. When I <code>docker inspect</code> my container, my gateway IP address: 172.17.0.1.</p>
  
  <p>Even on changing the mongodb connection to </p>
  
  <pre><code>app.db = mongoose.connect("mongodb://172.17.0.1:27017/localv2", options)
  </code></pre>
  
  <p>and re-building the image and starting a new container, I still get the error:</p>
  
  <pre><code>MongoError: failed to connect to server [172.17.0.1:27017] on first connect [MongoError: connect ECONNREFUSED 172.17.0.1:27017]
  </code></pre>
  
  <p>Command to run the container: <code>docker run -p 3002:3002 image-name</code></p>
  
  <p>Please help.</p>