dayuloli
dayuloli

Reputation: 17021

Docker automatically binds port

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

Upvotes: 0

Views: 2015

Answers (1)

Mazel Tov
Mazel Tov

Reputation: 2182

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....

Upvotes: 2

Related Questions