Docker Compose

Docker Compose in DevOps Tools: --- Before a symphony, dozens of musicians must become one orchestra, and they do not simply wander on and start playing.


The Analogy: The Orchestra Assembling Before the Downbeat

Before a symphony, dozens of musicians must become one orchestra, and they do not simply wander on and start playing. A stage manager and a conductor coordinate the assembly. The sections file in and settle, the concert hall is the shared space in which any player can hear and answer any other, and a plan governs who is summoned and in what order. It is a small society being wired together for a single performance, out of parts that arrived separately and know nothing of each other until they are placed in the same room.

The players address one another by role, never by seat. A cue goes to "the first oboe" or "the timpani", not to a chair number, because chairs and stands are rearranged for every concert while the roles stay fixed. The conductor lifts a baton toward "the cellos" and whoever occupies the cello chairs tonight responds. This is exactly how services on a Compose network find each other: by service name, a stable address the platform resolves to wherever that service currently sits, and never by a numeric address that is reassigned each time the ensemble is rebuilt.

The assembly follows dependencies. The strings settle first because the winds will tune to them; the soloist walks on last, after the ensemble is already in place. Summoning a section before the one it relies on is pointless, because the second oboe cannot tune to an A that has not yet been sounded. The conductor's plan sequences who comes before whom, in precisely the way a service declares which other services must be brought up ahead of it.

But here is the error that ruins an opening. Being in your chair is not the same as being ready to play. A musician can be seated, the music open on the stand, and still hold a cold, flat instrument that has not taken the tuning A. A conductor who reads "everyone is seated" as "everyone is ready" and gives the downbeat launches the symphony into a sour, ragged mess: the players were present, but not prepared. Presence is not readiness. That is exactly the trap in the orchestration tool at the end of this lesson, which starts a service the moment the one it depends on is merely running rather than actually able to answer, and the dependent service fails reaching for a database that is up but not yet listening.


Syntax or Core Structure

A Compose file describes a set of services, and the platform does three things with it: puts every service on a shared private network where they reach each other by name, mounts named volumes so data outlives any single container, and starts services in an order that respects their declared dependencies. A minimal two-service stack:

services:
  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: secret
    volumes:
      - db_data:/var/lib/postgresql/data

  api:
    build: ./api
    ports:
      - "5000:5000"
    depends_on:
      - db
    environment:
      # reach the database by its SERVICE NAME 'db', never a hardcoded IP
      DATABASE_URL: postgres://postgres:secret@db:5432/app

volumes:
  db_data:

The api reaches the database at the host db -- the service name -- because Compose runs a small DNS resolver on the shared network that maps each service name to its current address. That indirection matters because the numeric address is not stable: it is reassigned every time the stack comes up. Model the resolver and a later restart:

def make_network(run_id):
    return {'db': '172.18.0.%d' % (2 + run_id), 'api': '172.18.0.%d' % (3 + run_id)}

net1 = make_network(0)
net2 = make_network(10)   # a later 'compose up': fresh addresses
print('run1: name db ->', net1['db'])
print('run2: name db ->', net2['db'])
hardcoded = net1['db']
print('hardcoded %s valid on run2? %s' % (hardcoded, hardcoded == net2['db']))
print('name db valid on run2? %s' % ('db' in net2))

Output:

run1: name db -> 172.18.0.2
run2: name db -> 172.18.0.12
hardcoded 172.18.0.2 valid on run2? False
name db valid on run2? True

The database's numeric address moved from .2 to .12 across a restart. A service that had hardcoded the first address now points at nothing, while a service that addresses db by name follows it wherever it lands. This is why you name your neighbors, not their seat numbers -- the cue goes to "the first oboe", and whoever is in that chair tonight answers.


Technical Depth: The Five Things a Compose File Controls

Each key does one distinct job

A Compose service is a small bundle of orthogonal decisions, and confusing them is the source of most Compose bugs. It is worth holding each one separately in mind.

