Exposing Container Ports in Docker

docker
Reading Time: 3 minutes

Hi Readers, Docker is an open source platform adopted widely to ease the developing, shipping, and running applications. Docker has a object named containers isolates the applications from the infrastructure and avoids any external affect on the development environment.

In this blog we will see some network part of containers. We will see how to enable communication of the container to the outside world or to the other containers. We do this by exposing ports and mapping these ports. Let’s see how we can do that.

Need of exposing ports.

  • When a container is created using docker create or docker run, by default it does not publish any of its ports to the outside world.
  • In order to make a port available to services outside of Docker, or to Docker containers which are not connected to the container’s network, we can use the -P or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host to the outside world.
  • -p or –publish list : Publishes a container’s port(s) to the host.
  • -P or –publish-all : Publishes all exposed ports to random ports.

Let’s see how we can achieve this,

Create a nginx container without any port mapping,
docker container run -d nginx

This will pull the nginx image from the docker hub and create a container for us.

Check the port for nginx container
docker container ls

This shows the nginx container. We have tcp port for port 80. However it is yet not mapped.

Check if we get any response from localhost
curl localhost

Connection refused because we don’t have port mapping set for port 80.

Get the privateIP of the container
docker inspect container

Execute

curl This will give content of nginx home page.

Expose port 3000 on container

Once we expose the port, it means now this port is available to be mapped. We can re-map them using -p or -P flag.

docker container run -d --expose 3000 nginx

Verify if port 3000 is open
docker container ls

Alternatively we can expose and map the port at the same time,

docker container run -d --expose 3000 -p 80:8080
80: port that will be running on host machine.
8080: container port mapped with port 80.
Mapping TCP and UDP ports
docker container run -d -p 8081:80/tcp -p 8081:80/udp nginx

curl localhost:8081

We can see all the port mappings for specified container,

docker container port <containerID>

That’s all for this blog. Thanks for sticking till the end. In case of any queries you can contact me over my email id nitin.mishra@knoldus.com

References:

Docker

Written by 

Nitin Mishra is a Software Consultant at Knoldus Software LLP. He has done MCA from GGSIPU and completed Bachelor of Science in Computer Science from Delhi University. He is a tech enthusiast with good knowledge of Java. He is majorly focused in DevOps practice. On personal front he loves to travel mountains and writes poetry.