Docker & Containerization

Chapter 7
Docker Networking and Service Connectivity

Certificate in DevOps
Docker & Containerization   •   Certificate

Docker Networking and Service Connectivity

Introduction

Containers are isolated processes, but useful applications rarely operate alone. A web application may need to communicate with an API, a database, a message broker, and external users. Docker networking provides the addressing, packet forwarding, name resolution, and exposure mechanisms that allow these components to communicate while preserving useful isolation.

Networking problems are among the most common causes of container failure. A service may be running but unreachable because its port is not published, two containers may be attached to different networks, a client may use the wrong hostname, or a firewall may block traffic. Effective DevOps practice therefore requires more than memorising Docker commands: it requires a mental model of Linux networking and Docker’s network drivers.

This chapter explains network namespaces, interfaces, port publishing, Docker DNS, bridge, host, none, and overlay networks. It then applies these concepts to custom network design and systematic troubleshooting.

Learning Objectives

By the end of this chapter, you should be able to:

  • explain how Linux network namespaces isolate container networking;
  • distinguish container ports, published host ports, and service endpoints;
  • compare bridge, host, none, and overlay networks;
  • create and inspect custom Docker networks;
  • use Docker’s embedded DNS for service discovery;
  • diagnose common connectivity, routing, and exposure problems; and
  • apply secure and maintainable networking practices in a DevOps environment.

1. The Networking Model of a Container

A container normally has its own network namespace. A network namespace provides an isolated view of network resources, including interfaces, routing tables, firewall rules, and sockets. Consequently, a process inside a container can listen on port 8080 without conflicting with another container listening on port 8080. They occupy different namespaces.

The container is not usually connected directly to a physical network. Instead, Docker creates a virtual Ethernet pair. One end is placed inside the container namespace, commonly appearing as eth0; the other end remains in the host namespace and is connected to a Docker bridge or another networking mechanism. Packets travel between these components according to the selected network driver.

A simplified path for a request is:

Client → host IP and published port → Docker forwarding rules → container IP and port → application process

For container-to-container communication on the same user-defined bridge, the path is conceptually:

Container A → virtual interface → Docker bridge → virtual interface → Container B

The application must still listen on the correct address. An application listening only on 127.0.0.1 inside a container accepts connections only from that container’s namespace. To accept traffic arriving through its container interface, it commonly listens on 0.0.0.0 or on the container’s specific interface address. This setting must be balanced with application-level security requirements.

Important distinctions

ConceptMeaning
Container portA port on which a process listens inside the container namespace
Published portA host port forwarded to a container port
Host portA port on the Docker host or host network namespace
Container IPAn address assigned to a container on a Docker network
Service nameA DNS name used by containers to locate another service
Exposed portMetadata indicating an intended listening port; it does not itself publish the port

The EXPOSE instruction in a Dockerfile documents a port and may be used as metadata by tooling. It does not make the application reachable from outside the host. Reachability normally requires docker run -p or an equivalent Compose configuration.

2. Port Publishing and Exposure

Port publishing maps a host address and port to a container port. For example:

docker run -d --name web -p 8080:80 nginx

This asks Docker to make host port 8080 forward to port 80 in the web container. A request to http://HOST_IP:8080 can therefore reach the Nginx process listening on port 80 in the container.

The general form is:

-p [host_ip:]host_port:container_port[/protocol]

Examples include:

docker run -p 127.0.0.1:8080:80 nginx
# Accessible only through the host loopback address

docker run -p 8080:80/tcp nginx
# Publishes TCP port 8080 on the host

docker run -p 9000:9000/udp image-name
# Publishes a UDP port

If no host IP is specified, Docker commonly binds the published port on all host interfaces. This can unintentionally expose a development service to a wider network. Binding to 127.0.0.1 restricts access to the host itself, although reverse proxies and host firewall rules may alter the practical exposure.

Publishing is usually required for traffic entering from outside Docker. It is not normally required for two containers attached to the same user-defined network. In that situation, the client uses the target container’s service name and internal listening port, such as http://api:8080.

A common error is to make a container-to-container request to the host’s published port. For example, if the API is published as host port 9000 mapped to container port 8080, another container on the same network should generally call api:8080, not localhost:9000. localhost refers to the calling container itself, not the host and not another service.

3. Docker Network Drivers

Docker supplies several network modes. Each represents a different trade-off between isolation, simplicity, portability, and scale.

3.1 Bridge networks

