Skip to content
KALANBLON
Show contents

Chapter 6 of 7 · 25 min

Project: containerising a web application

By the end of this chapter, you'll be able to

  • Containerise an application and its database end to end
  • Organise the files of a Docker project: Dockerfile, .dockerignore, compose.yaml, .env.example
  • Check that it works and that data persists
  • Prepare the application for a server: restarts, secrets, ports

The starting project

books/
├── app.py              ← the API (Flask), reads DATABASE_URL
├── requirements.txt    ← flask==3.1.*, psycopg[binary]==3.2.*
└── schema.sql          ← creates the books table

You will add four files, without touching the application's code:

├── Dockerfile
├── .dockerignore
├── compose.yaml
└── .env.example

We check that the API answers and that data survives a restart.

Step 5 of 5
Text description of the animation
  1. A reduced Python image, dependencies cached, non-root user.
  2. The database exposes no port; the API waits until it is ready.
  3. Each member copies .env.example to .env and chooses their password.
  4. Build, network, volume, database, API: everything is created in the right order.
  5. We check that the API answers and that data survives a restart.

Step 1: the API's image

FROM python:3.13-slim
WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
RUN useradd --create-home appuser
USER appuser

EXPOSE 5000
CMD ["python", "-m", "flask", "--app", "app", "run", "--host", "0.0.0.0", "--port", "5000"]
# .dockerignore
.git
.env
__pycache__/
venv/

Flask's development server is enough for this school project. In real production, it is replaced by a server made for it, such as Gunicorn: CMD ["gunicorn", "--bind", "0.0.0.0:5000", "app:app"].

Step 2: the services

services:
  api:
    build: .
    image: books-api:1.0
    ports:
      - "5000:5000"
    environment:
      DATABASE_URL: postgresql://books:${DB_PASSWORD}@db:5432/books
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: books
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: books
    volumes:
      - data:/var/lib/postgresql/data
      - ./schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U books"]
      interval: 5s
      retries: 10
    restart: unless-stopped

volumes:
  data:

Three details matter:

  • ./schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro: the postgres image runs the scripts in this folder on first start-up, when the volume is empty. The table is thus created automatically;
  • restart: unless-stopped: if a container stops on an error, or the server reboots, Docker restarts it on its own, unless you stopped it on purpose;
  • build and image together: Compose builds the image and gives it that name.

Step 3: the secrets

# .env.example — committed, with no real value
DB_PASSWORD=choose-a-long-password

Each team member copies this file to .env (ignored by Git) and puts their own password in it.

Steps 4 and 5: start and check

cp .env.example .env            # then change the password
docker compose up -d --build
docker compose ps               # api: running · db: healthy
curl http://localhost:5000/books

Then the most important test, persistence: add a book, stop everything with docker compose down (without -v), start again with docker compose up -d, and check that the book is still there.

Your turn

Worked exercise

Project: your containerisation checklist

Carry out the project on the application of your choice (this chapter's, or the Node.js API from the APIs course), then check each point of this list and write down the result:

  1. docker compose up -d --build starts everything, with no other step than copying the .env.
  2. The database has no published port.
  3. Data survives docker compose down then up.
  4. No password appears in compose.yaml, the Dockerfile or the image.
  5. The API runs as a non-root user.
  6. Changing a line of code does not reinstall the dependencies on rebuild.
Hint 1
For point 4, docker compose config shows the substituted values: it is normal that it prints the password, since it reads your .env. Check the committed files and docker history books-api:1.0 instead.
Hint 2
For point 5, docker compose exec api whoami prints the process's user.
Show the solution and common mistakes

Here are the checks and the expected results:

1. docker compose up -d --build        → api Started, db Healthy
2. docker compose ps                    → db: PORTS column shows 5432/tcp, not published
3. down, then up, then curl /books      → the added book is still there
4. grep -r "DB_PASSWORD=" compose.yaml Dockerfile
                                        → no result (only ${DB_PASSWORD})
   docker history books-api:1.0         → no layer contains .env
5. docker compose exec api whoami       → appuser
6. change app.py, then docker compose build
                                        → "CACHED" on the pip install step

Common mistakes:

  • Using docker compose down -v out of habit: -v erases the volumes, so all the data.
  • Publishing the database's port "to be able to look at it": use docker compose exec db psql -U books instead.
  • Putting the .env in the Git repository "because it's simpler for the team": the password is then visible to anyone with access to the repository, forever in the history.

Summary

  1. 1A containerised project adds a Dockerfile, a .dockerignore, a compose.yaml and a .env.example.
  2. 2The database exposes no port; only the API is published.
  3. 3restart: unless-stopped restarts containers after an error or a server reboot.
  4. 4postgres initialisation scripts only run on first start-up; the schema then evolves through migrations.
  5. 5Check the result: one-command start-up, persistence, no secrets, non-root user.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.