0

When I am not exposing any ports when writing my Dockerfile, nor am I binding any ports when running docker run, I am still able to interact with applications running inside the container. Why?


I am writing my Dockerfile for my Node application. It's pretty simple and looks like this:

FROM node:8

COPY . .
RUN yarn
RUN yarn run build

ARG PORT=80
EXPOSE $PORT

CMD yarn run serve

Using this Dockerfile, I was able to build the image using docker build

$ cd ~/project/dir/
$ docker build . --build-arg PORT=8080

And run it using docker run

$ docker run -p 8080 <image-id>

I then accessed the application, running inside the Docker container, on an IP address like http://172.17.0.12:8080/ and it works.


However, when I removed the EXPOSE instruction from the Dockerfile, and remove the -p option in docker run, the application still works! It's like Docker is automatically binding my ports


Additional Notes:

  1. It appears that another user have experienced the same issue
  2. I have tried rebuilding my image using --no-cache after I removed the EXPOSE instructions, but this problem still exists.
  3. Using docker inspect, I see no entries for Config.ExposedPorts
dayuloli
  • 16,205
  • 16
  • 71
  • 126

1 Answers1

2

the EXPOSE command in Dockerfile really doesnt do much and I think it is more for people that read the Dockerfile to know what ports/services are running inside the container. However, the EXPOSE is usefull when you start contianer with capital -P argument (-P, --publish-all Publish all exposed ports to random ports)

docker run -P my_image

but if you are using the lower case -p you have to specify the source:destination port... See this thread

If you dont write EXPOSE in Dockerfile it doesnt have any influence to the app inside container, it is only for the capital -P argument....

Mazel Tov
  • 2,064
  • 14
  • 26
  • Thanks for your answer, but I am also not specifying the `-p` or `-P` flags, so I am not binding the ports from my host to the container. So it shouldn't be working. – dayuloli May 13 '18 at 10:03
  • ok, but the IP address `172.17.0.12` is the IP of the container so it will always succeed... the `-p` or `-P` binds the port of all host network interfaces – Mazel Tov May 13 '18 at 10:09
  • i assume you use the default docker network, and all the docker run commands are working with default docker network, if you dont want this behavior, you will have to create own `docker network` – Mazel Tov May 13 '18 at 10:10
  • from your host example: if you do `-p 9000:8080` you can access the container service at least with two options 1) `http://localhost:9000/` or 2) `http://172.17.0.12:8080` (or other container IP) – Mazel Tov May 13 '18 at 10:18
  • Right...that makes a lot more sense now thank you! I will read a bit more about networking and get back to you! Thank you very much! – dayuloli May 13 '18 at 10:38