Bridge networking is the normal choice for containers on a single Docker host. A bridge is a virtual Layer 2 network on the host. Containers attached to the bridge receive addresses from a private subnet and can communicate according to Docker’s forwarding rules.

Docker creates a default bridge network, but user-defined bridge networks are preferred for applications. They provide automatic DNS-based discovery, clearer isolation boundaries, and more predictable administration.

Example:

docker network create app-net
docker run -d --name db --network app-net postgres:16
docker run -d --name api --network app-net -e DB_HOST=db my-api:1.0

The API can resolve db through Docker’s embedded DNS and connect to the database’s internal port. The database need not publish its port to the host if only the API requires it.

3.2 Host networking

With host networking, the container shares the host’s network namespace. The container does not receive an independent container IP in the usual sense, and port publishing is unnecessary because the process binds directly to host interfaces.

docker run --network host monitoring-agent:1.0

Host mode can reduce networking overhead and is sometimes useful for network-monitoring or performance-sensitive workloads. However, it reduces isolation, creates possible port conflicts, and makes the application’s binding choices directly relevant to host exposure. It should therefore be selected deliberately rather than as a solution to every connectivity problem.

3.3 None networking

The none network mode gives a container only its loopback interface, with no normal external network connectivity.

docker run --network none diagnostic-image

This is valuable for batch jobs, isolated processing, or security-sensitive workloads that do not need network access. An application that expects to contact a database or package repository will fail in this mode unless an administrator adds a carefully controlled networking arrangement.

3.4 Overlay networks

Overlay networks connect containers across multiple Docker hosts. They encapsulate or otherwise transport virtual network traffic across an underlay network, allowing services on different hosts to communicate as though attached to a logical shared network.

Overlay networking is associated with Docker Swarm and multi-host deployments. It requires an appropriate control-plane configuration and host-to-host connectivity. It should not be confused with a bridge network, which is normally local to one host.

Overlay networks introduce additional concerns: address management, encryption options, MTU constraints, firewall rules, failure domains, and service discovery across nodes. They are useful when the deployment platform requires multi-host service communication, but they add operational complexity.

Network-mode comparison

ModeScopeIsolationTypical use
User-defined bridgeOne hostGoodApplication stacks on one host
Default bridgeOne hostLimited convenienceSimple experiments and legacy use
HostHost network namespaceLowMonitoring or specialised performance cases
NoneContainer onlyHigh network isolationOffline or isolated workloads
OverlayMultiple hostsConfigurableSwarm or multi-host services

4. Custom Networks and Service Discovery

A custom network expresses application topology explicitly. It allows an administrator to place related services together while keeping unrelated workloads separate.

docker network create --driver bridge app-net

docker run -d --name database --network app-net postgres:16

docker run -d --name backend --network app-net my-backend:1.0

docker run -d --name frontend --network app-net -p 8080:80 my-frontend:1.0

The frontend can communicate with the backend using the backend’s internal port and the name backend. The backend can communicate with the database using database. Only the frontend needs a published port if it is the public entry point.

A container can be connected to more than one network:

docker network create public-net
docker network create private-net

docker network connect public-net backend
# The backend may now communicate on both networks

A common architecture places a reverse proxy on a public-facing network and application services on a private network. The proxy joins both networks, while the database joins only the private network. This reduces accidental exposure and reflects trust boundaries.

Docker’s embedded DNS

On user-defined networks, Docker provides an embedded DNS service. Containers can normally resolve other containers by name, and Compose services can resolve one another by service name. The DNS name is not necessarily a permanent IP address: containers may be recreated and assigned new addresses while retaining their service identity.

This leads to an important operational rule: applications should use service names rather than hard-coded container IP addresses. DNS resolution identifies a destination; it does not guarantee that the destination application is healthy. A successful DNS lookup therefore does not prove that a TCP connection or application request will succeed.

Compose example:

services:
  api:
    image: example/api:1.0
    networks: [private]
  db:
    image: postgres:16
    networks: [private]

networks:
  private:
    driver: bridge

The API should use a database host such as db, not localhost. Environment variables are usually preferable to embedding network locations in application code.

5. A Conceptual Network Figure

Docker host with public and private networks Docker host Public bridge network Reverse proxy :80 Private bridge network API :8080 Worker Database :5432 Only the proxy is published to external clients
Docker host with public proxy and private application network
Figure: Docker host with public proxy and private application network

Figure: A common topology in which a public proxy fronts services on a private network.

6. Connectivity and Exposure Troubleshooting

Troubleshooting should proceed from the application outward rather than beginning with random changes. The following sequence separates distinct failure classes.

