Docker can build images automatically by reading the instructions from a Dockerfile.
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.
Using “docker build” anyone can create an automated build that executes several command-line instructions in succession.
Many times people failed to understand difference between “expose” and “publish” in Docker. We use these options in some context and today lets try to understand it. What does it mean to EXPOSE a port in your Dockerfile?
The EXPOSE instruction
The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. You can specify whether the port listens on TCP or UDP, and the default is TCP if the protocol is not specified.
Thus, Writing EXPOSE in your Dockerfile, is merely a hint that a certain port is useful. Docker won’t do anything with that information by itself.
The EXPOSE instruction exposes the specified port and makes it available only for inter-container communication. Let’s understand this with the help of an example.
We can use “expose” and “publish” and three following context as below;
- Neither specify EXPOSE in dockerfile nor -p in commandline – Container would be accessible inside a host machine but not on host ip:port
- Only specify EXPOSE in dockerfile – You expose ports using the EXPOSE keyword in the Dockerfile or the –expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional. You stil be able to access a container from inside a host.
- Specify EXPOSE in dockerfile and -p in commandline – If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker host.
- If you do -p, but do not EXPOSE –
Short answer:
- EXPOSE is a way of documenting
- –publish (or -p) is a way of mapping a host port to a running container port
So EXPOSE helps in inter-container communication. What if, there’s a need to bind the port of the container with that of the host machine on which the container is running?
Pass the -p (lower case p) as a option to the docker run instruction as follows
One benefit of using the EXPOSE instruction, whether you are running a multi-container application or not, is that it helps others understand what port the application listens by just reading the Dockerfile without the need of going through your code.
Docker Tutorials Fundamental To Advanced-2021 Crash Course:- https://bit.ly/3hOIbTB
- Implementing Managed IT Services: A Step-by-Step Guide - August 30, 2024
- DevOps Foundation Certification - August 29, 2024
- SRE Foundation Certification - August 29, 2024
Article about EXPOSE and failed to provide a single example of its usage.