Chapter 2 · Lesson 3 of 20
Docker

Docker Compose basics: run web and database with compose.yaml

Docker Compose runs several containers together from one YAML file that describes the services, ports and volumes.

By the end you will

Run a web server and a database together from one compose.yaml, then stop them.

Time
18 min
Level
Beginner
Check
4 questions
You need
  • Docker with the compose plugin installed

Docker Compose starts several containers from one compose.yaml: you describe each service once, and docker compose up -d creates the network, volumes and containers for you. The file replaces a pile of long docker run commands and makes the setup repeatable on any machine with Docker.

How it works#

A compose file declares services. Each service is a container recipe: an image (or a build), ports, environment, volumes and a restart policy. docker compose up reads the file, creates a private network for the project, creates any named volumes, then creates and starts one container per service.

Compose names things after the project, which defaults to the name of the folder holding the file. A service web in folder demo becomes the container demo-web-1, on the network demo_default, and a volume pgdata becomes demo_pgdata. That prefix is why two folders can use the same service names without clashing.

On that network, each service name is a hostname. The web service can reach Postgres at db:5432, so you never publish the database port just so another container can use it. Compose is also declarative: if you change the file and run up -d again, it recreates only the services whose configuration changed and leaves the rest alone.

A worked example, start to finish#

Take the file in step 1 and run docker compose up -d in a folder called demo.

  1. Compose reads the file and decides the project name is demo.
  2. It creates the network demo_default and the volume demo_pgdata.
  3. It pulls nginx and postgres:16 if they are missing.
  4. It creates and starts demo-db-1 and demo-web-1.

Run the same command again and nothing is recreated, because nothing changed. Now change the port to "8081:80" and run it a third time: Compose recreates only demo-web-1, and demo-db-1 keeps running untouched. That diff-and-apply behaviour is the main reason to prefer Compose over a script of docker run lines.

Step 1: Write compose.yaml#

yaml
services:
  web:
    image: nginx
    ports:
      - "8080:80"
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: change-me
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Indent with spaces only, never tabs. Quote port mappings like "8080:80" so YAML does not read them as a number. Replace change-me with a real password before you use this for anything but a test. You do not need a version: line: current Compose ignores it and may warn that it is obsolete.

Step 2: Start it#

bash
docker compose up -d

up creates and starts everything. -d runs it in the background. Run the command in the folder that holds the file, or pass -f path/to/compose.yaml.

What you should see: lines for the network, the volume and each container, ending in Started (or Running).

Step 3: Check that it works#

bash
docker compose ps
curl http://localhost:8080

What you should see: web and db both with status Up, port 0.0.0.0:8080->80/tcp on web, and the nginx welcome page from curl. The db shows only 5432/tcp, which means it is not published to the host.

Step 4: Logs and cleanup#

bash
docker compose logs db
docker compose logs -f web
docker compose down

logs prints a service’s output, and -f follows it (press Ctrl+C to stop following). down removes the containers and the project network but keeps named volumes, so the database files survive. docker compose stop only stops the containers and keeps them.

What you should see: the db log ends with a line saying the database system is ready to accept connections. down prints Removed for each container and the network.

Check it worked#

Run docker compose ps after step 2: both services Up. Run docker volume ls after down: a volume ending in _pgdata is still listed. Run docker compose up -d again and the database starts with its old data.

Edge cases and gotchas#

  • down -v deletes your data. The -v flag removes the named volumes declared in the file. Use it only when you want a clean slate.
  • Start order is not readiness. depends_on makes Compose start db before web, but not wait until Postgres accepts connections. Add a healthcheck to the database and depends_on with condition: service_healthy, or make the app retry.
  • Initial settings apply only once. POSTGRES_PASSWORD and similar variables are read only when the volume is empty. Changing them later does nothing to an existing database.
  • Published ports bypass ufw. "8080:80" listens on all interfaces, and Docker’s own firewall rules skip ufw. Write "127.0.0.1:8080:80" if only a local reverse proxy should connect.
  • Port conflicts. If host port 8080 is taken, up fails with a message that the port is already allocated. Change the left number.
  • Same folder name, same project. Two copies of a project in folders with the same name share a project name. Set it explicitly with docker compose -p myapp up -d or a top-level name: key.
  • Old and new commands differ. docker-compose (with a hyphen) is the legacy tool. If it is missing, use docker compose.

Troubleshooting#

SymptomLikely causeFix
no configuration file provided: not foundYou are not in the folder with compose.yamlcd there or use -f
yaml: line N: found character that cannot start any tokenA tab in the YAMLReplace tabs with spaces
services.web.ports must be a list (or similar)Wrong indentation or a missing dashCompare with the example, then run docker compose config
Bind for 0.0.0.0:8080 failed: port is already allocatedAnother process uses that host portChange the host port or stop the other process
docker: 'compose' is not a docker commandThe compose plugin is not installedInstall the Docker Compose plugin package
App cannot connect to db right after startThe database was not ready yetAdd a healthcheck and service_healthy, or retry in the app
Database data is gone after down-v was used, or the data was not on a volumeMount a named volume on the database data folder
service "db" refers to undefined volume pgdataThe volume is used by a service but not declared under the top-level volumes:Add pgdata: under volumes:
Edits to compose.yaml seem to do nothingThe containers were not recreatedRun docker compose up -d again
Old containers remain after you renamed the folderThe project name changed with the folder, so Compose does not see themdocker compose -p oldname down, or set name: in the file

Real-world scenario#

You run a small internal tool with a web front end and a Postgres database. Until now it started with two docker run commands that live in someone’s shell history. You write the compose.yaml from this lesson, swap nginx for the real image, and commit the file (without the password, which goes in a .env file).

On the server, docker compose up -d brings both services up and docker compose ps shows them Up. A month later you change the image tag and run up -d again: only the web container is replaced, the database keeps its volume and its connections. When a colleague asks how the tool is deployed, you send them the file. For a fuller walkthrough with a real app, see Deploy an app with Docker Compose and the blog guide Deploy a Docker Compose app, self-hosted.

Quick reference#

TaskCommand
Start everything in the backgrounddocker compose up -d
List services and statedocker compose ps
Follow logs of one servicedocker compose logs -f web
Stop but keep containersdocker compose stop
Remove containers and network, keep volumesdocker compose down
Remove containers, network and volumes (data loss)docker compose down -v
Print the resolved filedocker compose config

Security and safety notes#

  • docker compose down -v and docker volume rm delete data for good. Back up first.
  • Do not commit real passwords in compose.yaml. See Docker Compose environment variables for .env files.

Next#

Make the data last on purpose with Docker volumes and persistent data.

Try it: Start a web server and a database

Bring up the two services from compose.yaml, check them, read the database log and clean up.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda Play with Docker

Check what you learned4 questions
1What does docker compose down do to the named volume pgdata by default?
2In the example file, what does the line 8080:80 under ports do?
3Which command starts every service in the file in the background?
4You edit POSTGRES_PASSWORD in compose.yaml but the database keeps the old password. Why?

Frequently asked questions

What is the difference between docker-compose and docker compose?

docker-compose is the older standalone program. docker compose is the current plugin that ships with Docker Engine and uses the same file format.

Does depends_on wait until the database is ready?

Not by default. It only controls start order. To wait for readiness, give the database a healthcheck and use depends_on with condition service_healthy.

I changed POSTGRES_PASSWORD but the old password still works. Why?

The Postgres image only reads that variable when it first creates an empty data directory. With an existing volume the old password stays until you change it inside the database.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios