Your First docker compose yaml file, Explained (Guide)

If you have ever started a project with docker run and watched the command grow into a tangle of flags, port mappings, and volume mounts, you already know the problem Compose solves. A docker compose yaml file replaces that long command with one short, readable document describing every container your app needs: the web server, the API, the database, and how they connect. You write the file once, then start the whole stack with a single command. This guide explains what the file does and walks you through writing your first one, using an annotated example you can run on your own VPS today.

What a docker compose yaml file actually does

Definition: a docker compose yaml file is a declarative document, usually named docker-compose.yml, that tells Docker which containers to run, how to configure them, and how they communicate.

Declarative means you describe the end state you want, not the steps to get there. You do not write “start this, then link that.” You write “I want a web server on port 8080 and a database with this password,” and Compose figures out the startup order, creates the networks, and mounts the volumes. When you change the file, you run docker compose up -d again and Compose applies only the differences.

Three things make this worth learning on day one:

  • Repeatability. The same file starts the same stack on your laptop, your VPS, or a teammate’s machine. No more “works on my server” surprises.
  • Version control. The file is plain text, so it lives in git next to your code. You can review infrastructure changes like any other pull request.
  • One-command lifecycle. Starting, stopping, rebuilding, and tearing down the entire stack each takes one short command, which you will learn below.

The three building blocks: services, networks, volumes

Every docker compose yaml file is built from three concepts. Understand these and you can read any Compose file ever written.

Services

A service is one container, or one type of container, in your stack. A web server is a service, a database is a service, a background worker is a service. Each service has an image (or a build path to a Dockerfile) plus its configuration: ports, environment variables, volumes, and restart behavior. One service can run multiple identical containers with --scale, but for most self-hosted setups one container per service is enough.

Networks

Services on the same network resolve each other by service name, no IP addresses needed. In the example below, the API connects to the database at hostname db, and that just works because both sit on the backend network. Compose creates a default network automatically, but declaring your own, like splitting a public frontend network from a private backend one, keeps the database unreachable from the outside.

Volumes

Containers are disposable: when you remove one, everything written inside it disappears. Volumes are how you keep data alive. A named volume like pgdata is managed by Docker and is the right home for database files. A bind mount like ./html:/usr/share/nginx/html maps a folder on your host into the container, which is handy for config files and static sites you edit directly.

Writing your first docker-compose.yml example

Here is a complete first file: an nginx web server in front of a small API, backed by Postgres. Each section is annotated so you can see what every line does.

services:
  web:
    image: nginx:1.27-alpine      # lightweight nginx image
    ports:
      - "8080:80"               # host port 8080 -> container port 80
    environment:
      - NGINX_HOST=${DOMAIN:-localhost}  # value from .env, default localhost
    volumes:
      - ./html:/usr/share/nginx/html:ro  # your site files, read-only
    networks:
      - frontend
    depends_on:
      api:
        condition: service_healthy  # wait until api passes its healthcheck

  api:
    build: ./api                  # build from Dockerfile in ./api
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/appdb
    networks:
      - frontend
      - backend
    healthcheck:                  # defines what "healthy" means
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 10s
      timeout: 3s
      retries: 5

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD}  # never hardcode real passwords
    volumes:
      - pgdata:/var/lib/postgresql/data   # named volume: data survives restarts
    networks:
      - backend                   # no route to the public frontend network

networks:                         # declared networks are created on first up
  frontend:
  backend:

volumes:                          # declared volumes are created on first up
  pgdata:

Save it as docker-compose.yml, create an empty ./html folder and a .env file (see below), then run docker compose up -d. Visit http://your-server:8080 and nginx answers. That is your first working stack.

The docker compose commands you will use every day

You only need a handful of commands for daily work. Run them from the folder that holds your docker compose yaml file.

  • docker compose up -d – start everything in the background (add --build to rebuild images after changing a Dockerfile).
  • docker compose ps – show the running containers and their published ports.
  • docker compose logs -f – stream logs from all services (append a service name like web to filter).
  • docker compose exec web sh – open a shell inside the running web container.
  • docker compose restart api – restart one service without touching the rest.
  • docker compose config – validate the file and print the merged result. Run this before up when something looks off.
  • docker compose down – stop and remove containers and networks. Your named volumes stay, so data is safe.
  • docker compose down -v – also delete named volumes. This wipes database data, so treat it as destructive.

Note the command is docker compose with a space, the current Compose v2 plugin. The old docker-compose with a hyphen is the legacy Python version and is deprecated.

Keep secrets out of the file: your docker compose env file

Compose files end up in git repositories, and passwords do not belong in git. Compose reads a .env file in the same folder automatically and substitutes ${VAR} placeholders in the YAML. A minimal .env for the example above looks like this:

DB_PASSWORD=change-this-to-something-long
DOMAIN=example.com

Add .env to your .gitignore and commit only a .env.example with placeholder values so teammates know what to fill in. On the server, create the real .env once and never commit it. For values with special characters, wrap them in quotes inside the .env file to avoid parsing surprises.

depends_on and healthchecks: ordering is not readiness

A common beginner mistake is assuming depends_on waits for a service to be ready. It only waits for the container to start. A Postgres container starts in a second but needs several more to accept connections, and an API that connects too early crashes on boot.

The fix is the pattern in the example: give the dependency a healthcheck, then use depends_on with condition: service_healthy. Compose waits until the healthcheck passes before starting the dependent service. For images that ship without a healthcheck, define one yourself with a test command, as the api service above does with curl.

FAQ

Do I need to install something extra to use Compose?

No. Compose v2 ships with Docker Desktop and with the Docker Engine plugin package (docker-compose-plugin) on Linux. If docker compose version prints a version, you are ready.

Can I use Compose in production on a VPS?

Yes, for single-server setups it is one of the simplest reliable options. Pair it with restart: unless-stopped on critical services so containers come back after a reboot, and keep backups of your named volumes. Most self-hosted apps you will meet, from Jellyfin to Vaultwarden, ship exactly this kind of file.

How do I update a service to a newer image?

Edit the tag in the file, then run docker compose up -d. Compose pulls the new image, recreates only that container, and leaves the rest of the stack running.

Where did my data go after docker compose down?

Nowhere: plain down keeps named volumes. Data is only deleted with down -v or by explicitly removing the volume. If a database looks empty after a restart, check that the volume name in the file matches the one you created. A full Nextcloud stack is a good second project once this first file makes sense.

What is the difference between ports and expose?

ports publishes a container port on the host so the outside world can reach it. expose only documents which ports a service uses for other containers on the same network. On a VPS, use ports only for services the public needs.

Where to go from here

You now have a mental model of the file and a working first stack. The natural next steps are adding restart: unless-stopped to your services, putting a reverse proxy like Caddy or Traefik in front for HTTPS, and setting up volume backups before you store anything you care about. From there, each new service you add is just another block under services:.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.