Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 111 ยท Networking

Containers Talking to Each Other

Learn how containers connect: service names as hostnames, container ports versus published ports, the app-and-database pattern, tiered networks, and handling startup order.

Real applications are never a single container. A web app needs a database, a cache, maybe a queue and a reverse proxy. Each runs in its own container, and the whole system works only if the pieces can find and reach each other. Beginners usually get stuck on the same three questions: "What hostname do I use?", "Which port do I use?" and "Why does my app crash because the database is not ready yet?"

This lesson answers all three with a small working system: a Python service that counts page hits in Redis, and a PostgreSQL container used to show readiness checks. You will build it by hand with docker run, so you see exactly what Compose automates later. All output below comes from real runs; IDs and addresses are shortened or will differ on your machine.

The three rules

  1. Put the containers on the same user-defined network. Without that there is no name resolution (see User-Defined Bridge Networks).
  2. Use the other container's name (or alias) as the hostname. Never an IP address, never localhost.
  3. Use the port the service listens on inside its container. Not a published port.

Everything else in this lesson is a consequence of these rules. Let us prove each one.

The example system

Our tiny service increments a counter in Redis every time it is requested. Here is the code, speaking Redis's simple wire protocol over a plain socket so no libraries are needed:

Python
# app.py
import os
import socket
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

REDIS_HOST = os.environ.get("REDIS_HOST", "localhost")
REDIS_PORT = int(os.environ.get("REDIS_PORT", "6379"))


def incr_hits():
    with socket.create_connection((REDIS_HOST, REDIS_PORT), timeout=2) as conn:
        conn.sendall(b"*2\r\n$4\r\nINCR\r\n$4\r\nhits\r\n")
        return int(conn.recv(64).strip()[1:])


def wait_for_redis():
    for attempt in range(1, 6):
        try:
            incr_hits()
            print(f"redis ready after {attempt} attempt(s)", flush=True)
            return
        except OSError as error:
            print(f"attempt {attempt}: cannot reach {REDIS_HOST}:{REDIS_PORT}: {error}", flush=True)
            time.sleep(1)
    raise SystemExit("giving up on redis")


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        body = f"hits={incr_hits()}\n".encode()
        self.send_response(200)
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    wait_for_redis()
    HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()

Two details to notice: the Redis host and port come from environment variables (so the same image works anywhere, see Configuring Containers), and the server listens on 0.0.0.0, which matters later. The Dockerfile is minimal:

DOCKERFILE
FROM python:3-alpine
WORKDIR /app
COPY app.py .
CMD ["python", "app.py"]
CONSOLE
$ docker build -t hits-api .

Rule 2: names, not localhost

First the wrong way. Create a network with Redis on it, then run our service with the default REDIS_HOST of localhost:

CONSOLE
$ docker network create data-net
$ docker run -d --name redis --network data-net redis:alpine
$ docker run --rm --network data-net hits-api
attempt 1: cannot reach localhost:6379: [Errno 111] Connection refused
attempt 2: cannot reach localhost:6379: [Errno 111] Connection refused
attempt 3: cannot reach localhost:6379: [Errno 111] Connection refused
attempt 4: cannot reach localhost:6379: [Errno 111] Connection refused
attempt 5: cannot reach localhost:6379: [Errno 111] Connection refused
giving up on redis

Redis is running and the network is correct, yet the connection is refused. Inside the service container, localhost is the service container itself. Nothing listens on 6379 there. The same happens with PostgreSQL if you point a client at localhost:

CONSOLE
$ docker run --rm --network data-net -e PGPASSWORD=pw postgres:17-alpine psql -h localhost -U postgres -c 'select 1'
psql: error: connection to server at "localhost" (::1), port 5432 failed: Connection refused

The fix is to use the name Docker's DNS knows, which is the container name (here redis):

CONSOLE
$ docker rm -f redis hits-api 2>/dev/null
$ docker run -d --name redis --network data-net redis:alpine
$ docker run -d --name api --network data-net -e REDIS_HOST=redis -p 127.0.0.1:8000:8000 hits-api
$ docker logs api
redis ready after 1 attempt(s)
$ curl -s http://127.0.0.1:8000
hits=2
$ curl -s http://127.0.0.1:8000
hits=3

