Search code examples
javascriptnode.jsdockerdockerfiledocker-toolbox

Unable to access the Docker nodejs container on the browser


I am using windows ver 10 home, so I am using "docker toolbox for windows" where my docker client is windows/amd64 and server is linux/amd64.

I have built a very simple nodejs application with three files.

server.js

/**


* Created by farhanx on 7/28/2018.
 */
'use strict';

const express = require('express');

// Constants
const PORT = 5000;
const HOST = 'localhost';

// App
const app = express();


app.get('/', function (req, res) {

    res.send('Hello world\n');
});

app.get('/students', function (req, res) {

    res.send('student page\n');
});

app.listen(PORT, HOST);
console.log('Running on http://'+HOST+':'+PORT);

and package.json

{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "First Last <first.last@example.com>",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.16.1"
  }
}

Docker file

FROM node:8
# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm install --only=production

# Bundle app source
COPY . .

EXPOSE 5001
CMD [ "npm", "start" ]

Then I have built my docker image successfully and ran this command

docker run -p 5001:5000 farhan/mynode

since I have mentioned port 5000 for the server inside the nodejs server file and inside the docker file I have exposed the 5001 as a port.

Now it runs fine and shows on the console that the nodejs server is running but whenever I use localhost:5001, it displays page not found. Which means somehow docker container is working fine but is not accessible to the browser.


Solution

  • Since you are using toolbox, you have to access app in your browser via http://linux_docker_host_ip:5001.

    To know the host ip, go to virtualbox, and see the docker machine's ip address. Normally you will find a network icon on right bottom corner when you click on vm in virtual box. By default the IP is '192.168.99.100'