Step 1: Confirm the process

Check whether the container is running and whether the application is ready:

docker ps
docker logs api
docker inspect api

A running container does not necessarily contain a healthy or listening process. Review startup logs, health checks, configuration, and credentials.

Step 2: Confirm the listening address and port

Inside the container, inspect listening sockets where tools are available:

docker exec api ss -lnt

Determine whether the process listens on the expected port and whether it binds to 0.0.0.0 rather than only 127.0.0.1. Confirm the protocol: TCP and UDP are distinct.

Step 3: Confirm network attachment

docker network ls
docker network inspect app-net
docker inspect api

The client and server must share a suitable network for direct container-to-container communication. A service attached only to private-net cannot be reached directly by a client attached only to public-net.

Step 4: Test name resolution

From a diagnostic container on the same network:

docker run --rm --network app-net busybox nslookup api

If the name does not resolve, check the network, service name, aliases, and whether the diagnostic container is attached to the correct network. Do not interpret DNS failure as an application failure until network membership is confirmed.

Step 5: Test the port

docker run --rm --network app-net busybox wget -qO- http://api:8080

A DNS success followed by connection refusal often indicates that no process is listening, the wrong port was selected, or the application is bound only to loopback. A timeout may indicate filtering, routing, a wrong address, or a process that is not responding.

Step 6: Test external exposure

From the host, inspect published ports:

docker port web
curl http://127.0.0.1:8080

If local access works but remote access fails, examine host firewall rules, cloud security groups, bind addresses, reverse-proxy configuration, and whether the published port is intentionally restricted to loopback.

Common symptoms

SymptomLikely causes
Name or service not knownWrong service name, different networks, DNS configuration
Connection refusedNo listener, wrong port, loopback-only binding
Connection timeoutFirewall, routing, incorrect address, unavailable service
Host works but container failsWrong use of localhost, missing network attachment
Container works but remote client failsPort not published, host firewall, loopback binding
Database exposed unnecessarilyPublished database port, overly broad bind address

7. Worked Application: Three-Tier Service

Consider a small application consisting of a web frontend, an API, and PostgreSQL. The design requirement is that users access the frontend from the host, the frontend calls the API, and only the API calls the database.

A suitable Compose configuration is:

services:
  web:
    image: example/web:1.0
    ports:
      - "127.0.0.1:8080:80"
    networks:
      - public
      - private
    depends_on:
      - api

  api:
    image: example/api:1.0
    environment:
      DB_HOST: db
      DB_PORT: "5432"
    networks:
      - private
    depends_on:
      - db

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: change-this-secret
    networks:
      - private

networks:
  public:
  private:
    internal: true

The web service is published on host loopback port 8080. It joins both networks because it must receive external traffic and call the API. The API and database share only the private network. The database has no published port, so it is not directly exposed through the host’s port space.

This configuration illustrates four principles:

  1. publish only the entry point that external users require;
  2. use service names such as api and db for internal communication;
  3. represent security boundaries through network membership; and
  4. treat startup order and readiness separately—depends_on can influence creation order, but applications should still retry connections and use health checks where appropriate.

If the web service returns an API error, the engineer should first verify that api resolves from the web container, that the API listens on its configured internal port, and that the API can resolve db. Publishing the API port would not fix a failure on the private network and might create unnecessary exposure.

8. Illustrative Case Study: Diagnosing an Unreachable API

Background

A development team runs a frontend and API with Docker Compose. The frontend is reachable at host port 3000, but browser requests to the API fail.

Problem

The Compose file publishes api as 9000:8080. The frontend configuration uses http://localhost:9000 as its API URL. From the host, curl http://localhost:9000/health succeeds.

Analysis

The browser and the frontend container are not the same client. If JavaScript executes in the user’s browser, localhost:9000 refers to the user’s machine, not the frontend container. If the frontend server itself makes the request, localhost refers to the frontend container. In neither case is it automatically the API container.

The correct solution depends on the application design. A browser-facing frontend can call a reverse-proxy path such as /api, with the proxy forwarding internally to api:8080. Alternatively, the browser can call a deliberately published API address that is reachable from the user’s machine. For server-side frontend calls, the service name api should be used.

Approach and solution

The team places both services on a custom network and configures the frontend server to call http://api:8080. It removes the API publication because the reverse proxy is the intended external entry point. It then verifies:

docker network inspect app-net
docker exec frontend getent hosts api
docker exec frontend wget -qO- http://api:8080/health

Outcome

