Learn Docker ยท 7/12

Container Networking: Making Containers Talk

8 min read

Imagine an office building where every single employee is placed inside their own soundproof, windowless room with a locked door. They can do their individual tasks perfectly fine, but the moment the accountant needs to hand a report to the manager, the system breaks down. They cannot communicate.

This is exactly what happens when you spin up Docker containers. By design, containers are heavily isolated. They have their own file system, their own processes, and their own isolated network stack.

However, modern applications do not exist in isolation. A web server needs to talk to a database. A backend API needs to talk to a caching service. A frontend needs to fetch data from the backend.

The Problem: How do we safely and reliably allow these completely isolated environments to communicate with each other and the outside world?

The Solution: Docker Networking.

Let's break down how Docker connects these isolated rooms, starting from the default setup and moving into industry-standard practices.


1. Docker Networking Basics: The Default Bridge Network ๐ŸŒ‰

Definition and Problem

When you install Docker, it automatically creates a default network called bridge. A bridge network is a Link Layer device which forwards traffic between network segments. In Docker, it is a software bridge (named docker0 on your host machine) that allows containers connected to the same bridge network to communicate, while providing isolation from containers not connected to that bridge.

The Problem it solves: Without this default bridge, every container you start would be entirely disconnected from everything. The default bridge provides a quick, zero-configuration way for containers to ping each other using IP addresses.

What happens under the hood?

When you run a container without specifying a network, Docker automatically attaches it to this default bridge network.
Docker assigns the container a private IP address (usually starting with 172.17.x.x). It creates a pair of virtual ethernet interfaces (veth pairs)โ€”think of it as a virtual Ethernet cable. One end plugs into the container, and the other end plugs into the docker0 bridge on your host machine.

Hands-on Example

Let's spin up two containers and see how they communicate.

bash
# Start the first container
docker run -dit --name container_A alpine sh

# Start the second container
docker run -dit --name container_B alpine sh

Now, let's find the IP address of container_A:

bash
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_A
# Output: 172.17.0.2 (Yours might vary slightly)

If we log into container_B, we can ping container_A using that IP:

bash
docker exec -it container_B sh
/ # ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2): 56 data bytes
64 bytes from 172.17.0.2: seq=0 ttl=64 time=0.089 ms

The Industry Reality

While the default bridge is great for a quick test, it is almost never used in professional production environments. Why? Because on the default bridge, containers can only communicate via IP addresses. If a container restarts, its IP address might change. If you hardcode an IP address inside a container's configuration, a senior DevOps engineer somewhere wakes up in a cold sweat.

This brings us to the actual standard.


2. Creating Custom User-Defined Bridge Networks ๐Ÿ—๏ธ

Definition and Problem

A user-defined bridge network is a custom network created by the user to group specific containers together.

The Problem it solves: The default bridge network has two fatal flaws:

  1. Every single unassigned container gets dumped into it, meaning there is zero network isolation between different applications running on the same host.
  2. It does not support automatic DNS resolution (which we will cover in the next section).

If you are running a blog app and a finance app on the same server, you do not want the blog's frontend to accidentally (or maliciously) have network access to the finance database. User-defined networks solve this by creating multiple, isolated bridges.

How to use it

Creating a custom network is straightforward.

bash
# Create a custom bridge network for our blog application
docker network create blog-net

Now, when you start containers, you explicitly assign them to this network:

bash
docker run -d --name blog-db --network blog-net postgres:15
docker run -d --name blog-backend --network blog-net node:18

Because blog-db and blog-backend are both on blog-net, they can talk to each other. If you start a random third container without specifying the network (which puts it on the default bridge), it will have absolutely no way to reach blog-db.

Industry Standard: Always create a specific user-defined network for each logical application stack. If you use Docker Compose, it actually does this for you automatically!


3. Container-to-Container Communication via DNS Resolution ๐Ÿ“‡

Definition and Problem

DNS (Domain Name System) is a hierarchical system that translates human-readable domain names into numerical IP addresses. In Docker, Embedded DNS resolution allows containers to discover and communicate with each other using their container names instead of their IP addresses.

The Problem it solves: Containers are ephemeral. They crash, they get updated, they get restarted. Every time a container restarts, Docker might hand it a brand new IP address. If your Node.js backend connects to postgres://172.18.0.3:5432, and the database restarts and gets 172.18.0.4, your backend crashes.

How it works

Docker runs an embedded DNS server at 127.0.0.11 inside every container. When you use a user-defined bridge network, Docker automatically registers the container's name (and aliases) with this internal DNS server.

(Note: As mentioned earlier, Docker intentionally disabled this feature on the default bridge network for legacy backward compatibility. This is the main reason we use custom networks).

Hands-on Example

Let's use the blog-net we created earlier.

bash
# Start a database container
docker run -d --name database --network blog-net alpine sleep 3000

