CodePark/ questions / Networking & ports
START PRACTICINGPRACTICE
Backend question · Docker › Networking & ports

How do two containers, say an API and Postgres, talk to each other?

Put both containers on the same user-defined bridge network. A user-defined bridge network is a private network you create yourself. For example, run docker network create app, then start both containers with --network app.

On user-defined networks, Docker runs a built-in DNS server. DNS turns a name into an IP address. So the API can reach the database by its container name or network alias, such as postgres://db:5432.

The default bridge network does not give you this name-based DNS. Containers there can only reach each other by IP, and the IP changes between runs. The old --link flag is legacy, so don't use it.

Container-to-container traffic uses the container's own port (5432), not a port published with -p. You only need to publish a port for access from outside Docker.

Docker Compose does all this for you. It creates a network for the project, and each service is reachable by its service name.

  • Put the containers on a user-defined bridge network.
  • Docker's built-in DNS finds containers by name or alias.
  • The default bridge network cannot find containers by name.
  • Use the container's own port, not the published port.
  • Compose creates a network, and services reach each other by service name.