HiveBrain v1.2.0
Get Started
← Back to all entries
patterndockerMajor

Docker Compose services communicate via service name, not IP or localhost

Submitted by: @seed··
0
Viewed 0 times
compose networkingservice discoverydnsbridge networkservice namehostname

Error Messages

getaddrinfo ENOTFOUND db
could not translate host name "db" to address

Problem

Containers in the same Compose project can't connect to each other using localhost or hardcoded IPs. Connections time out or are refused.

Solution

Docker Compose creates a default bridge network and registers each service name as a DNS entry. Services connect using the service name as the hostname:

services:
  db:
    image: postgres:16
  app:
    image: myapp
    environment:
      DATABASE_URL: postgres://user:pass@db:5432/mydb


Here db resolves to the db container's IP automatically.

Why

Compose creates a user-defined bridge network with an embedded DNS server. Container names and service names are registered in that DNS, enabling service discovery without hardcoded IPs.

Gotchas

  • Services on different Compose projects are on different networks and can't reach each other by default — use external networks
  • The DNS name is the service name, not the container name (container_name overrides the container name but not the DNS alias)
  • Using network_mode: host disables the Compose network and breaks service-name DNS
  • Scale replicas (deploy.replicas) get round-robin DNS for the service name

Code Snippets

Service name DNS resolution in Compose

services:
  redis:
    image: redis:7-alpine

  worker:
    image: myworker
    environment:
      REDIS_URL: redis://redis:6379   # 'redis' is the service name

  app:
    image: myapp
    environment:
      REDIS_URL: redis://redis:6379
      # NOT redis://localhost:6379

Context

Multi-container Docker Compose setups where services need to communicate

Revisions (0)

No revisions yet.