Chapter 2 · Lesson 6 of 20
Docker

Docker networks explained: connect containers by name

A Docker network is a virtual network that lets containers on the same host reach each other, and the outside world, by rules Docker sets up.

By the end you will

Connect two containers by name on a user-defined network.

Time
20 min
Level
Beginner
Check
4 questions
You need
  • Docker installed

How containers talk on a Docker network

Containers on the same Docker network find each other by service name, so the web container can call the api and the api can call the database without published ports.
  1. Only the container with a published port is reachable from outside.
  2. The containers all join the same user-defined network.
  3. On that network a container name works like a hostname.
  4. The web container reaches the API by name, with no address to look up.
  5. The API reaches the database by name over the same private network.
Static diagram
  1. Outside worldrequestweb
  2. webjoinUser-defined network
  3. User-defined networkname: apiapi
  4. webhttp://apiapi
  5. apidb:5432db

Containers on the same user-defined Docker network can reach each other by container name, on the container’s own port, with no -p needed. Containers on the default bridge network cannot look each other up by name, which is why a fresh docker run setup often cannot find its database.

How it works#

Docker creates virtual networks on the host. Each container gets its own network stack and an address on one or more of those networks. Containers on the same network can talk directly, on the container’s own ports. Containers on different networks cannot, unless one joins both.

There are two kinds of bridge network you will meet. The default bridge (called bridge, usually 172.17.0.0/16) is where a container lands if you name no network. Containers there reach each other only by IP address, and IP addresses change between restarts. A user-defined bridge adds an embedded DNS service: each container name resolves to its current address. That is why you should create a network for each app.

Two names to avoid mixing up: localhost inside a container is the container itself, not the host and not another container. And publishing a port with -p does something different from networking: it forwards traffic from the host to one container. Containers talking to each other never need it. A database with no -p is reachable by its neighbours but not from the host or the internet.

A worked example, start to finish#

With appnet and the db container from step 2 running, ask the built-in DNS what db is:

bash
docker run --rm --network appnet alpine nslookup db
docker run --rm --network appnet alpine ping -c 1 db

The first command shows the resolver address 127.0.0.11, which is Docker’s embedded DNS inside every container on a user-defined network, and then an address for db. The second pings it and gets a reply from that address. Nothing was published with -p, and it worked, because both containers sit on the same network. Stop db, start it again, and the address may change while the name keeps resolving. That is the reason to use names, never addresses.

Step 1: Create a network#

bash
docker network create appnet

What you should see: the new network’s ID.

Step 2: Start containers on it#

bash
docker run -d --name db --network appnet -e POSTGRES_PASSWORD=change-me postgres:16
docker run --rm --network appnet alpine ping -c 2 db

The second container is a throwaway (--rm) that pings db twice by name. db has no -p: containers on appnet can reach it, the host machine cannot. That is a good default for a database.

What you should see: two replies, with a line like 64 bytes from 172.x.x.x (the address of db), and no packet loss.

Step 3: Look around#

bash
docker network ls
docker network inspect appnet

network ls lists networks and their drivers. inspect prints JSON, including each attached container with its address.

What you should see: appnet with driver bridge, and db under Containers.

Step 4: Compose does this for you#

Docker Compose creates a default network for each project, named after the project (for example demo_default). Every service joins it, and each service name works as a hostname. In a Compose file, an app connects to a database service named db at host db, port 5432, with no ports entry needed.

To split services, declare networks yourself:

yaml
services:
  web:
    image: nginx
    networks: [front, back]
  db:
    image: postgres:16
    networks: [back]
networks:
  front:
  back:

Here web reaches db, but nothing on front alone can.

Check it worked#

The ping prints replies from db. docker network inspect appnet lists db under Containers with an IPv4 address. Run docker run --rm alpine ping -c 1 db (default bridge) and it fails with a “bad address” message, which shows the difference.

Edge cases and gotchas#

  • localhost is the container. An app that connects to localhost:5432 looks inside itself. Use the service or container name.
  • Use the container’s own port, not the published one. If a db publishes 5433:5432, other containers still connect to db:5432. The left number only matters from the host.
  • Names only work on user-defined networks. The default bridge has no name lookup. Create a network or use Compose.
  • Reaching the host from a container. On Linux, host.docker.internal does not exist unless you add --add-host=host.docker.internal:host-gateway. And a host service bound to 127.0.0.1 is still not reachable from the container network, so it must listen on an address the container can reach.
  • Published ports bypass ufw. Docker writes its own firewall rules, so -p 8080:80 is open to the world even if ufw denies it. Bind to 127.0.0.1 or do not publish.
  • Address ranges can clash. Docker picks private subnets. If one overlaps with your VPN or office network, routes break. You can set a different subnet with docker network create --subnet.
  • Host networking removes isolation. --network host (Linux) shares the host’s network. The container’s ports are the host’s ports, and -p is ignored.

Troubleshooting#

SymptomLikely causeFix
ping: bad address 'db'The containers are not on the same user-defined networkPut both on one network with --network
network appnet has active endpointsContainers still attachedRemove or stop them, then docker network rm appnet
connection refused to db:5432The db is not ready yet, or wrong portWait or retry, and check docker logs db
App reaches db but with the wrong dataAnother container named db on another networkUse unique names per project
Works from the host, fails between containersYou used a published port or localhostUse the service name and container port
Error response from daemon: network with name appnet already existsYou ran create twiceReuse it, or pick another name
Host cannot connect to the database containerNo port is published, which is the default and is intentionalUse docker exec, or publish on 127.0.0.1 only
Name stops resolving after a restartThe app cached the old addressRestart the app, or make it re-resolve the name
Lookups of outside names fail inside a containerThe host resolver or a firewall blocks the containerTest with docker run --rm alpine nslookup example.com and check host DNS

Real-world scenario#

You run a blog container and a MySQL container. The blog’s config says the database host is localhost, so it cannot connect. You then try the container’s IP address, and it works until the next restart changes the address.

The fix takes a minute. You create a network, restart both containers with --network blognet, and change the host setting to the container name mysql. The database has no -p, so it is invisible from outside. Later you move both into a compose file, where the same names work with no extra setup, and put a reverse proxy in front of the blog as the only published service.

Quick reference#

TaskCommand
Create a networkdocker network create appnet
Start a container on itdocker run -d --name db --network appnet IMAGE
Attach a running containerdocker network connect appnet NAME
Detach itdocker network disconnect appnet NAME
List and inspectdocker network ls, docker network inspect appnet
Remove an unused networkdocker network rm appnet

Security and safety notes#

  • Do not publish database ports to all interfaces. If you must, bind to 127.0.0.1 and reach it over an SSH tunnel.

Next#

Learn how images get from your machine to a server in Image, container and registry explained.

Check what you learned4 questions
1Why can containers on the default bridge not find each other by name?
2Do two containers on the same user-defined network need -p to talk to each other?
3In a Compose file, how does an app reach a service named db?
4App and db are on different user-defined networks. Can the app reach db by name?

Frequently asked questions

Why can my app not reach the database by name?

On the default bridge network, containers cannot resolve each other by name. Put both on a user-defined network, or use Docker Compose, which creates one for you.

Do I need -p for containers to talk to each other?

No. Containers on the same network reach each other on the container's own port. Publishing with -p is only for access from outside Docker.

Can containers on different networks talk to each other?

Not by default. Each network is isolated. Attach a container to both networks with docker network connect, or put them on one shared network.

How does a container reach a service running on the host itself?

On Linux there is no host.docker.internal by default. Add extra_hosts with host.docker.internal:host-gateway (or --add-host with the same value), then connect to that name.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios