Ravindra BagaleCourses & study guides

Chapter 7: Docker Volumes, Networks and Compose

7.3 User-defined bridge networks

On the default bridge, containers do not get reliable DNS names for each other the way beginners expect. Create a user-defined bridge so service names resolve.

docker network create badge-api_net

docker run -d --name badge-api-db --network badge-api_net \
  -v badge-api_pgdata:/var/lib/postgresql/data \
  -e POSTGRES_PASSWORD=lab-only-change-me \
  postgres:16

docker run -d --name badge-api --network badge-api_net \
  -p 8080:8080 \
  -e DATABASE_URL=postgres://postgres:lab-only-change-me@badge-api-db:5432/postgres \
  badge-api-hello:0.1

Inside the API container, the hostname badge-api-db is the DB's shop name on the private lane. You do not need the host's public IP for that hop.

Idea Picture
User-defined network Private network between containers
Container name / Compose service name Shop sign on that corridor
Published -p port Street door for browsers / curl from your laptop
DB without -p No street door — only corridor access

Steps — network smoke check

  1. docker network create badge-api_net (skip if it exists).
  2. Start DB on badge-api_net with a named volume (no -p for lab safety on public VMs).
  3. Start API on the same network with -p 8080:8080 and DATABASE_URL pointing at host badge-api-db.
  4. From the API container: docker exec -it badge-api sh then try a DB client or app health that hits the DB (if your image has tools).
  5. From the host: curl http://localhost:8080/health.

What you see: API health OK; docker network inspect badge-api_net shows both containers attached.

Ravindra Bagale's Tip

Connection string madhe localhost DB sathi API container madhun chalat nahi — localhost = tyach container. Service name badge-api-db use kara. Bilkul visru naka!