Skip to lesson

Networking between containers

ShopLite's API must find its MySQL container, but container IPs change every time a container is recreated. Compose gives each service a name instead, and mixing up localhost and db is the most common start-up bug.

The project network and DNS by service name

A project network is the private network <project>_default that Compose creates for a project. Every service joins it and can reach the other services there by their service names.

ShopLite's api and db must find each other, but a container's IP changes whenever it is recreated. Compose solves this with a private network where every service answers to its name.

Example 1 · A model of Docker DNS on the project network

ServiceDnsDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class ServiceDnsDemo {    // Simplified model of the DNS server on network shoplite_default    static Map<String, String> network = new LinkedHashMap<>();
    static String resolve(String fromService, String host) {        if (host.equals("localhost")) {            return network.get(fromService) + " (" + fromService + " itself)";        }        String ip = network.get(host);        return ip == null ? "UnknownHostException: " + host : ip;    }
    public static void main(String[] args) {        network.put("db", "172.18.0.2");        network.put("api", "172.18.0.3");
        System.out.println("api asks for db        -> " + resolve("api", "db"));        System.out.println("api asks for localhost -> " + resolve("api", "localhost"));        System.out.println("api asks for mysql     -> " + resolve("api", "mysql"));
        network.put("db", "172.18.0.4");   // db container recreated, new IP        System.out.println("after recreate, db     -> " + resolve("api", "db"));    }}
Output
api asks for db        -> 172.18.0.2
api asks for localhost -> 172.18.0.3 (api itself)
api asks for mysql     -> UnknownHostException: mysql
after recreate, db     -> 172.18.0.4

What this code does

  • The service name db resolves to whatever IP the container has now; after a recreate the IP changes and the name still works. That is why you never hard-code a container IP.
  • localhost resolves to the asking container itself, and the image name mysql is not a host name at all: only service names are registered.

docker compose up creates one network per project, named <project>_default (for ShopLite, shoplite_default), and attaches every service to it. Think of a hostel's Wi-Fi that only its rooms can join.

Docker runs a small DNS server on that network. DNS turns a name into an IP address: when api asks for db, Docker answers with the current IP of the db container. The IP changes when a container is recreated; the name does not, so always use the name.

The Java example is a simplified model: real Docker DNS also knows container names and aliases.

db:3306 inside Compose, localhost:3307 from the host

localhost is the name every computer uses for itself. Inside a container it means that container, not your laptop and not the other containers.

The same MySQL has two addresses, depending on who asks. The api container uses db:3306; your laptop uses localhost:3307. The picture shows both paths.

Two paths to the same MySQL. From your laptop, localhost:3307 reaches the published port and Docker forwards it to db port 3306. From the api container, db:3306 goes over the project network straight to db. If api uses localhost:3306 it reaches itself, where nothing listens.
Which address works depends on where the program runs

Example 2 · One setting, two addresses: choosing the JDBC URL

JdbcUrlDemo.javaJava
import java.util.Map;
public class JdbcUrlDemo {    static final String LAPTOP_DEFAULT = "jdbc:mysql://localhost:3307/shoplite";
    static String dbUrl(Map<String, String> env) {        return env.getOrDefault("DB_URL", LAPTOP_DEFAULT);    }
    public static void main(String[] args) {        Map<String, String> ideRun = Map.of();        Map<String, String> composeRun = Map.of("DB_URL", "jdbc:mysql://db:3306/shoplite");        Map<String, String> wrongRun = Map.of("DB_URL", "jdbc:mysql://localhost:3306/shoplite");
        System.out.println("IDE on laptop  : " + dbUrl(ideRun));        System.out.println("api in Compose : " + dbUrl(composeRun));        System.out.println("wrong in api   : " + dbUrl(wrongRun) + "  <- looks inside the api container");    }}
Output
IDE on laptop  : jdbc:mysql://localhost:3307/shoplite
api in Compose : jdbc:mysql://db:3306/shoplite
wrong in api   : jdbc:mysql://localhost:3306/shoplite  <- looks inside the api container

What this code does

  • The same code serves both places: without DB_URL it uses the laptop address on the published port 3307; Compose sets DB_URL to the service name and the container port 3306.
  • The third line is the classic bug. Inside the API container, localhost:3306 is the API container, where no MySQL runs, so the driver reports Connection refused.

So an API started with jdbc:mysql://localhost:3306/shoplite looks for MySQL inside its own container, finds nothing and fails.

The two addresses for the same MySQL are:

  • From another container on the project network: db:3306 (service name, container port).
  • From your laptop (IDE, Workbench, mysql client): localhost:3307 (the host side of ports: "3307:3306").

Predict the output

Pick the address

Use this file. Pick the JDBC URL that reaches MySQL.

Round 1 of 2

The api container (started by Compose) connects to MySQL.

services:
db:
image: mysql:8.4
ports:
- "3307:3306"
api:
build: .
This is why ShopLite reads the URL from DB_URL: the IDE run uses its default localhost:3307, and Compose passes jdbc:mysql://db:3306/shoplite.

ports vs expose

ports: publishes a container port on your computer as HOST:CONTAINER, so programs outside Docker can connect. Containers on the same network do not need it.

ports: opens a door from your computer into a container; expose: only writes a note. The snippet below uses both.

YAML
services:  db:    image: mysql:8.4    expose:      - "3306"        # documentation: other containers use db:3306  api:    build: .    ports:      - "8080:8080"   # published: your browser can open localhost:8080

expose: documents that a service listens on a port for other containers, and publishes nothing. On the project network, containers reach every port of each other with or without it, so expose is mostly documentation, like EXPOSE in a Dockerfile. Only ports: changes who can connect from outside.

Keeping the database unpublished

On a laptop, "3307:3306" is handy for Workbench. On a server, a published MySQL port is a door into your data. The example publishes only the API.

Example 3 · Production-like: only the API is published

Runs in: the shoplite-api project folder with Docker 27+

YAML
name: shopliteservices:  db:    image: mysql:8.4    restart: unless-stopped    environment:      MYSQL_ROOT_PASSWORD: rootpass      MYSQL_DATABASE: shoplite      MYSQL_USER: shoplite      MYSQL_PASSWORD: shoplitepass    volumes:      - mysql-data:/var/lib/mysql    # no ports: MySQL is reachable only as db:3306 on the project network  api:    build: .    restart: on-failure    ports:      - "8080:8080"    environment:      DB_URL: jdbc:mysql://db:3306/shoplite      DB_USER: shoplite      DB_PASSWORD: shoplitepassvolumes:  mysql-data:
Sample output
$ docker compose ps --format "table {{.Service}}\t{{.Ports}}"
SERVICE   PORTS
api       0.0.0.0:8080->8080/tcp
db        3306/tcp, 33060/tcp

What this code does

  • The db row shows 3306/tcp with no 0.0.0.0: part: the port exists inside the network but is not published on the host.
  • The API still works because it connects to db:3306 from inside the network. Only 8080 is open to the outside world.

Bots try passwords on open database ports all day. With db left without ports:, the API still reaches db:3306 over the project network and nothing outside Docker can.

If you sometimes need Workbench, publish to the loopback address only: "127.0.0.1:3307:3306" accepts connections from the same computer and not from the network.

Find the bug

Find the open database door

This file will run on a cloud server. Tap the line that exposes MySQL.

Only the API must be reachable from the internet.

Round 1 of 2

Debugging: exec, nc, UnknownHostException and Connection refused

Connection refused means the name or IP was found, but no program is listening on that port, so the connection is turned away at once. It is a different problem from a name that cannot be found.

When the API cannot reach MySQL, two error messages tell you which half is broken. Test from inside the container, where the app really runs.

Terminal
docker compose exec api sh$ getent hosts db                  # does the name resolve?172.18.0.2      db$ exit# no nc in the image? use a debug container on the same networkdocker run --rm -it --network shoplite_default nicolaka/netshoot nc -zv db 3306Connection to db (172.18.0.2) 3306 port [tcp/mysql] succeeded!

Example 4 · What the two errors look like from Java

ConnectProbeDemo.javaJava
import java.io.IOException;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.Socket;
public class ConnectProbeDemo {    static void probe(String label, String host, int port) {        try (Socket socket = new Socket()) {            socket.connect(new InetSocketAddress(host, port), 2000);            System.out.println(label + " -> open");        } catch (IOException e) {            System.out.println(label + " -> " + e.getClass().getSimpleName());        }    }
    public static void main(String[] args) throws IOException {        int closedPort;        try (ServerSocket temp = new ServerSocket(0)) {            closedPort = temp.getLocalPort();       // free a port: nothing listens there now        }
        try (ServerSocket server = new ServerSocket(0)) {            probe("listening port   ", "localhost", server.getLocalPort());            probe("closed port      ", "localhost", closedPort);            probe("unknown host name", "db.invalid", 3306);        }    }}
Output
listening port    -> open
closed port       -> ConnectException
unknown host name -> UnknownHostException

What this code does

  • ConnectException (message Connection refused) means the address was found but no program listens on the port: the same thing the MySQL driver reports for localhost:3306 inside the API container.
  • UnknownHostException means the name lookup failed before any connection was tried. .invalid is a reserved name that never resolves, like db from a laptop that is not on the Compose network.

docker compose exec api sh opens a shell inside the running api container. Small images often have no ping or nc; getent hosts db usually works on Ubuntu-based images, or you can start a throwaway debug container on the same network.

The two errors name the broken half:

  • UnknownHostException: db: the name could not be resolved. The app is not on the project network (for example, it runs in your IDE) or the service name is misspelt.
  • Connection refused (often inside a MySQL Communications link failure): wrong port, localhost inside a container, or MySQL is still starting.

Order of execution

Debug a failing connection

The api cannot reach MySQL. Put the checks in a sensible order.

Next step

Check your understanding

11 quick questions