Port Mapping and Container Linking in Docker

Port Mapping

When running containers that need to be accessed from outside the host machine—such as a private Docker registry—it's common to use the -p flag. For example:

docker run -d -p 5000:5000 -v /opt/data/registry:/tmp/registry registry

This maps port 5000 on the host to port 5000 inside the container. Without such a mapping, external systems cannot reach services running within the container because the container’s network is isolated by default.

Docker supports two flags for port exposure:

  • -P (uppercase): Automatically maps all exposed ports in the image to random ports in the range 49000–49900 on the host.
  • -p (lowercase): Allows explicit specification of port mappings. Only one cnotainer can bind to a given host port at a time.

The -p flag acccepts three formats:

  1. ip:hostPort:containerPort — Binds a specific IP and port on the host to a container port. Example: 127.0.0.1:5000:5000.
  2. ip::containerPort — Binds a specific IP with a dynamically assigned host port to the container port. Example: 127.0.0.1::5000.
  3. hostPort:containerPort — Most commonly used; binds a host port directly to a container port without restricting the IP. Example: 5000:5000.

After starting a container, you can inspect its port mpapings using:

docker ps
# or
docker port <container_name>

Multiple -p flags can be used to expose several ports from the same container.

Container Linking

In multi-container applications—such as a web application communicating with a database—it's often undesirable to expose internal services via host ports for security and encapsulation reasons. Docker provides inter-container communication mechanisms, one of which is the legacy --link option (limited to containers on the same Docker host).

First, start a MySQL container:

docker run --name db_server -e MYSQL_ROOT_PASSWORD=secret123 -d mysql:8

Then launch another container and link it to the MySQL instance:

docker run --name app_container --link db_server:database -it ubuntu bash

This establishes a secure channel between the two containers without publishing any ports to the host. Docker facilitates discovery through:

  1. Environment variables: The receiving container gets environment variables like DATABASE_PORT_3306_TCP_ADDR and DATABASE_PORT_3306_TCP_PORT.
  2. /etc/hosts entry: An entry is added mapping the alias (database) to the linked container’s IP address.

Tags: docker port-mapping container-linking networking MySQL

Posted on Sat, 25 Jul 2026 16:09:36 +0000 by luanne