Internal service communication succeeds, the API is no longer unnecessarily exposed, and the public interface is handled consistently by the proxy.

Learning points

  • localhost is namespace-relative.
  • Host success does not prove container success.
  • Published ports are for selected exposure, not a substitute for internal DNS.
  • A reverse proxy can provide a stable public endpoint while keeping application services private.

9. Security, Governance, and Operational Practice

Networking is a security boundary, although it is not a complete security control. A container attached to a network may still be compromised, and an exposed application may have its own authentication weaknesses.

Recommended practices include:

  • use user-defined networks rather than relying on the default bridge for application stacks;
  • publish only ports required by users, operators, or approved integrations;
  • bind development ports to loopback when remote access is unnecessary;
  • keep databases, queues, and administrative interfaces off public networks;
  • use network segmentation to express trust boundaries;
  • use application authentication, authorization, and encryption in addition to network isolation;
  • manage secrets with a secret-management mechanism rather than plain configuration where possible;
  • document required ports, protocols, source networks, and ownership;
  • monitor unexpected published ports and changes to network topology; and
  • test connectivity and exposure as part of CI/CD and deployment validation.

In production, organisations should also control who may create networks, publish ports, run privileged containers, or use host networking. Audit records should support investigation of unexpected exposure. Regulatory obligations may apply when network configuration protects personal, financial, health, or operational data.

10. Limitations and Contemporary Developments

Docker’s built-in networking is effective for many single-host and Swarm deployments, but larger environments may use Kubernetes networking, cloud virtual networks, service meshes, ingress controllers, or container network interface plugins. These systems add capabilities such as policy enforcement, load balancing, encrypted service-to-service traffic, and cross-cluster connectivity.

The conceptual foundations remain the same: namespaces provide isolation, interfaces provide attachment, routing determines paths, DNS provides names, and policy controls reachability. However, abstractions can obscure the underlying path. Engineers should learn to correlate high-level configuration with host interfaces, routes, firewall rules, DNS responses, and application logs.

Overlay and encrypted networks can also reduce the effective maximum transmission unit because encapsulation adds headers. Symptoms may include failures for larger packets while small requests succeed. Such problems require coordinated inspection of underlay MTU, overlay configuration, and firewall behaviour rather than repeated application changes.

AI-assisted operations can help summarise logs, generate diagnostic commands, or detect unusual port exposure, but generated commands must be reviewed. An incorrect command may publish a sensitive service, delete a network, or weaken isolation. Human approval, least privilege, auditability, and test environments remain essential.

Best-Practice Checklist

Before deploying a containerised service, ask:

  • Does the process listen on the intended interface and protocol?
  • Does the client and server share the required Docker network?
  • Is the client using a service name rather than a fragile container IP?
  • Is a published port actually required?
  • Is the published port bound to the appropriate host address?
  • Are private services absent from public networks?
  • Are health checks and connection retries implemented?
  • Have host firewalls, cloud rules, and reverse proxies been considered?
  • Can the topology and ownership be explained to another operator?

Chapter Summary

Docker networking combines Linux network namespaces, virtual interfaces, bridges, routing, DNS, and port-forwarding mechanisms. A container port belongs to the container namespace, while a published port creates a host-to-container exposure path. Publishing is generally needed for external clients but not for containers sharing a user-defined network.

User-defined bridge networks are the standard choice for single-host application stacks because they provide explicit membership and embedded DNS. Host networking removes network isolation and should be used selectively. None networking provides strong network isolation for workloads that need no external connectivity. Overlay networking extends logical connectivity across hosts but requires additional operational planning.

Reliable service connectivity depends on correct network attachment, service-name resolution, listening addresses, internal ports, published ports, firewalls, and application readiness. A systematic troubleshooting method begins with the process, then checks listening sockets, network membership, DNS, port connectivity, and external exposure. Secure designs publish only intended entry points and keep databases and internal services on private networks.

Key Terms

Network namespace: An isolated Linux networking context containing interfaces, routes, and sockets.

Virtual Ethernet pair: Two linked virtual interfaces used to connect a container namespace to the host.

Bridge network: A virtual Layer 2 network commonly used to connect containers on one Docker host.

User-defined bridge: An administrator-created bridge with explicit membership and embedded DNS support.

Host network: A mode in which a container shares the host network namespace.

None network: A mode that provides no normal external network interface.

Overlay network: A logical network that connects containers across multiple hosts.

Port publishing: Forwarding a host port to a container port.

Container port: A port on which a process listens inside the container namespace.

Host port: A port in the host namespace used for external access.

