Docker Port Mapping Strategies

Master Docker port mapping with -p flag. Learn host-to-container port mapping, binding to specific interfaces, random port assignment, and UDP ports.

Container Lifecycle

Detailed Explanation

Port Mapping with -p

Docker port mapping connects host network ports to container ports, making containerized services accessible.

Basic Syntax

# Map host port 8080 to container port 80
docker run -d -p 8080:80 nginx

# Map multiple ports
docker run -d -p 8080:80 -p 443:443 nginx

Binding to Specific Interfaces

By default, -p binds to all interfaces (0.0.0.0). Restrict to localhost for security:

# Only accessible from localhost
docker run -d -p 127.0.0.1:5432:5432 postgres:16

# Bind to a specific IP
docker run -d -p 192.168.1.100:80:80 nginx

Random Port Assignment

Let Docker assign a random available host port:

docker run -d -p 80 nginx

# Check the assigned port
docker port <container-id>

UDP Ports

Specify the protocol for non-TCP ports:

docker run -d -p 53:53/udp dns-server
docker run -d -p 53:53/tcp -p 53:53/udp dns-server

Port Ranges

Map a range of ports at once:

docker run -d -p 8000-8010:8000-8010 my-app

Checking Published Ports

docker port my-container
# 80/tcp -> 0.0.0.0:8080
# 80/tcp -> [::]:8080

Use Case

Exposing web applications and APIs during development, securing database ports by binding to localhost only, running multiple instances of the same service on different ports, and configuring DNS or streaming services that use UDP.

Try It — Docker CLI Reference

Open full tool