Skip to content
Velloreth
Tutorials 9 min read

Deploy Applications with Docker Compose

Deploy a real multi-service app with Docker Compose - compose.yaml structure, healthchecks, env files, volumes, updates, reverse proxy, and backups on a single server.

By

Compose sits in an awkward spot in most people’s mental model: too high-level to be “just Docker commands”, too low-level to be Kubernetes. That is exactly why it is useful. For one machine running a database, a cache, and an application, it is the whole deployment toolchain.

This walkthrough deploys a small but real stack - a Node API, PostgreSQL, and Redis - and then covers the parts that determine whether it survives contact with a production server: health checks, environment files, persistence, updates, and backups.

Check your install

docker --version
docker compose version
Docker version 28.x.x, build xxxxxxx
Docker Compose version v2.x.x

If docker compose is not found, install the compose plugin rather than the legacy docker-compose binary - v1 is end of life and behaves differently in several places that matter here, including --wait and health check conditions.

You need a server with Docker installed, SSH access, and a domain name pointing at it if you want TLS. Everything below runs as a non-root user in the docker group.

The stack

server/
├── compose.yaml
├── .env
├── .env.example
├── .gitignore
├── api/               # your app, with a Dockerfile
└── data/              # created by Docker, not by you

The application is a plain Node service. Its api/Dockerfile:

FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev

FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]

Multi-stage so build tools never reach the final image, npm ci so installs are reproducible, and USER node so the process does not run as root inside the container. Those three lines are the non-negotiables.

compose.yaml, one service at a time

name: myapp

services:
  api:
    build: ./api
    restart: unless-stopped
    ports:
      - "127.0.0.1:3000:3000"
    environment:
      DATABASE_URL: postgres://app:${POSTGRES_PASSWORD}@db:5432/app
      REDIS_URL: redis://cache:6379
      SESSION_SECRET: ${SESSION_SECRET}
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:3000/health"]
      interval: 15s
      timeout: 5s
      retries: 3
      start_period: 20s

  db:
    image: postgres:17-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - dbdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s

  cache:
    image: redis:7-alpine
    restart: unless-stopped
    command: ["redis-server", "--appendonly", "yes"]
    volumes:
      - cachedata:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 3

volumes:
  dbdata:
  cachedata:

Line by line, the decisions:

name: myapp fixes the project name. Without it, Compose derives one from the directory, so renaming the folder silently creates a second stack.

build: ./api vs image: - use build for code you own, image for third-party services. Postgres and Redis should always come from a pinned tag: postgres:17-alpine is a decision, postgres:latest is a surprise waiting for a major upgrade you did not ask for.

ports: "127.0.0.1:3000:3000" binds to loopback only. The API is not reachable from the internet; a reverse proxy on the same host forwards to it. Binding 3000:3000 would expose it directly, which you almost never want.

restart: unless-stopped brings containers back after a crash or a host reboot, but leaves them alone once you deliberately stop them. always restarts even after you run docker compose stop, which makes maintenance annoying.

Volumes are named, declared under the top-level volumes: key. Compose prefixes them with the project name, so they are not shared between unrelated stacks.

The health check that makes startup ordering work

The single most common Compose failure looks like this:

api-1  | Error: connect ECONNREFUSED 172.19.0.2:5432
api-1  | exiting with code 1

depends_on: [db] guarantees Postgres starts first. It does not guarantee Postgres is ready to accept connections - initialising a data directory takes seconds. During that window your app connects, fails, exits, restarts, and fails again.

condition: service_healthy closes the gap. Compose waits until the health check reports healthy before starting the dependent service:

depends_on:
  db:
    condition: service_healthy

The three conditions:

ConditionWaits forUse when
service_startedcontainer runningno readiness to wait for (Redis, cache)
service_healthyhealth check passingdatabases, anything with a warm-up
service_completed_successfullyone-off container exits 0migrations, seed jobs

Note what health checks do not do: they do not restart dependents when a service becomes unhealthy later. If the database dies at 3am, the API still needs its own connection retry logic. Compose gets the ordering right; your application still owns resilience.

Environment files and secrets

Create .env next to compose.yaml:

POSTGRES_PASSWORD=replace-me-with-a-long-random-string
SESSION_SECRET=replace-me-too

And .env.example with the same keys but dummy values, so a collaborator knows what to fill in. Then .gitignore:

.env
data/

Compose automatically reads .env from the project directory for variable substitution in compose.yaml. ${POSTGRES_PASSWORD} in the YAML is replaced at parse time - it is not a shell expansion inside the container.

Two things that bite people:

  • An unset variable expands to an empty string, silently. Validate before deploying with docker compose config, which prints the fully resolved file. If you see POSTGRES_PASSWORD= in the output, your .env is not being read.
  • Environment variables are visible to anyone who can run docker inspect. That is fine for a single-tenant server. For anything shared, use Docker secrets or a dedicated secrets manager instead.

Deploy it

docker compose config --quiet && echo "config OK"
docker compose up -d --wait
[+] Running 4/4
 ✔ Network myapp_default   Created
 ✔ Volume "myapp_dbdata"   Created
 ✔ Container myapp-cache-1  Healthy
 ✔ Container myapp-db-1     Healthy
 ✔ Container myapp-api-1    Healthy

--wait blocks until health checks pass (or time out) instead of returning immediately. Without it, up -d returns as soon as containers start, and you have no idea whether the app actually came up.

Then verify:

