Exposing network port on Docker container is essential and part of almost any Docker deployment with or without a Dockerfile.
When building Docker images with a Dockerfile, we can use the expose statement to open a network port.
Important note: The expose statement will not open the port when deploying a container from the image. We need to use the -p switch with docker run as you will below actually to open the port.
In the following example, I have a Dockerfile that deploys an Nginx web server and copy a simple HTML file to the default site.
FROM nginx:latest COPY ./index.html /usr/share/nginx/html/index.html EXPOSE 80/tcp
To build the image, I will run the command below.
docker build --tag mynginx .
To deploy a container from the new build, I will run
docker run -p 127.0.0.1:80:80 mynginx
The result is shown below.
Remember that the expose statement help team members and engineers understand how the application is configured and which ports are needed to be exposed and open to the outside world.