(The first hit was consumed by the startup check, so the visible counter starts at 2.) It works because redis resolves to the Redis container's address on data-net.

In a real project you rarely type container names by hand. In Compose you name the service, and that name is the hostname: REDIS_HOST=redis just works. Choose short, role-based names (db, cache, search) instead of names tied to a product, so you can swap the implementation later.

Rule 3: container ports, not published ports

Look at what we published: only the API's port 8000, bound to 127.0.0.1. Redis publishes nothing:

CONSOLE
$ docker ps --format 'table {{.Names}}\t{{.Ports}}'
NAMES     PORTS
api       127.0.0.1:8000->8000/tcp
redis     6379/tcp

Yet the API reached Redis on port 6379. Publishing (-p host:container) is for traffic coming from outside Docker into a container: your browser, curl, another machine. Container-to-container traffic on a shared network goes directly to the port the process listens on. It never passes through the host's published ports.

Check this with PostgreSQL. Its real port is 5432. Trying a different "published-looking" port fails:

CONSOLE
$ docker run --rm --network data-net -e PGPASSWORD=pw postgres:17-alpine psql -h db -p 5433 -U postgres -c 'select 1'
psql: error: connection to server at "db" (172.23.0.4), port 5433 failed: Connection refused
$ docker run --rm --network data-net -e PGPASSWORD=pw postgres:17-alpine psql -h db -U postgres -c 'select 1 as ok'
 ok 
----
  1
(1 row)

Practical consequences:

  • If you map -p 5433:5432 for convenience on your laptop, other containers must still use db:5432.
  • You usually do not need to publish a database at all. Publish only what humans or the outside world must reach, and keep everything else private. Removing a database's -p is one of the cheapest security wins available (see Publishing Ports).
  • The service must listen on 0.0.0.0 (all interfaces) inside its container. A server bound to 127.0.0.1 accepts only connections from the container itself, so neighbours and published ports are refused. Our API uses 0.0.0.0 for exactly this reason.

Failure messages and what they mean

Name resolution failures look different from connection failures. Learn to tell them apart:

CONSOLE
$ docker run --rm --network data-net -e PGPASSWORD=pw postgres:17-alpine psql -h nosuchdb -U postgres -c 'select 1'
psql: error: could not translate host name "nosuchdb" to address: Try again
Message Likely cause
could not translate host name / bad address / Try again The name is wrong, the container is not running yet, or it is on a different network
Connection refused The name resolved, but nothing listens on that port: wrong port, server still starting, or bound to 127.0.0.1
timed out Packets are dropped: different networks with a bad IP, a firewall, or a stuck server

More on diagnosing these in Troubleshooting Networks.

Tiered networks: the app-and-database pattern

A common production layout has three tiers: a proxy that faces the world, an application, and a data store. Each tier should reach only the tier next to it. With networks that is easy:

TEXT
   internet
      |
  [ proxy ] ---- front-net ---- [ api ] ---- data-net (internal) ---- [ redis / db ]

Create the two networks. The data network is --internal, so the database has no route to the internet at all:

CONSOLE
$ docker network create front-net
$ docker network create --internal data-net

Start Redis only on the data network, and give the API both networks. A container is started on one network, and docker network connect adds the second:

CONSOLE
$ docker run -d --name redis --network data-net redis:alpine
$ docker run -d --name api --network data-net -e REDIS_HOST=redis hits-api
$ docker network connect front-net api

Now a container on the front network (a stand-in for your proxy) can resolve api but not redis:

CONSOLE
$ docker run --rm --network front-net alpine:3 ping -c1 -W1 redis
ping: bad address 'redis'

If an attacker compromises the proxy, Redis is not even visible to them. If they compromise the API, they reach Redis, but that was always required. This is least privilege for networks.

Publishing a port on a container that is only attached to an internal network does nothing: in our test docker port for such a container printed no mapping at all. If the API must be reachable from your browser, make sure it also sits on a non-internal network (like front-net above).

Startup order and readiness

Containers start in the order you tell them, but "started" does not mean "ready". PostgreSQL needs several seconds to initialize its files before it accepts connections. If your app connects in its first millisecond, it fails.

Here is what happens when the API starts before Redis exists, using the retry loop from app.py:

