Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker EXPOSE vs command line -p option (boot2docker)

After spending way too long trying to access my node server running from a docker container within a boot2docker instance I realised the issue came down to a difference between expose and docker run -p.

In my Dockerfile I had EXPOSE 3001, and I could not access this via my host machine.

After running "docker run -p 3001:3001 myappinst myapp" I was able to access the port.

Up until now I thought "docker run -p 3001:3001" was essentially the same as EXPOSE 3001 in the dockerfile.

I noticed however, when running docker ps

I get the following for "EXPOSE":

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 16341e2b9968 housemation-crawler:latest "npm start" 2 minutes ago Up 2 minutes 3001/tcp housemation-crawler-inst

(note: 3001/tcp)

vs the below with docker run -p 3001:3001

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 0b14f736033c housemation-crawler:latest "npm start" 8 seconds ago Up 2 seconds 0.0.0.0:3001->3001/tcp housemation-crawler-inst

(0.0.0.0:3001->3001/tcp)

Looks like the latter is doing some kind of port forwarding, whereas the former is just opening up the port? Would that be right?

If I wanted to access a non forwarded exposed port how would I go about doing so? Also, if I wanted to have port forwarding within the dockerfile, what would be the correct syntax?

like image 837
Melbourne2991 Avatar asked Feb 01 '15 08:02

Melbourne2991


1 Answers

Your assumptions about how EXPOSE in Dockerfile and -p option in docker run are right. As you can read in Docker on line documentation:

EXPOSE <port> [<port>...]

The EXPOSE instructions informs Docker that the container will listen on the specified network ports at runtime. Docker uses this information to interconnect containers using links (see the Docker User Guide) and to determine which ports to expose to the host when using the -P flag. Note: EXPOSE doesn't define which ports can be exposed to the host or make ports accessible from the host by default. To expose ports to the host, at runtime, use the -p flag or the -P flag.

So the EXPOSE instruction in Dockerfile will indicate Docker which ports have to map to host if you run the container with the -P flag; but the local ports mapped are not deterministic and are chosen by Docker at run time. Apart from this, Docker will use the ports in EXPOSE to export information as environmental variables in linked containers.

If you want to set the local port mapped, you have to use the -p option in docker run.

like image 115
Javier Cortejoso Avatar answered Oct 30 '22 18:10

Javier Cortejoso