0

i really do not understand the following command in Dockerfile

EXPOSE 8080

I built a java application and dockerized it via this Dockerfile

FROM openjdk:10-jre-slim

WORKDIR /app
COPY ./target/display-console-1.0-SNAPSHOT.jar /app

CMD ["java", "-jar", "display-console-1.0-SNAPSHOT.jar"]

My java application got a controller which listen on port 8085. So when i use it from my localhost, i just do something like

docker run -ti my-docker-hub-account/my-image -p 8085:8085

and all works perfectly !

So, what is the interest of command

EXPOSE XXXX

in Dockerfile ?

thanks by advance

  • In modern Docker, `EXPOSE` does almost nothing. In first-generation Docker networking it was needed for connections between containers (links) but newer Docker networks don't require it. The linked question has many more details about "expose" vs. "publish" as Docker verbs; note that some of its older answers do date back to when `EXPOSE ` was actually required rather than optional but standard practice. – David Maze Feb 15 '23 at 15:48

2 Answers2

0

The official documentation is pretty clear on the purpose

The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. To actually publish the port when running the container, use the -p flag on docker run to publish and map one or more ports, or the -P flag to publish all exposed ports and map them to high-order ports.

So if you use the -P (capital P) option it will expose the listed ports with EXPOSED (to random ports on the host).

And it also functions for documentation purposes to other people consuming and re-purposing those dockerfiles.

PeterT
  • 7,981
  • 1
  • 26
  • 34
0

The EXPOSE command let the docker container be accessed over network on the specified port / port range.

When you run a web service from a docker container you must use this command so that you can access it from the outside of the container.

Jib
  • 1,334
  • 1
  • 2
  • 12
  • i do not understand. In fact, if i do from another container (a bash container) : curl -X GET http://172.18.0.1:8085/display/console without using EXPOSE command in Dockerfil it works perfectly. I just bridged the two containers on the same network. So what is the interest ? – it.drive.view Feb 15 '23 at 15:50
  • @it.drive.view It works because you passed the `-p` option which does the same. The point is that you explicitly tell the users of the Dockerfile which port is needed. Usually you do not provide a ready to go command line, only resources files .. Plus you can integrate within a docker-compose yaml file – Jib Feb 15 '23 at 17:07