EXPOSE: Dockerfile metadata documenting an intended container port.

Embedded DNS: Docker-provided name resolution for containers on suitable user-defined networks.

Service discovery: The process of locating a service through a stable name or endpoint.

Network attachment: Connecting a container to a Docker network.

Loopback interface: A local interface, commonly addressed as 127.0.0.1, that refers to the current namespace.

Reverse proxy: A server that receives client requests and forwards them to internal services.

Network segmentation: Dividing services into separate networks or trust zones.

MTU: Maximum Transmission Unit, the largest packet payload that can be transmitted without fragmentation at a given network layer.

Health check: An automated test of service readiness or health.

Review Questions

Short Answer Questions

  1. What is a network namespace, and why is it important for containers?
  2. What is the difference between a container port and a published port?
  3. Why are user-defined bridge networks preferred over the default bridge for application stacks?
  4. What does localhost mean when used inside a container?
  5. Why should a database port usually not be published to the host?

Long Answer Questions

  1. Compare bridge, host, none, and overlay networking, including a suitable use case for each.
  2. Explain how Docker’s embedded DNS supports service discovery and why hard-coded container IP addresses are fragile.
  3. Describe the complete path of a request arriving at a published host port and reaching a process inside a container.
  4. Explain how a public reverse proxy and a private application network can improve security and maintainability.
  5. Develop a systematic troubleshooting procedure for a container that is running but unreachable.

Analytical / Application Questions

  1. A frontend container and an API container are on the same custom bridge network. The frontend calls localhost:8080, but the API listens on port 8080. Explain the failure and specify the correct endpoint.
  2. An API is reachable from the Docker host but not from a remote workstation. Identify at least three possible causes and describe tests that distinguish them.
  3. Design a network topology for a web proxy, two API replicas, a worker, and a database. State which services require published ports, which networks each service joins, and how service names are used.

Multiple Choice Questions with Answers

Question 1

Which statement best describes a network namespace?

A. A DNS record stored by Docker

B. An isolated Linux networking context containing interfaces, routes, and sockets

C. A host firewall rule for published ports

D. A physical network adapter installed on the host

Correct Answer: B. An isolated Linux networking context containing interfaces, routes, and sockets

Question 2

A container runs an HTTP server on port 80, and the command uses -p 8080:80. Which port is normally used by an external client on the Docker host?

A. 80

B. 8080

C. 443

D. The container IP gateway port

Correct Answer: B. 8080

Question 3

Two containers on the same user-defined bridge network should normally locate one another using which mechanism?

A. The host's public IP address

B. The containers' permanent physical MAC addresses

C. Docker's embedded DNS and service or container names

D. The loopback address of either container

Correct Answer: C. Docker's embedded DNS and service or container names

Question 4

What does localhost usually refer to inside a container?

A. The Docker host

B. The public internet

C. The default bridge gateway

D. The current container's network namespace

Correct Answer: D. The current container's network namespace

Question 5

Which network mode provides the container with no normal external network connectivity?

A. Host

B. Overlay

C. None

D. Bridge

Correct Answer: C. None

Question 6

What is a major consequence of host networking?

A. The container shares the host network namespace and has reduced network isolation

B. The container can communicate only with itself

C. The container automatically receives an encrypted overlay address

D. All container ports are blocked from the host

Correct Answer: A. The container shares the host network namespace and has reduced network isolation

Question 7

Which command creates a user-defined bridge network named app-net?

A. docker port create app-net

B. docker network create app-net

C. docker bridge add app-net

D. docker create --dns app-net

Correct Answer: B. docker network create app-net

Question 8

A service name resolves successfully, but a connection to the service port is refused. What is the most likely next check?

A. Whether the process is listening on the expected port and address

B. Whether the host has a different public domain name

C. Whether the container image has a larger filesystem

D. Whether the client has changed its keyboard layout

Correct Answer: A. Whether the process is listening on the expected port and address

Question 9

Which service would normally be the best candidate for a published host port in a three-tier application?

A. The database, regardless of client requirements

B. The internal worker only

C. The public-facing reverse proxy or frontend

D. Every service, to simplify networking

Correct Answer: C. The public-facing reverse proxy or frontend

Question 10

What is the principal purpose of an overlay network?

A. To disable all container networking

B. To connect containers across multiple Docker hosts through a logical network

C. To replace application-level authentication

D. To make every container use the host loopback interface

Correct Answer: B. To connect containers across multiple Docker hosts through a logical network

Docker & Containerization
Chapter 7 of 13