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

Docker Compose networking and service discovery

Submitted by: @anonymous··
0
Viewed 0 times
docker composenetworkingservice discoverynetworksdepends_on

Problem

Need containers in Docker Compose to communicate with each other by name, with proper network isolation.

Solution

Docker Compose networking patterns:

version: '3.8'
services:
  api:
    build: ./api
    ports:
      - '3000:3000'  # Host:Container
    networks:
      - frontend
      - backend
    environment:
      - DATABASE_URL=postgres://db:5432/mydb
      - REDIS_URL=redis://cache:6379
    depends_on:
      db:
        condition: service_healthy

  web:
    build: ./web
    ports:
      - '8080:80'
    networks:
      - frontend
    # Can reach 'api' but NOT 'db' or 'cache'

  db:
    image: postgres:16
    networks:
      - backend
    healthcheck:
      test: pg_isready -U postgres
      interval: 5s
      timeout: 5s
      retries: 5

  cache:
    image: redis:7
    networks:
      - backend

networks:
  frontend:   # web <-> api
  backend:    # api <-> db, cache


Key points:
  • Services on same network reach each other by service name
  • Use multiple networks for isolation
  • depends_on with healthcheck ensures startup order
  • Only expose ports that need host access
  • Internal DNS resolves service names automatically

Why

Docker Compose creates a default network, but explicit networks provide security through isolation - the web frontend shouldn't be able to directly access the database.

Gotchas

  • Services on different networks cannot communicate
  • Port mapping is host:container, not container:host
  • depends_on without condition only waits for container start, not readiness

Context

Multi-service applications using Docker Compose

Revisions (0)

No revisions yet.