KeyWhat it controlsCommon misread
image or buildwhere the container comes fromthinking build re-runs on every up
networkswho can reach whom, by service nameassuming a stable numeric address
volumeswhat data outlives the containerstoring state in the writable layer
depends_onstart order of servicesmistaking it for readiness
portswhich service ports the host exposesexposing a db port to the world

The networks row is quieter but worth understanding, because it is doing work you never wrote. Compose creates one private network per project automatically and attaches every service to it, which is why the api could reach db by name without a single line of network configuration. That default network is also an isolation boundary: services in a different Compose project sit on a different network and cannot reach yours by name, so two stacks can both run a service literally called db on the same host without colliding. The name you resolve is scoped to your project, not the whole machine, which is what makes name-based addressing safe to rely on in the first place.

The two rows that cause real outages are volumes and depends_on. This section takes the first; the Real World Example takes the second.

A named volume outlives the container; the writable layer does not

Recreating a container -- which Compose does on nearly every config change -- discards its writable layer entirely. Data you care about must live on a named volume, which is storage that exists independently of any one container and is remounted onto the replacement. Model a store recreated both ways:

class Volume:
    def __init__(self):
        self.rows = []
class Container:
    def __init__(self, storage):
        self.storage = storage
    def write(self, r):
        self.storage.rows.append(r)

named = Volume()                     # storage lives outside the container
c1 = Container(named)
for r in ('a', 'b', 'c'):
    c1.write(r)
print('named volume before recreate: %d rows' % len(named.rows))
c2 = Container(named)                # recreated container, same volume remounted
print('named volume after recreate:  %d rows' % len(c2.storage.rows))

d1 = Container(Volume())             # no named volume: the writable layer
for r in ('a', 'b', 'c'):
    d1.write(r)
print('writable layer before recreate: %d rows' % len(d1.storage.rows))
d2 = Container(Volume())             # recreate -> a fresh, empty writable layer
print('writable layer after recreate:  %d rows' % len(d2.storage.rows))

Output:

named volume before recreate: 3 rows
named volume after recreate:  3 rows
writable layer before recreate: 3 rows
writable layer after recreate:  0 rows

The named volume keeps all three rows across the recreate, because the storage object was never owned by the container -- it was mounted in. The writable-layer store had the same three rows and lost every one, because recreating the container built a fresh empty layer. A Postgres service without a named volume behaves exactly like the second case: the first compose up after a config edit silently wipes the database. The rule is blunt -- durable state goes on a named volume, never in the container.


Real World Example: The Startup Race Against the Database

A team ships a stack where the api declares depends_on: [db], and they believe that guarantees the database is ready when the API boots. It runs fine on their laptops for weeks, then fails intermittently in CI and on cold starts in production. The cause is that a database container needs a few seconds after it starts before it accepts connections -- Postgres runs recovery and opens its socket -- and depends_on does not wait for that. Model the two connect timings against the database's readiness:

DB_WARMUP = 3   # seconds after the db container starts before it accepts connections

def start(api_connects_at):
    return 'OK' if api_connects_at >= DB_WARMUP else 'CONNECTION REFUSED'

bt = 0           # depends_on: satisfied the instant the db CONTAINER is up
ht = DB_WARMUP   # condition: service_healthy: waits for the readiness probe

print('depends_on start-order: api connects t=%d, db ready t=%d -> %s' % (bt, DB_WARMUP, start(bt)))
print('service_healthy ready:  api connects t=%d, db ready t=%d -> %s' % (ht, DB_WARMUP, start(ht)))
print('gap=%d s the api spent talking to a db that was up but not listening' % (DB_WARMUP - bt))

Output:

depends_on start-order: api connects t=0, db ready t=3 -> CONNECTION REFUSED
service_healthy ready:  api connects t=3, db ready t=3 -> OK
gap=3 s the api spent talking to a db that was up but not listening

