1

I am building a Node/Mongo app using Docker and I am having trouble hitting my localhost from my host computer running MacOs when I run docker-compose up. Using postman or curl -i localhost:3000 returns nothing. I have also tried inspecting the container and connecting with that ip. What am I doing wrong? Thanks!

docker-compose.yml:

version: "2"
services:
  web:
    build: .
    ports:
      - "3000:3000"
    volumes:
      - .:/app
    env_file:
      - todoListDocker.env
    links:
      - mongo

mongo:
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=tWwp3Fm4hZUsaLw4
    volumes:
      - mongo:/data/db
    ports:
      - "27017:27017"
    env_file:
      - todoListDocker.env

volumes:
  mongo:

Dockerfile:

FROM node:boron

MAINTAINER Clinton Medbery <clintomed@gmail.com>

RUN ["apt-get", "update"]
RUN ["apt-get", "install", "-y", "vim"]

RUN mkdir - p /app
WORKDIR /app

COPY package.json /app

RUN npm install

COPY . /app
EXPOSE 3000

CMD ["npm", "start"]

Index.js:

const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

var app = express();

var router = require('./services/router');

//Use ENV Variables
console.log("Connecting to Mongo");
mongoose.connect('mongodb://root:tWwp3Fm4hZUsaLw4@mongo:27017');
// mongoose.connect('mongodb://localhost:todoList/todoList');

console.log("Connected to Mongo");


app.use(morgan('combined'));
app.use(bodyParser.json());
app.use('/v1', router);

var PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';

app.get('/hello', function (req, res) {
    console.log("Hello World");
    res.send({hello:'Hello World!'});
});

console.log('Listening on port ', HOST, PORT);
app.listen(PORT, HOST);
ShadyAmoeba
  • 527
  • 1
  • 4
  • 15

1 Answers1

2

Your express server is listening on localhost port 3000.

var PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';

This will bind to the container's localhost. That is independent from the Mac's localhost, and from any other container's localhost. You cannot reach it from outside the container.

You need to bind to the external interface of the container, which will let the Mac, or other containers, connect to the port. You can use the special address 0.0.0.0 for this.

var PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '0.0.0.0';

Now that the express server is reachable from the Mac, the port binding 3000:3000 will work. By default, that will be bound on all of the Mac's network interfaces, but you can limit it to the Mac's localhost if you prefer.

ports:
  - "127.0.0.1:3000:3000"
Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
  • That was it! Thank you sir. I marked your answer as correct. Too bad I can't vote on it with Stack Overflow's arcane rep system. I appreciate it! – ShadyAmoeba May 07 '17 at 15:08