Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker: cannot open port from container to host

I'm using Docker for Mac. I have a container that run a server, for example my server is run on port 5000. I have exposed this port on Dockerfile

When my container is running, I connect to this container and check and if this server is working or not by running below command and see that it returns data (a bunch of html and javascript)

wget -d localhost:5000

Notes, I start this container and also publish port outside by command:

docker run -d -p 5000:5000 <docker_image_name>

But at docker host (is my mac and running El Capitan), I open chrome and go to address localhost:5000. It doesn't work. Just a little note, if I go to any arbitrary port such as localhost:4000 I see error message from chrome such as:

This site can’t be reached
localhost refused to connect.

But error message for localhost:5000 is:

The localhost page isn’t working
localhost didn’t send any data.

So it seems I have configured work "a little" but something wrong. Please tell me how to fix this.

like image 241
Trần Kim Dự Avatar asked Nov 27 '16 08:11

Trần Kim Dự


People also ask

How do I access the host port in a Docker container?

Use --net="host" in your docker run command, then localhost in your docker container will point to your docker host. THIS! This is the answer!

How do you expose a port to host a container?

You can expose a port through your Dockerfile or use --expose and then publish it with the -P flag. This will bind the exposed port to your Docker host on a random port (verified by running docker container ls ). You can expose a port through your Dockerfile or use --expose and then publish it with the -p 80:80 flag.

How do I access exposed port Docker?

There are several ways to do this: you can expose a port via the --expose flag at runtime, or include an EXPOSE instruction in the Dockerfile. You can also publish ports by using the -p or -P flags in the Docker run string. There's also container linking via --link .


1 Answers

Please check the program in container is listening on interface 0.0.0.0.

In container, run command:

ss -lntp

If it appears like:

LISTEN  0   128   127.0.0.1:5000  *:*

that means your web app only listen at localhost so container host cannot access to your web app. You should make your server listen at 0.0.0.0 interface by changing your web app build setting.

For example if your server is nodejs app:

var app = connect().use(connect.static('public')).listen(5000, "0.0.0.0");

If your server is web pack:

 "scripts": {
    "dev": "webpack-dev-server --host 0.0.0.0 --port 5000 --progress"
  }
like image 63
Cuong Tran Avatar answered Sep 27 '22 23:09

Cuong Tran