Docker networking basics

Topic: Containers core

Summary

Containers can use the default bridge, a user-defined bridge, or the host network. Use bridge networks so containers resolve each other by name; publish ports with -p to expose services to the host. Use this when connecting containers or when debugging connectivity between containers and host.

Intent: How-to

Quick answer

  • Default bridge: containers can talk by IP but not by name. User-defined network: docker network create mynet; docker run --network mynet --name app myimage. Containers on same network resolve names (e.g. ping db).
  • Publish port: -p 8080:80 maps host 8080 to container 80. Only needed when the host or external clients must reach the container. Container-to-container on same network: use service name and container port (no -p needed for that).
  • Host network: --network host uses host network stack (no isolation). Use for performance or when you need host ports; avoid when possible. Compose: services on same default network resolve by service name.

Prerequisites

Steps

  1. Create user network

    docker network create mynet. docker run -d --network mynet --name db postgres:16. docker run -d --network mynet --name app -p 8080:80 myapp. app can connect to db:5432 by name.

  2. Publish ports

    -p 8080:80 publishes container port 80 to host 8080. -p 127.0.0.1:8080:80 binds only to localhost. List port mappings: docker port app.

  3. Compose networking

    Compose creates a default network per project; services use service name as hostname. Custom: networks: mynet:; services: app: networks: - mynet.

  4. Inspect and troubleshoot

    docker network ls; docker network inspect mynet. If container cannot reach another: ensure same network; ping by name; check listening port inside container (no firewall between containers on same network).

Summary

Use user-defined networks so containers resolve each other by name; publish ports with -p when the host or external clients need access. Use this to wire multi-container stacks and expose services.

Prerequisites

Steps

Step 1: Create user network

Create a network and run containers on it; use container name as hostname for other containers.

Step 2: Publish ports

Use -p to map container ports to the host; bind to 127.0.0.1 when only local access is needed.

Step 3: Compose networking

Use the default Compose network or define custom networks; reference services by name.

Step 4: Inspect and troubleshoot

Inspect networks and containers; verify name resolution and port exposure.

Verification

  • Containers on the same network can reach each other by name; published ports are reachable from the host as intended.

Troubleshooting

Cannot resolve name — Containers must be on the same user-defined network (not just default bridge). Port not reachable — Check -p mapping and that the process inside the container listens on the expected port and address (0.0.0.0).

Next steps

Continue to