docker compose ps
NAME              IMAGE                  STATUS                    PORTS
myapp-api-1       myapp-api              Up 4 minutes (healthy)    127.0.0.1:3000->3000/tcp
myapp-cache-1     redis:7-alpine         Up 4 minutes (healthy)
myapp-db-1        postgres:17-alpine     Up 4 minutes (healthy)

The (healthy) suffix is the signal you actually care about. Up 4 minutes alone only means the process has not exited.

The day-to-day commands

TaskCommand
Tail logs for one servicedocker compose logs -f api --tail 100
Run a one-off commanddocker compose exec db psql -U app -d app
Open a shelldocker compose exec api sh
Restart after config changedocker compose up -d
Stop, keep datadocker compose stop
Stop and remove containers and networkdocker compose down
Stop and delete data volumesdocker compose down -v
Resolve and print the final configdocker compose config
Rebuild after a Dockerfile changedocker compose up -d --build api

down -v deletes your database. It is the correct command when you genuinely want a clean slate and the wrong command everywhere else. Nothing else in the daily workflow destroys data.

Updating a running stack

Two cases, two commands.

Only the application changed:

git pull
docker compose up -d --build api

Base images moved (Postgres patch, Redis patch):

docker compose pull
docker compose up -d

Watch it come back healthy before closing the terminal:

docker compose up -d --wait && docker compose ps

For the API container there is a brief window where the old container stops and the new one starts. On a single host, with one instance, that is a sub-second gap - usually fine for a small service, and a real problem if it is not. The honest options at that point are a proxy that retries on connection failure, running two replicas with a load balancer in front, or accepting the blip. Compose can do the second (deploy.replicas: 2 plus a proxy), but if you are routinely needing zero-downtime rollouts across a fleet, you have outgrown a single host and should be looking at something else.

Reverse proxy and TLS

Let the proxy handle certificates. Caddy is the shortest path - one service, automatic HTTPS:

  proxy:
    image: caddy:2-alpine
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      api:
        condition: service_started

Caddyfile:

api.example.com {
    reverse_proxy api:3000
}

Services reach each other by service name on the default Compose network - api:3000, db:5432 - without you declaring a network at all. Declare custom networks only when you want two stacks isolated from each other.

Expose only the proxy’s ports. Everything else binds to 127.0.0.1 or has no ports: mapping at all.

Backups, because the deploy is the easy part

A database with no tested backup is a database you have not deployed yet. Schedule a dump on the host:

#!/bin/sh
set -eu
stamp=$(date +%F-%H%M)
docker compose exec -T db pg_dump -U app -d app | gzip > "/backups/app-$stamp.sql.gz"
find /backups -name 'app-*.sql.gz' -mtime +14 -delete

Cron it:

crontab -e
# 0 3 * * * /srv/myapp/backup.sh >> /var/log/app-backup.log 2>&1

Two rules: the backup must run without you, and you must restore from it at least once into a scratch container before you trust it. pg_dump exiting non-zero for six weeks is invisible until the day you need it.

Hardening around the stack

Compose manages containers. The host underneath still needs the basics:

sudo ufw allow OpenSSH
sudo ufw allow 80,443/tcp
sudo ufw enable

Only SSH and the proxy ports. Everything else in compose.yaml should bind to 127.0.0.1 or to no host port at all - the firewall is a second layer, not the first.

Cap runaway processes with limits in compose.yaml, so one bad deploy cannot take the machine down:

    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 512M

Keep base images patched. On Ubuntu or Debian the host handles its own kernel updates through unattended upgrades; container images you handle yourself, which is the practical argument for a weekly docker compose pull && docker compose up -d --wait in a maintenance window.

Finally, add a .dockerignore in api/ so your build context stays small and no secrets get copied into a layer:

node_modules
.git
.env
*.log

A .env file copied into an image is readable by anyone who pulls it, and it will still be there after you delete the file from Git history.

What Compose is not

It is not a scheduler, it has no notion of multiple machines, and it will not rebalance or roll out across nodes. Scaling is --scale api=3 on one host, competing for the same CPU. There is no built-in secrets encryption, no automatic certificate rotation for internal traffic, and no self-healing beyond restarting the container that died.

That list is not a deficiency for its intended shape. One server, a handful of services, a compose.yaml in Git, a .env on the box, and a cron job for dumps - that setup runs small production workloads for years with about twenty minutes of maintenance a month.

The stack above, once docker compose ps shows everything healthy behind your proxy, is deployed. Revisit it when traffic or team size forces the question, not before.

Frequently asked questions

Is Docker Compose good enough for production?
For a single server running a handful of services, yes - it is what many small teams and side projects actually run. It gives you reproducible startup, health checks, restart policies, and one-command updates. Outgrow it when you need multiple hosts or rolling deployments across a fleet.
What is the difference between docker-compose and docker compose?
docker-compose (with a hyphen) is the old Python v1 binary, which is end of life. docker compose (no hyphen) is the v2 plugin written in Go and bundled with Docker Desktop and the Docker Engine plugin set. Use the hyphenless form.
How do I handle database migrations safely?
Run them as a one-off container before the new app version starts, using depends_on with condition: service_completed_successfully. Make migrations backward compatible so an old app container can run against the new schema during the transition.
Where should my data live?
In named volumes, not bind mounts, for anything the database writes. Named volumes are managed by Docker, survive container removal, and are straightforward to back up with a dump command run through docker compose exec.