Ports Availability
Learn about port mapping and how to ensure their availability.
We'll cover the following...
Port mapping can be defined as exposing the services inside a container to the host system or external network. It allows traffic to be routed from a specific port on the host to a port within the container. This helps enable communication between the host system and the containerized application. Docker containers operate in an isolated network environment, and the ports aren’t accessible from the host or external network. Port mapping fixes this issue, making containers accessible.
Various ways of port mapping
In Docker, there are various ways to perform port mapping. Here are some of those methods:
Using the
docker runcommand: Thedocker runcommand automatically maps a container to a port whether it’s specified or not. It’s written this way:
docker run -d <image_name>
There are occasions when we want to specify the mapping to a particular port. We’ll then write it this way:
docker run -p 8080:80 <image_name>
Specifying port mapping in a Docker compose file: In a
docker-compose.ymlfile, we can define port mappings for services using theportsdirective. We illustrate that below.
services:web:image: nginxports:- 8080:80
Exposing ports in Dockerfile: In the case where ports are exposed in Dockerfile, there’ll still be a need to use the same port when running the
docker runcommand. If we don’t use the port specified on the Dockerfile when using thedocker runcommand, the port mapping will still work, as long as the port specified in thedocker runcommand is available on the host ...