2.2. Docker Compose

Docker Compose Docker Compose

In this lab, you start PostgreSQL on your machine with Docker Compose and keep its data in a volume.

Step 1: Create a Compose File

Create a directory for the files of this lab and change into it:

mkdir -p ~/labs/2.2
cd ~/labs/2.2

Create the file compose.yaml in ~/labs/2.2 with the following content:

name: basics

services:
  postgres:
    image: postgres:18
    environment:
      POSTGRES_USER: messages
      POSTGRES_PASSWORD: s3cr3t
      POSTGRES_DB: messages
    ports:
      - "127.0.0.1:5432:5432"
    volumes:
      - data:/var/lib/postgresql

volumes:
  data:

Explanation

The file describes what you would otherwise pass to docker run as flags. Older projects often call it docker-compose.yml, as in the picture. Compose reads both names.

FieldMeaning
nameName of the project, the prefix of everything that Compose creates
servicesThe containers of the project, here only postgres
imageThe image to run, as in docker run
environmentEnvironment variables: the image creates this user, password and database
portsLike -p. With 127.0.0.1, only your machine can reach the database
volumesStorage named data, mounted where PostgreSQL 18 keeps its files

Step 2: Start PostgreSQL

Start everything in the file. The command keeps running and shows the output of the container. The first start downloads the PostgreSQL image (more than 100 MB), which takes 10 seconds or longer, depending on your connection:

docker compose up
...
postgres-1  | PostgreSQL init process complete; ready for start up.
...
postgres-1  | 2026-11-22 18:02:57.333 UTC [1] LOG:  database system is ready to accept connections

If you don’t see these two lines yet, wait a moment. Leave this terminal open and don’t type in it: it’s your first terminal for the rest of the lab.

Port 5432 is already in use

Change the port to "127.0.0.1:15432:5432" in compose.yaml and repeat docker compose up.

Open a second terminal (on Windows, a WSL terminal again), change into the directory of the lab and check the state of the project:

cd ~/labs/2.2
docker compose ps
NAME                IMAGE         COMMAND                   SERVICE    CREATED         STATUS         PORTS
basics-postgres-1   postgres:18   "docker-entrypoint.s..."  postgres   5 seconds ago   Up 4 seconds   127.0.0.1:5432->5432/tcp

Explanation

docker compose reads compose.yaml in the current directory, so run its commands in ~/labs/2.2. up created a network, the volume and the container, and then showed what the container prints. At its first start, PostgreSQL set up the empty volume with your user and database. Programs on your machine, e.g. the database tool of your IDE, reach it at localhost:5432 (or the port you chose).

Option: run in the background with -d

docker compose up -d starts the containers in the background. For local development and in this lab, stay in the foreground, so you see their output.


Step 3: Store a Row

In the second terminal, create a table with psql, the command-line client of PostgreSQL in the container:

docker compose exec postgres psql -U messages -c "create table notes (text text)"
CREATE TABLE

If psql can’t connect, wait a moment and repeat the command. Insert a row:

docker compose exec postgres psql -U messages -c "insert into notes values ('Hello Compose')"
INSERT 0 1

Read it:

docker compose exec postgres psql -U messages -c "select * from notes"
     text
---------------
 Hello Compose
(1 row)

Explanation

docker compose exec <service> <command> runs a command in the running container of a service, so you don’t need psql on your machine. -U sets the user and -c the SQL statement. Without a database name, psql uses the database with the name of the user, here messages. It doesn’t ask for the password, because the image trusts connections from inside the same container.


Step 4: Recreate the Container

Stop PostgreSQL: press Ctrl+C in the first terminal. Compose stops the container and the prompt returns:

...
postgres-1 exited with code 0

In the same terminal, remove the container and the network of the project:

docker compose down

Start the project again in the first terminal, in the foreground:

docker compose up
...
postgres-1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
...
postgres-1  | 2026-11-22 18:03:07.020 UTC [1] LOG:  database system is ready to accept connections

In the second terminal, read all rows of the table notes with psql:

docker compose exec postgres psql -U messages -c "select * from notes"
     text
---------------
 Hello Compose
(1 row)

If psql can’t connect yet, wait a moment and repeat the command.

Explanation

Ctrl+C only stopped the container. down removed it, and up created a new one. The row is still there, because PostgreSQL stores its files in the volume basics_data, which exists independently of the container: the log says that it found a database and skipped the initialization. down doesn’t delete volumes.


Optional Tasks

Finished early? Try these tasks. The following labs don’t depend on them. Each task lists the commands you need. Open the solution if you get stuck.

Task 1: Call by Name

Leave PostgreSQL running in the first terminal. In the second terminal, read the table from a temporary container that connects over the network. Use the name of the service as the host.

CommandEffect
docker compose run --rm -e <name>=<value> <service> <command>Runs a command in a new container of the service
psql -h <host>Connects to PostgreSQL on another host
psql -P pager=offPrints the result directly, so psql can’t get stuck in a pager
PGPASSWORDEnvironment variable with the password for psql
Solution

In the second terminal, start the temporary container with psql as its command:

cd ~/labs/2.2
docker compose run --rm -e PGPASSWORD=s3cr3t postgres psql -P pager=off -h postgres -U messages -c "select * from notes"
     text
---------------
 Hello Compose
(1 row)

Compose puts the containers of a project into one network, where they find each other by the names of their services. Over the network, PostgreSQL asks for the password. The first terminal may show the output of the temporary container as well, because it belongs to the same project.

Task 2: Out of the File

Move the password out of compose.yaml into a file .env. In the second terminal, check that Compose still finds it, while PostgreSQL keeps running in the first.

CommandEffect
${NAME}In a Compose file: the value of NAME, e.g. from .env
docker compose configPrints the Compose file with all values filled in
Solution

Create the file .env in ~/labs/2.2:

POSTGRES_PASSWORD=s3cr3t

Replace the password in compose.yaml:

      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}

Print the resulting configuration in the second terminal:

cd ~/labs/2.2
docker compose config
...
    environment:
      POSTGRES_DB: messages
      POSTGRES_PASSWORD: s3cr3t
      POSTGRES_USER: messages
...

You can now commit compose.yaml to Git without the password. List .env in .gitignore, so it stays out.

Task 3: Clean Slate

Start over with an empty database: restart PostgreSQL in the first terminal, then check it in the second.

CommandEffect
docker compose down -vRemoves the volumes of the project as well
Solution

Press Ctrl+C in the first terminal and wait for the prompt. In the same terminal, remove the project with its volume and start it again:

cd ~/labs/2.2
docker compose down -v
docker compose up

Wait until the log shows PostgreSQL init process complete and then ready to accept connections. In the second terminal, look for the table:

cd ~/labs/2.2
docker compose exec postgres psql -U messages -c "select * from notes"
ERROR:  relation "notes" does not exist
LINE 1: select * from notes
                      ^

Without the old volume, PostgreSQL started with an empty database. The first terminal logs the same error. If psql can’t connect instead, wait a moment and repeat the command.


Clean Up

Press Ctrl+C in the first terminal and wait for the prompt. In the same terminal, remove the container, the network and the volume. -v removes the volumes as well:

cd ~/labs/2.2
docker compose down -v

The files and the PostgreSQL image stay on your machine.


Complete files

~/labs/2.2/compose.yaml:

name: basics

services:
  postgres:
    image: postgres:18
    environment:
      POSTGRES_USER: messages
      POSTGRES_PASSWORD: s3cr3t
      POSTGRES_DB: messages
    ports:
      - "127.0.0.1:5432:5432"
    volumes:
      - data:/var/lib/postgresql

volumes:
  data: