The EXPOSE instruction exposes a particular port with a specified protocol inside a Docker Container. In the simplest term, the EXPOSE instruction tells Docker to get all its information required during the runtime from a specified Port. These ports can be either TCP or UDP, but it’s TCP by default. It is also important to understand that the EXPOSE instruction only acts as an information platform (like Documentation) between the creator of the Docker image and the individual running the Container. Some points to be noted are:
- It can use TCP or UDP protocol to expose the port.
- Default Protocol is TCP if no other protocol is specified.
- It does not map ports on the host machine.
- It can be overridden using the publish flag (-p) while starting a Container.
The syntax to EXPOSE the ports by specifying a protocol is:
Syntax: EXPOSE <port>/<protocol>
In this article, we are going to discuss some practical examples of how to use EXPOSE instruction in your Dockerfile and overriding it using the publish flag while starting a Docker Container.
Follow the below steps to implement the EXPOSE instruction in a docker container:
Step 1: Create a Dockerfile with EXPOSE Instruction
Let’s create a Dockerfile with two EXPOSE Instructions, one with TCP protocol and the other with UDP protocol.
FROM ubuntu:latest EXPOSE 80/tcp EXPOSE 80/udp
Step 2: Build the Docker Image
To build the Docker Image using the above Dockerfile, you can use the Docker Build command.
sudo docker build -t expose-demo .
Step 3: Running the Docker Container
To run the Docker Container, you can use the Docker run command.
sudo docker run -it expose-demo bash
Step 4: Verify the Ports
To verify the ports exposed, you can use the Docker inspect command.
sudo docker image inspect --format='' expose-demo
In the above screenshot, you can see the ExposedPorts object contains two exposed ports that we have specified in the Dockerfile.
Step 5: Publishing the ports
To publish all the exposed ports, you can use the -p flag.
sudo docker run -P -d expose-demo
Step 6: Checking published ports
You can just the list containers to check the published ports using the following command. But make sure that the Container is running.
sudo docker start <container-id> sudo docker container ls
To conclude, in this article, we discussed how to use the EXPOSE instruction inside a Dockerfile to expose ports of a Container using a specified protocol and use -p flag to publish the ports.
Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.