Docker EXPOSE
Confused what EXPOSE:8080 is ?
It means that containers are listening at the port 8080 at runtime and this port is not accessible to us until we map it
i.e. we need to tell it explicitly through which port of our host machine we will interact to it's listening port.
Also, container will be able to communicate at port 8080 with other container i.e just communication among their own buddies be on same docker network. It all works on what port is being defined for communication.
Ex:
There are two containers i.e foo1
and foo2
who are running some application and some server respectively.
Expose ports for these containers are 8080 and 8060 respectively
now due to some requirement application need to have access to server.
foo1
will try to communicate to foo2
, but how ? port 8060 when exposed foo1
will try to connect to this exposed port and get the work done.
Now, suppose my application is running on localhost:8080 which is inside the container foo1
, cant just simple ping to localhost:8080. It will not work. I need to specify same port as that of my application running to the container's port because my application to run on 8080 it is just using 8080 port of the foo1
container nothing magical its using. When expose port say - 8888 it's just means my application is running on container's port 8080 and I have exposed the container's port 8888 which is entirely unrelated.
Now map container's port 8080 to some port of my host machine, lets say 9090. hence, my machine's port 9090 will be able to communicate to container at 8080
But the question is without mapping will it be able to communicate with my host machine? yes it does but at random port and we would need to check manually.
some trials for clear understanding:
My docker image name is hello-world
- Without writing EXPOSE in Dockerfile, run
docker run -d helloworlddocker container ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
69ced831b0c5 hello-world "/bin/sh -c 'java -j…" 10 seconds ago Up 8 seconds jovial_proskuriakova
Which port it is communicating? None ! Because wwe dint tell it even if it can communicate.
- Write EXPOSE 8080
docker run -d helloprojectdocker container ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d9b72209fc15 hello-world "/bin/sh -c 'java -j…" 26 seconds ago Up 25 seconds 8080/tcp zealous_gould
8080 is communication port. But our host machine cant communicate ! Need to map it.
- Map ports (without writing EXPOSE in Dockerfile one of the alternative)
docker run -d -p 9090:8080 helloprojectdocker container ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4e396e85bd6d hello-world "/bin/sh -c 'java -j…" 5 seconds ago Up 3 seconds 0.0.0.0:9090->8080/tcp infallible_liskov
My java application will be pinged on 9090 !
because that's my host machine's port connected accessing my application through container's port on which my java application is running.
Syntax docker run -p <HOST_PORT>:<CONTAINER:PORT> IMAGE_NAME