Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Docker not correctly expose my port when using -P but works with -p 80:80?

Tags:

docker

My Dockerfile contains this:

EXPOSE 80

Yet, if I run the image with -P I can't connect to it. Running with -p 80:80 works fine.

danny@linux:~$ sudo docker run -d -P dart-test
               b3277a5483531f6dc23a1c807cf895103fd5333b603c1b4a352e07c9721f1a48

# Can't connect here
danny@linux:~$ curl http://localhost/
               curl: (7) Failed to connect to localhost port 80: Connection refused

danny@linux:~$ sudo docker stop b3277
               b3277

danny@linux:~$ sudo docker run -d -p 80:80 dart-test
               dfe68699bfb33ce33e8e6e1953ac828b9d31209988df64e2627d9228758438ba

# Connects fine here
danny@linux:~$ curl http://localhost/
               Hello, world!

danny@linux:~$ 
like image 979
Danny Tuppeny Avatar asked Sep 18 '14 19:09

Danny Tuppeny


People also ask

Does Docker automatically expose port?

By default, when you create or run a container using docker create or docker run , it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag.

How do I expose port in Docker run?

To publish a port for our container, we'll use the --publish flag ( -p for short) on the docker run command. The format of the --publish command is [host_port]:[container_port] . So if we wanted to expose port 8080 inside the container to port 3000 outside the container, we would pass 3000:8080 to the --publish flag.

Does Docker use port 80?

By default, the httpd server listens on port 80. It's not mandatory to perform port mapping for all Docker containers. Often, we will avoid opening host ports in order to keep the services of the container private or only visible to sibling containers in the same Docker network.


1 Answers

When you use -P, docker will bind the exposed port to a random high port from the range 49153 to 65535 on the docker host. To determine the actual port, you'll need to run

docker port <CONTAINER> 80

When you use -p 80:80, you specifically bind the exposed port to the host's port 80.

like image 135
dcro Avatar answered Oct 20 '22 03:10

dcro