0

I am trying to expose port 3000 of my container to the host. This is the command I am using:

docker run -ti --expose=3000 -p 3000:3000 dockerName

On the PORTS section of docker ps I see 0.0.0.0:3000->3000/tcp.

When I try to connect to a simple NodeJS server on that port I get Unable to connect. I am running Docker 18.03.0-ce and the latest version of NodeJS.

I try to connect through localhost (127.0.0.1) IP, the internal container IP (172.17.0.1), the IP issued by the host OS (172.17.0.1) and the host IP all without success. I have also completely disabled the firewall on the host OS.

Here is the NodeJS code, which works fine on the host:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

Is there any way to get this to work inside the container and connect to it through the host OS?

Emil Zahariev
  • 137
  • 3
  • 10
  • Possible duplicate of [docker react does not work in localhost](https://stackoverflow.com/questions/48977194/docker-react-does-not-work-in-localhost) – johnharris85 Mar 25 '18 at 21:33

1 Answers1

7

The reason you cannot connect is because your Node.js app listens on IP 127.0.0.1 which is not available outside the container.

Change your app so that it listens on IP 0.0.0.0 and you will be able to connect properly.

mike
  • 5,047
  • 2
  • 26
  • 32
  • That worked. Thank you! Out of curiosity, why does't the initial method work and is there a way to make it work? – Emil Zahariev Mar 26 '18 at 04:20
  • The initial method did not work because the app was listening on localhost interface which is not accessible outside the container. Docker uses networking to connect to containers and since localhost is not accessible outside the host, it's not available outside container as well. The only way around this is to create port mapping within the container but that's more effort than benefit. If you're worried about security, bind the docker's listening address to 127.0.0.1 and you will achieve the same result. – mike Mar 26 '18 at 14:02
  • Thanks for the info. – Emil Zahariev Mar 26 '18 at 17:39