Plain depends_on lets the API connect at t=0, the instant the database container is running, and the connection is refused because the database will not accept one until t=3. The fix Compose offers is a healthcheck on the database plus depends_on with condition: service_healthy on the API, which holds the API back until the readiness probe passes at t=3, turning the refusal into a clean connect. The three-second gap is the whole bug: a window where the container is up but the service inside is not listening, and depends_on cannot tell the difference.

The healthcheck fix is correct for startup, but it should not be mistaken for a complete answer, and the honest limits matter. condition: service_healthy is a one-time gate evaluated only during up: it proves the database was accepting connections at boot, not that it stays up. If the database crashes and restarts an hour later, the API is not re-blocked and will see the same CONNECTION REFUSED it saw at t=0 -- depends_on says nothing about the steady state. The design flaw that survives even the fix is treating a dependency as a one-time startup event rather than a continuous relationship. A correct service assumes its dependencies can vanish and return at any moment and reconnects with retries and backoff; depends_on and healthchecks are a convenience for a clean first boot, not a substitute for connection-retry logic. A stack that works only because the database happened to win the startup race is one crash away from the same failure at three in the morning.


Common Mistakes

  1. Treating depends_on as readiness. It waits for the dependency's container to start, not for the service inside to accept connections, so the dependent boots against a service that is up but not listening and crashes on its first query.
  1. Hardcoding a service's IP instead of its name. Addresses are reassigned on every up, so a baked-in IP points at nothing after a restart. Address services by name and let the Compose resolver follow them.
  1. Storing state in the container instead of a named volume. The next config edit recreates the container and discards its writable layer, silently wiping data that was not on a named volume.
  1. Publishing internal ports to the host. A ports entry on an internal database exposes it on the host network, often to the whole machine. Internal services should reach each other over the Compose network without ports at all.
  1. Committing secrets in the compose file. A real POSTGRES_PASSWORD written into a checked-in file leaks to everyone with repo access. Keep credentials in an env file or a secrets mechanism, never in version control.
  1. Expecting build to rebuild on every up. up reuses the existing image, so code changes do not appear until you run up --build or rebuild explicitly. Silent staleness follows from assuming otherwise.
  1. Leaning on start order in place of retries. Even a correct startup sequence does not survive a dependency that restarts mid-run, so an app without reconnect logic breaks the moment its database bounces.
  1. Being surprised by down and volumes. Plain down keeps named volumes while down -v destroys them, so people either lose data they meant to keep or are confused that old data persists after a teardown.
  1. Relying on the top-level version key. It is obsolete in modern Compose and ignored, so treating it as something that changes behavior is a mistake left over from older tutorials.

Best Practices

  • Address every service by its name and let the Compose network resolve it, so the stack survives the address reassignment that happens on each up.
  • Put all durable state on named volumes and treat each container's writable layer as scratch that will be discarded on the next recreate.
  • Gate dependents with a healthcheck plus condition: service_healthy for a clean first boot, and still write reconnect-with-backoff in the application for everything after boot.
  • Keep internal services off the host by publishing ports only for what genuinely needs external access, leaving databases reachable only on the internal network.
  • Keep secrets out of the committed compose file, using an env file or a secrets mechanism so credentials never enter version control.
  • Rebuild deliberately with up --build when code changes, rather than assuming a plain up picks up a new image.
  • Design each service to tolerate a dependency disappearing and returning during normal operation, not only at startup, so a mid-run restart does not take the stack down.
  • Give each long-lived service a healthcheck so orchestration has a real readiness signal to act on instead of the far weaker fact that a container is running.

Practice Exercises

  1. Extend the readiness model so the database becomes ready at t=5 and the API retries every second up to six times. Compute at which attempt the API succeeds, and show that the plain depends_on version without retries would still have failed.
  1. Add a third service, a cache, that the API also depends on. Write the service-name resolver for all three services and show the API resolving both db and cache by name after a restart that moves every address.
  1. Model down versus down -v against a named volume holding three rows. Show which command leaves the three rows intact and which returns zero, mirroring the persistence block.
  1. Write a health-aware start function that blocks the API until both db and cache report healthy, and compute the API's connect time as the maximum of the two services' warmup times.