# Start an app container
docker run -it --name app --network blog-net alpine sh

Inside the app container, instead of worrying about IPs, we simply ping the word database:

bash
/ # ping database
PING database (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.120 ms

Practical Usability: In industry, this is how you configure your applications. Your backend environment variables will simply look like this:
DB_HOST=database
DB_PORT=5432

Docker intercepts the request for database, looks up the current IP address of the container named database, and routes the traffic seamlessly. You never have to care what the actual IP address is.


4. Connecting to the Outside World: Understanding Ingress and Egress ๐ŸŒ

We have our containers talking to each other beautifully. But a web application is entirely useless if actual human users on the internet cannot reach it. Furthermore, what if your container needs to download an update from the internet?

This brings us to Ingress (traffic coming IN) and Egress (traffic going OUT).

Egress (Outbound Traffic)

Definition: Egress is network traffic that begins inside a network and proceeds through its routers to a destination outside of the network.

The Problem: Containers have private IP addresses (like 172.18.0.2). The public internet has no idea how to route traffic back to that private IP.

How Docker solves it: Docker uses IP Masquerading (a form of NAT - Network Address Translation). When a container tries to reach google.com or download an npm package, the traffic goes to the host machine's docker0 bridge. The host machine modifies the packet, stripping away the container's private IP and replacing it with the host's actual IP address. The internet replies to the host, and the host remembers which container asked for it and forwards the reply back.
Good news: This works completely automatically out of the box. You do nothing.

Ingress (Inbound Traffic)

Definition: Ingress is network traffic that originates from the outside and attempts to access internal resources.

The Problem: Because containers are isolated, your host machine acts like a strict bouncer at a club. If a user tries to access port 80 (HTTP) on your server's public IP, the host machine handles it. It doesn't magically know that there is an Nginx container inside running on port 80.

The Solution: Port Publishing (Port Mapping)
To allow ingress traffic, we must explicitly drill a hole through the host's firewall and route it to a specific container. We do this using the -p or --publish flag.

Syntax:

docker run -p <HOST_PORT>:<CONTAINER_PORT>

Hands-on Example:

Let's run an Nginx web server. Nginx runs on port 80 by default inside the container.

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

What did we just do?
We told Docker: "Listen on port 8080 of my actual host machine (my laptop, or my AWS server). Whenever traffic arrives there, immediately forward it to port 80 inside the web-server container."

If you open your web browser and go to http://localhost:8080, you will see the Nginx welcome screen!

Pro Tip: A very common beginner mistake is mapping ports backwards. Always remember it is Host first, Container second. You dictate where the traffic lands on your machine, and then where it goes inside the isolated room.


Summary Cheat Sheet ๐Ÿ“

  1. Default Bridge (docker0): Exists out of the box. Containers can talk via IP. Poor isolation. No DNS. Don't use in production.
  2. User-Defined Bridge: Create with docker network create. Great isolation. Automatically resolves container names to IPs. Industry standard.
  3. Internal DNS: Docker automatically handles translating container names (like db or redis) to the correct, shifting private IP addresses inside user-defined networks.
  4. Egress: Containers reaching the internet. Works automatically via host NAT.
  5. Ingress: The internet reaching containers. Requires explicit port mapping using -p HostPort:ContainerPort.

References and Further Reading ๐Ÿ“š

Challenge

You are tasked with deploying a two-tier web application using Docker. The application consists of a backend service and a database. Your goal is to write the necessary Docker CLI commands to create a secure, isolated network for these services and expose the backend to the host machine.

Requirements:

  1. Network: Create a user-defined bridge network named app-network.
  2. Database Container: Launch a container for the database service.
    • Use the postgres:14-alpine image.
    • Name the container database-svc.
    • Attach it to the app-network.
    • Run it in detached mode.
    • Crucially, do not publish its port to the host machine.
  3. Backend Container: Launch a container for the backend service.
    • Use the backend-app:latest image.
    • Name the container backend-svc.
    • Attach it to the app-network.
    • Run it in detached mode.
    • Configure it with an environment variable DB_HOST that is set to the service name of the database container, enabling communication via Docker's internal DNS.
    • Publish the container's internal port 80 to port 8080 on the host machine to make it accessible externally.

Expected result

The solution consists of three distinct Docker commands written sequentially. The order of the flags within a single command may vary, but all specified flags and arguments must be present.

  1. The first command must use docker network create to provision the network.
  2. The second command must use docker run to start the database container. It must include the --network, --name, and -d flags but must NOT include the -p flag.
  3. The third command must use docker run to start the backend container. It must include the --network, --name, -d, -p, and -e flags with their correct values.
shell
docker network create app-network
docker run -d --network app-network --name database-svc postgres:14-alpine
docker run -d --network app-network --name backend-svc -p 8080:80 -e DB_HOST=database-svc backend-app:latest
shell

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.