DEV Community

Jayesh Nalawade
Jayesh Nalawade

Posted on • Originally published at jayeshdevops.hashnode.dev

Docker Port Mapping

Docker port mapping allows your containerized application to be accessed from outside the container by linking a port on the host machine to a port inside the container.

Why Port Mapping?

Containers run in isolated environments, so they don’t automatically have access to your host’s network. Port mapping lets you “expose” specific ports from the container so external requests can reach it.

For example, if you’re running a web app in a container on port 80, you can use port mapping to make it available on a specified port on your computer, like port 8080.

How to Use Docker Port Mapping

When running a container, you can map ports with the -p option in the following format:

docker run -p :

Example

Let's say you have a web server running on port 80 inside a Docker container, and you want to access it on port 8080 on your local machine.

docker run -p 8080:80 my_web_server

  • 8080: Port on the host machine (your computer).

  • 80: Port inside the container where the application is running.

  • my_web_server: Name of the Docker image.

Now, if you open http://localhost:8080 in a web browser, you’ll be able to access the application running in the Docker container.

Multiple Port Mappings

You can also map multiple ports if needed. Here’s an example where we map ports 8080 and 443 (for HTTPS):

docker run -p 8080:80 -p 8443:443 my_web_server

  • 8080:80 maps port 80 in the container to 8080 on the host.

  • 8443:443 maps port 443 in the container to 8443 on the host.

Check Mapped Ports

To check the mapped ports of running containers, use:

docker ps

This command shows the container’s details, including the port mappings under the “PORTS” column.

Common Use Cases

  1. Web Applications: Expose port 80 or 443 from the container to make the app accessible via HTTP or HTTPS.

  2. Database Containers: Map standard ports like 3306 (MySQL) or 5432 (PostgreSQL) for database access.

  3. API Services: Expose specific ports so other services can access the API.

Summary

  • Use -p : to map a container port to a host port.

  • You can map multiple ports by specifying -p multiple times.

  • Check your mappings with docker ps.

Port mapping in Docker allows applications inside containers to communicate with the outside world, enabling easy access and integration into your development or production environment.

Top comments (1)

Collapse
 
surya_f8c6194ccabac1c4a88 profile image
Surya

We can't assign -p to host network containers