CONSOLE
$ docker run -d --name api --network data-net -e REDIS_HOST=redis hits-api
$ sleep 2
$ docker run -d --name redis --network data-net redis:alpine
$ docker logs api
attempt 1: cannot reach redis:6379: [Errno -3] Try again
redis ready after 2 attempt(s)

The first attempt failed because the name redis did not exist yet (a name only resolves once the container exists on the network). One second later the retry succeeded. There are three standard ways to handle readiness, in order of preference:

  1. Make the application retry. Connection pools, drivers and frameworks usually support it, or you write a small loop like ours. It also protects you in production when the database restarts at 3 a.m.

  2. Give the dependency a healthcheck and have the orchestrator wait for it. Docker can run a probe command and report the result in docker ps:

    CONSOLE
    $ docker run -d --name db --network data-net -e POSTGRES_PASSWORD=pw \
        --health-cmd 'pg_isready -U postgres' --health-interval 2s --health-retries 10 postgres:17-alpine
    $ docker ps --filter name=db --format '{{.Names}} {{.Status}}'
    db Up 1 second (health: starting)
    $ docker ps --filter name=db --format '{{.Names}} {{.Status}}'
    db Up 6 seconds (healthy)
    $ docker exec db pg_isready -U postgres
    /var/run/postgresql:5432 - accepting connections
    

    Healthchecks are explained in HEALTHCHECK, and Compose can start a service only when its dependency is healthy (see Startup Order and Health).

  3. Wait in the entrypoint with a script that polls the dependency. It works anywhere but adds moving parts, so prefer the first two.

Plain docker run has no "wait for" feature. A script that sleeps for a fixed number of seconds is fragile: too short and it fails on a slow machine, too long and every start is slow. Poll until ready instead.

Many replicas behind one name

If several containers share a network alias, a lookup returns all their addresses in rotating order. That gives simple load distribution without a load balancer, as shown in User-Defined Bridge Networks. Compose uses the same mechanism when you scale a service. For real balancing with health checks and retries, put a reverse proxy in front (see Nginx and Reverse Proxies).

Reaching the host from a container

Sometimes the service you need is not a container but a program on your own machine. Use the special name host.docker.internal, which Docker Desktop provides and which Linux engines can enable with --add-host=host.docker.internal:host-gateway. It is covered in DNS, Proxies and Firewalls.

Clean up

CONSOLE
$ docker rm -f api redis db
$ docker network rm front-net data-net

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your API container needs to reach a Redis container on the same user-defined network. Which host should its config use?

    Docker's embedded DNS resolves container names on a shared network. localhost and 127.0.0.1 refer to the API container itself, and hard-coded IPs break when containers are recreated.
  2. 2. Redis is run with -p 127.0.0.1:6380:6379. Which port should another container on the same network use?

    Published ports only apply to traffic entering from the host. Container-to-container traffic uses the port the process listens on, 6379.
  3. 3. A client reports 'Connection refused' to db:5432, while 'bad address' appears for a typo in the name. What does 'Connection refused' tell you?

    A refusal means the packet reached a host that answered 'no one is listening'. Typical causes are a server still starting, the wrong port, or a server bound only to 127.0.0.1.
  4. 4. Why should a service inside a container listen on 0.0.0.0 rather than 127.0.0.1?

    A server bound to the container's loopback is invisible to other containers and to published ports. Binding to all interfaces lets traffic arrive on the container's network interface.
  5. 5. What is the most robust way to deal with a database that is not ready when your app starts?

    Retrying handles slow starts and later database restarts. Fixed sleeps are fragile, and publishing ports does not change readiness.

Summary

  • Put communicating containers on the same user-defined network and address them by name, never by localhost or a hard-coded IP.
  • Container-to-container traffic uses the container's own port; -p mappings only matter for traffic from outside Docker.
  • Services must listen on 0.0.0.0 inside their container.
  • Publish only what outsiders need; keep databases and caches unpublished.
  • Use several networks (one --internal) to give each tier access only to its neighbours.
  • "Started" is not "ready": make clients retry, add healthchecks, and let Compose wait for healthy dependencies.
  • could not translate host name means a name problem; Connection refused means the name resolved but nothing is listening.

Next: Troubleshooting Networks