DEV Community

Cover image for Docker for Everyday Development, One App, One Database, One Compose File
David Au Yeung
David Au Yeung

Posted on

Docker for Everyday Development, One App, One Database, One Compose File

Introduction

Getting an application to run is exciting.

Then the practical questions arrive.

How do I stop it?

How do I start it again tomorrow?

If I restart the application, will my saved records disappear?

And if something goes wrong, where do I look?

These questions are not glamorous, but they are the difference between running a demo once and actually understanding your setup.

In this article, we will install Docker Desktop on Windows, build a small appraisal application, connect it to PostgreSQL, and learn how to maintain it using PowerShell.

The example is complete and standalone. You do not need any previous project files.

The goal is simple:

Understand what is running, know where the data lives, and know how to stop and restart the application without guessing.

What Is Docker?

Docker is a tool for packaging and running applications in containers.

Instead of manually installing Python, configuring a database, and hoping every setting matches someone else’s computer, we describe the software environment and let Docker create it.

There are a few terms worth knowing.

  1. Image, a prepared package containing an application and the software it needs.

  2. Container, a running instance of an image.

  3. Dockerfile, the instructions Docker uses to build an image.

  4. Volume, storage that exists separately from a container.

  5. Docker Desktop, the Windows application that provides and manages the Docker environment.

The important distinction is between the application and its data.

We should be able to replace an application container without replacing the database records.

That is why we will store PostgreSQL’s data in a volume.

On Windows, this guide uses Linux containers through WSL 2. You will still run the commands from PowerShell.

What Is Docker Compose?

A useful application often needs more than one program.

Our example needs:

  1. A web application.
  2. A PostgreSQL database.

Docker Compose lets us describe both in one configuration file called compose.yaml.

That file tells Docker:

  1. Which services to run.
  2. How to build or download them.
  3. How they connect.
  4. Which addresses are available from Windows.
  5. Where persistent data is stored.
  6. How to check whether the services are ready.

Instead of starting each part manually, Compose manages them together.

Docker Desktop includes Docker Compose, so we do not need a separate Compose download. Docker’s Compose guide

What We Are Building

We will create a small local appraisal application.

It will let us enter a fictional employee name, choose a score, write a comment, and save the record.

The arrangement will look like this:

Browser on Windows
    ↓
Web application, http://127.0.0.1:8000
    ↓
PostgreSQL database
    ↓
Persistent Docker volume
Enter fullscreen mode Exit fullscreen mode

We will also optionally connect pgAdmin, a graphical database management tool.

The two Compose services will be named:

  1. app, the web application.
  2. db, the PostgreSQL database.

For this article, we will use a dedicated project folder and volume:

Project folder: docker-appraisal-demo
Database:       appraisal
Application user: appraisal_app
Data volume:    appraisal_demo_pgdata
Enter fullscreen mode Exit fullscreen mode

These demo names help keep the tutorial separate from an existing application.

This is a local learning example, not a production HR system. Use fictional records only. It does not include user accounts, access controls, or the other protections needed for real employee information.

Before You Start

You will need:

  1. A Windows 11 version supported by the current Docker Desktop release.
  2. An Intel or AMD computer for the installation path described here.
  3. Hardware virtualization enabled.
  4. At least 8 GB of RAM, with more being helpful.
  5. Several gigabytes of free disk space.
  6. An internet connection for the initial downloads.
  7. Windows PowerShell 5.1 or PowerShell 7.

Check the official Windows installation requirements before installing. If you use an Arm based computer, follow Docker’s matching installation instructions.

You do not need to install Python or PostgreSQL directly on Windows for this demo.

All terminal commands below are for PowerShell.

Copy the code exactly. Punctuation inside commands and configuration files is required syntax.

Step 1, Prepare WSL 2

WSL means Windows Subsystem for Linux.

For our purposes, it gives Docker the Linux environment needed to run these containers.

Open the Start menu, search for PowerShell, and choose Run as administrator.

If WSL is not installed, run:

wsl --install --no-distribution
Enter fullscreen mode Exit fullscreen mode

This installs WSL without adding a separate Ubuntu installation. Docker Desktop does not require you to manage your own Linux distribution for this tutorial.

Restart Windows after installation.

Then open PowerShell as administrator again and run:

wsl --update
wsl --set-default-version 2
wsl --version
Enter fullscreen mode Exit fullscreen mode

If WSL was already installed, you can start with these update and verification commands.

If Windows reports a virtualization problem, open Task Manager, select Performance, then CPU, and check the virtualization status. Enabling it may require a BIOS or UEFI setting, or help from your IT administrator.

Microsoft provides the WSL installation guide and WSL command reference.

Step 2, Download and Install Docker Desktop

Open the official download page:

Download Docker Desktop for Windows

Then:

  1. Choose the Windows installer for your processor, normally x86_64 for Intel or AMD.
  2. Run the installer.
  3. Choose the WSL 2 backend when the installer offers that choice.
  4. Complete the installation.
  5. Restart Windows if requested.
  6. Open Docker Desktop from the Start menu.
  7. Complete its initial setup and wait for the Docker engine to become ready.

If the relevant setting is available, check Settings, General, Use WSL 2 based engine. Docker may already enable this automatically.

We are using Linux containers, not Windows containers.

Docker Desktop is free for personal learning and other qualifying uses. Some workplace uses require a paid subscription, so check the terms before installing it on a company computer.

For the remaining project steps, open a normal PowerShell window, not an administrator window.

Step 3, Confirm That Docker Works

Run:

docker version
docker compose version
docker info --format '{{.OSType}}'
Enter fullscreen mode Exit fullscreen mode

The first command should show both client and server information.

The second confirms that Compose is available.

The third should return:

linux
Enter fullscreen mode Exit fullscreen mode

Now run Docker’s small test container:

docker run --rm hello-world
Enter fullscreen mode Exit fullscreen mode

You should see a message beginning with:

Hello from Docker!
Enter fullscreen mode Exit fullscreen mode

The --rm option removes this temporary test container after it finishes. It does not remove your other containers or database volumes.

If these commands fail, stop here and resolve the Docker installation problem before creating the application.

Step 4, Create the Project Folder

We will create the project inside your Windows user folder.

Run the initial setup steps once, in the same PowerShell window. Several steps use the small file writing helper defined below.

$ErrorActionPreference = "Stop"

$project = Join-Path $env:USERPROFILE "docker-appraisal-demo"

if (Test-Path -LiteralPath $project) {
    throw "The project folder already exists. Do not overwrite an existing project with these setup steps."
}

New-Item -ItemType Directory -Path $project | Out-Null
Set-Location $project

New-Item -ItemType Directory -Path "templates", "db-init", "backups" | Out-Null

function Write-ProjectFile {
    param(
        [string]$Path,
        [string]$Text
    )

    $fullPath = Join-Path (Get-Location).Path $Path
    $content = $Text.Replace("`r`n", "`n") + "`n"
    $encoding = [System.Text.UTF8Encoding]::new($false)

    [System.IO.File]::WriteAllText($fullPath, $content, $encoding)
}
Enter fullscreen mode Exit fullscreen mode

This creates the folders and defines a helper that saves text files in a format suitable for the Linux containers.

Windows and Linux can use different line endings. The helper avoids a common problem where a Linux startup script fails because it was saved in an unexpected Windows text format.

If you reopen PowerShell partway through setup, return to the project folder and redefine the helper before continuing with file creation.

The maintenance commands later in the article do not need this helper.

Step 5, Create Private Settings

We need two database passwords.

One belongs to the PostgreSQL administrator.

The other belongs to the application account, which will have fewer permissions.

Rather than publishing a shared sample password, we will generate fresh ones.

function New-DemoPassword {
    [byte[]]$bytes = New-Object byte[] 32
    $generator = [System.Security.Cryptography.RandomNumberGenerator]::Create()

    try {
        $generator.GetBytes($bytes)
    }
    finally {
        $generator.Dispose()
    }

    return ([System.BitConverter]::ToString($bytes)).Replace("-", "").ToLowerInvariant()
}

if (Test-Path -LiteralPath ".env") {
    throw ".env already exists. Do not regenerate passwords for an existing database."
}

$postgresPassword = New-DemoPassword
$appPassword = New-DemoPassword

Write-ProjectFile ".env" "POSTGRES_PASSWORD=$postgresPassword`nAPP_DB_PASSWORD=$appPassword"
Enter fullscreen mode Exit fullscreen mode

The .env file now contains the private settings Compose will use.

It is a normal text file, not an encrypted password vault. Keep it private.

We will also create a Git ignore file:

Write-ProjectFile ".gitignore" @'
.env
backups/
__pycache__/
*.pyc
'@
Enter fullscreen mode Exit fullscreen mode

This helps prevent accidental commits of passwords and backups if you later use Git.

Do not rerun the password generation step after the database has been initialized. Changing this file does not automatically change passwords already stored inside PostgreSQL.

Step 6, Prepare the Database

PostgreSQL needs a table to store our records and an application account that can use it.

The following command creates the database initialization script:

Write-ProjectFile "db-init\01-create-app.sh" @'
#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" --set=app_password="$APP_DB_PASSWORD" <<'SQL'
CREATE ROLE appraisal_app LOGIN PASSWORD :'app_password';

CREATE TABLE public.appraisals (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    employee_name varchar(100) NOT NULL,
    score smallint NOT NULL CHECK (score BETWEEN 1 AND 5),
    comments varchar(2000) NOT NULL DEFAULT '',
    created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
);

GRANT CONNECT ON DATABASE appraisal TO appraisal_app;
GRANT USAGE ON SCHEMA public TO appraisal_app;
GRANT SELECT, INSERT ON TABLE public.appraisals TO appraisal_app;
GRANT USAGE, SELECT ON SEQUENCE public.appraisals_id_seq TO appraisal_app;
SQL
'@
Enter fullscreen mode Exit fullscreen mode

Here is what it does:

  1. Creates the appraisal_app login.
  2. Creates the appraisals table.
  3. Gives each record an automatically generated ID.
  4. Restricts scores to values from 1 through 5.
  5. Lets the application read and add records.

The application account is not a database administrator. It does not receive permission to delete tables or manage database users.

One important detail:

PostgreSQL runs these initialization scripts only when it starts with an empty data directory.

Editing this script later will not update an existing database. Database changes after initial setup need separate SQL changes or a migration process.

This behavior is documented in the official PostgreSQL Docker image instructions.

Step 7, Create the Small Web Application

We will use three Python packages:

  1. Flask, which handles the web page and form.
  2. Psycopg, which connects Python to PostgreSQL.
  3. Gunicorn, which runs the web application inside the Linux container.

Docker will install them inside the image.

Create the dependency file

Write-ProjectFile "requirements.txt" @'
Flask>=3.1,<4
psycopg[binary]>=3.2,<4
gunicorn>=23,<24
'@
Enter fullscreen mode Exit fullscreen mode

These are version ranges for the teaching example. A maintained production project should lock and test its exact dependency versions.

Create the application code

Write-ProjectFile "app.py" @'
import psycopg
from flask import Flask, redirect, render_template, request, url_for
from psycopg.rows import dict_row

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 32 * 1024


def open_db():
    return psycopg.connect(
        connect_timeout=5,
        row_factory=dict_row,
    )


@app.get("/health")
def health():
    try:
        with open_db() as conn:
            row = conn.execute(
                "SELECT current_user AS db_user"
            ).fetchone()

            conn.execute(
                "SELECT 1 FROM public.appraisals LIMIT 1"
            ).fetchone()

        return {
            "database": "connected",
            "db_user": row["db_user"],
            "status": "ok",
        }

    except psycopg.Error:
        app.logger.exception("Database health check failed")

        return {
            "database": "unavailable",
            "status": "error",
        }, 503


@app.route("/", methods=["GET", "POST"])
def index():
    error = None

    if request.method == "POST":
        employee_name = request.form.get("employee_name", "").strip()
        comments = request.form.get("comments", "").strip()

        try:
            score = int(request.form.get("score", ""))
        except ValueError:
            score = 0

        if not 1 <= len(employee_name) <= 100:
            error = "Enter an employee name with 1 to 100 characters."
        elif not 1 <= score <= 5:
            error = "Choose a score from 1 to 5."
        elif len(comments) > 2000:
            error = "Keep comments within 2000 characters."
        else:
            try:
                with open_db() as conn:
                    conn.execute(
                        """
                        INSERT INTO public.appraisals
                            (employee_name, score, comments)
                        VALUES (%s, %s, %s)
                        """,
                        (employee_name, score, comments),
                    )

            except psycopg.Error:
                app.logger.exception("Could not save appraisal")
                return "Could not save the record. Check the app logs.", 503

            return redirect(url_for("index"), code=303)

    try:
        with open_db() as conn:
            records = conn.execute(
                """
                SELECT id, employee_name, score, comments, created_at
                FROM public.appraisals
                ORDER BY id DESC
                LIMIT 100
                """
            ).fetchall()

    except psycopg.Error:
        app.logger.exception("Could not load appraisals")
        return "The database is unavailable. Check the app logs.", 503

    return render_template(
        "index.html",
        records=records,
        error=error,
    ), (400 if error else 200)
'@
Enter fullscreen mode Exit fullscreen mode

The connection settings will come from environment variables supplied by Compose.

The application checks input before saving, and it passes values to PostgreSQL separately from the SQL statement. That avoids treating a name or comment as executable SQL.

The /health address checks that the application can connect using its own account and read the table.

Create the browser page

Write-ProjectFile "templates\index.html" @'
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Employee Appraisal Demo</title>
    <style>
        body {
            margin: 0;
            background: #eef3f8;
            color: #203247;
            font-family: "Segoe UI", Arial, sans-serif;
        }
        main {
            max-width: 1000px;
            margin: 32px auto;
            padding: 0 20px;
        }
        section {
            background: white;
            padding: 24px;
            margin: 20px 0;
            border-radius: 12px;
            box-shadow: 0 4px 16px #0000000d;
            overflow-x: auto;
        }
        label {
            display: block;
            margin: 16px 0 6px;
            font-weight: 600;
        }
        input, select, textarea {
            width: 100%;
            padding: 10px;
            box-sizing: border-box;
            border: 1px solid #b8c7d6;
            border-radius: 6px;
            font: inherit;
        }
        button {
            margin-top: 18px;
            padding: 12px 20px;
            border: 0;
            border-radius: 6px;
            background: #156082;
            color: white;
            font: inherit;
            cursor: pointer;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px;
            border-bottom: 1px solid #dce5ee;
            text-align: left;
            vertical-align: top;
        }
        td {
            overflow-wrap: anywhere;
        }
        .error {
            color: #a31515;
            font-weight: 600;
        }
    </style>
</head>
<body>
<main>
    <h1>Employee Appraisal Demo</h1>
    <p>A local Docker application with PostgreSQL storage.</p>
    <p>Use fictional records only.</p>

    <section>
        <h2>Add an appraisal</h2>

        {% if error %}
        <p class="error">{{ error }}</p>
        {% endif %}

        <form method="post">
            <label for="employee_name">Employee name</label>
            <input
                id="employee_name"
                name="employee_name"
                maxlength="100"
                required
            >

            <label for="score">Score, 1 is lowest and 5 is highest</label>
            <select id="score" name="score">
                {% for score in range(1, 6) %}
                <option value="{{ score }}">{{ score }}</option>
                {% endfor %}
            </select>

            <label for="comments">Comments</label>
            <textarea
                id="comments"
                name="comments"
                maxlength="2000"
                rows="4"
            ></textarea>

            <button type="submit">Save appraisal</button>
        </form>
    </section>

    <section>
        <h2>Saved appraisals</h2>
        <p>The most recent 100 records are shown below.</p>

        {% if records %}
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Employee</th>
                    <th>Score</th>
                    <th>Comments</th>
                    <th>Created</th>
                </tr>
            </thead>
            <tbody>
                {% for row in records %}
                <tr>
                    <td>{{ row.id }}</td>
                    <td>{{ row.employee_name }}</td>
                    <td>{{ row.score }}</td>
                    <td>{{ row.comments }}</td>
                    <td>{{ row.created_at }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <p>No records yet. Add your first example above.</p>
        {% endif %}
    </section>

    <p><a href="/health">Check the database connection</a></p>
</main>
</body>
</html>
'@
Enter fullscreen mode Exit fullscreen mode

The page displays only the latest 100 records, but older records remain in the database.

Flask’s HTML templates escape the displayed values, so a comment is shown as text rather than treated as page markup.

Step 8, Tell Docker How to Build the App

Create the Dockerfile:

Write-ProjectFile "Dockerfile" @'
FROM python:3.12-slim-bookworm

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

WORKDIR /app

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

RUN useradd --create-home --uid 10001 appuser

COPY app.py .
COPY templates ./templates

USER appuser

EXPOSE 8000

CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "--access-logfile", "-", "--error-logfile", "-", "app:app"]
'@
Enter fullscreen mode Exit fullscreen mode

In plain language, this says:

  1. Start with an image that already contains Python.
  2. Create a working folder inside the image.
  3. Install the required packages.
  4. Copy in our application files.
  5. Run the application using an ordinary container user rather than root.
  6. Start the web server on port 8000 inside the container.

EXPOSE 8000 documents the internal port. The Compose configuration will decide how Windows can reach it.

Now create .dockerignore:

Write-ProjectFile ".dockerignore" @'
.env
.git
backups/
__pycache__/
*.pyc
db-init/
compose.yaml
'@
Enter fullscreen mode Exit fullscreen mode

This keeps unnecessary files, including our private settings and backups, out of the build context sent to Docker.

The database initialization folder is mounted separately at runtime, so it does not belong in the application image.

Step 9, Describe Both Services with Compose

Create compose.yaml:

Write-ProjectFile "compose.yaml" @'
name: appraisal-demo

services:
  db:
    image: postgres:17-bookworm
    restart: unless-stopped
    stop_grace_period: 1m

    environment:
      POSTGRES_DB: appraisal
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
      APP_DB_PASSWORD: ${APP_DB_PASSWORD:?Set APP_DB_PASSWORD in .env}

    ports:
      - "127.0.0.1:5433:5432"

    volumes:
      - pgdata:/var/lib/postgresql/data
      - ./db-init:/docker-entrypoint-initdb.d:ro

    healthcheck:
      test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "postgres", "-d", "appraisal"]
      interval: 5s
      timeout: 5s
      retries: 12
      start_period: 20s

    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

  app:
    build: .
    restart: unless-stopped
    stop_grace_period: 30s

    environment:
      PGHOST: db
      PGPORT: "5432"
      PGDATABASE: appraisal
      PGUSER: appraisal_app
      PGPASSWORD: ${APP_DB_PASSWORD:?Set APP_DB_PASSWORD in .env}

    ports:
      - "127.0.0.1:8000:8000"

    depends_on:
      db:
        condition: service_healthy

    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3).read()"]
      interval: 10s
      timeout: 5s
      retries: 6
      start_period: 20s

    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

volumes:
  pgdata:
    external: true
    name: appraisal_demo_pgdata
'@
Enter fullscreen mode Exit fullscreen mode

There is a lot in this file, but the main ideas are straightforward.

The service names are also connection names

The app connects to the database using:

Host: db
Port: 5432
Enter fullscreen mode Exit fullscreen mode

Compose supplies the network and makes the name db available to the app.

Inside the app container, localhost would mean the app container itself, not the database.

Windows uses the published ports

The website will be available at:

http://127.0.0.1:8000/
Enter fullscreen mode Exit fullscreen mode

A database tool running directly on Windows will connect using:

Host: 127.0.0.1
Port: 5433
Enter fullscreen mode Exit fullscreen mode

The database mapping means Windows port 5433 forwards to PostgreSQL’s internal port 5432.

Binding to 127.0.0.1 limits these published ports to the local computer. It does not add authentication to the web application.

The format is HOST_IP:HOST_PORT:CONTAINER_PORT:

Part Meaning
127.0.0.1 Bind only to your computer’s localhost
5433 Outside port on your computer
5432 Inside port in the container

The app waits for the database

The depends_on health condition delays the application’s initial start until PostgreSQL is ready.

The app then has its own health check, which verifies its actual database access.

A health check reports a problem. It does not, by itself, automatically restart an unhealthy container.

Logs have size limits

The logging settings rotate container output rather than allowing one log file to grow indefinitely.

These limits apply to container logs, not to database records or backups.

The database uses a separate volume

The database records live in:

appraisal_demo_pgdata
Enter fullscreen mode Exit fullscreen mode

We mark the volume as external so its lifecycle is managed separately from this Compose project.

External does not mean offsite. The volume still lives within Docker Desktop’s storage on this computer.

Compose will expect the volume to exist, so we will create it next. Docker’s volume configuration documentation

We deliberately choose PostgreSQL 17

This example uses the PostgreSQL 17 image and its matching data directory.

Do not casually change the major version to a newer number. PostgreSQL major upgrades require planning, and newer images can also use different storage layouts.

Step 10, Create Storage and Start the Application

First, make sure the tutorial volume does not already exist.

This check helps prevent us from accidentally reusing an older database with different settings.

$existingVolumes = @(docker volume ls --format '{{.Name}}')

if ($LASTEXITCODE -ne 0) {
    throw "Could not list Docker volumes. Check that Docker Desktop is running."
}

if ($existingVolumes -contains "appraisal_demo_pgdata") {
    throw "The tutorial volume already exists. Do not initialize over existing data."
}

docker volume create appraisal_demo_pgdata

if ($LASTEXITCODE -ne 0) {
    throw "Could not create the database volume."
}
Enter fullscreen mode Exit fullscreen mode

This is an initial setup step, not a command to repeat every time you start the app.

Now validate the Compose configuration:

docker compose config --quiet

if ($LASTEXITCODE -ne 0) {
    throw "The Compose configuration is invalid. Fix it before continuing."
}
Enter fullscreen mode Exit fullscreen mode

The quiet option validates the file without printing the resolved configuration, which could include passwords.

Start the project:

docker compose up -d --build --wait --wait-timeout 180

if ($LASTEXITCODE -ne 0) {
    throw "Startup failed. Check the logs with: docker compose logs --tail=100 db app"
}
Enter fullscreen mode Exit fullscreen mode

Here is what the options mean:

  1. up, create or update the services and start them.
  2. -d, keep them running in the background.
  3. --build, build the application image before starting.
  4. --wait, wait for the services to become running or healthy.
  5. --wait-timeout 180, allow up to 180 seconds for that readiness wait.

The first build may take longer because Docker needs to download images and packages. The readiness timeout is not a total limit on all downloads and build work.

Docker documents this behavior in the docker compose up reference.

Check the containers:

docker compose ps
Enter fullscreen mode Exit fullscreen mode

Both services should eventually show healthy.

Now check the application’s database connection:

Invoke-RestMethod -Uri "http://127.0.0.1:8000/health" |
    Select-Object database, db_user, status |
    Format-List
Enter fullscreen mode Exit fullscreen mode

Expected values:

database : connected
db_user  : appraisal_app
status   : ok
Enter fullscreen mode Exit fullscreen mode

Notice the database user.

The app is connected as appraisal_app, not as the PostgreSQL administrator.

Step 11, Save Your First Record

Open the website:

Start-Process "http://127.0.0.1:8000/"
Enter fullscreen mode Exit fullscreen mode

Enter a fictional example:

Employee name: Jamie Demo
Score:         4
Comments:      Completed the monthly reporting task.
Enter fullscreen mode Exit fullscreen mode

Select Save appraisal.

The record should appear in the table.

Refresh the page. It should still be there because it is stored in PostgreSQL, not just in the browser.

You can also inspect the table directly from PowerShell:

docker compose exec -T db psql -U postgres -d appraisal -c "SELECT id, employee_name, score, comments FROM public.appraisals ORDER BY id;"
Enter fullscreen mode Exit fullscreen mode

This runs PostgreSQL’s command line tool inside the database container.

You do not need to install that tool on Windows.

Step 12, View the Same Data in pgAdmin, Optional

pgAdmin provides a graphical way to inspect PostgreSQL.

It is a database management tool, not a second database server.

Download the Windows installer from:

Download pgAdmin for Windows

Install it and open pgAdmin.

If it asks for a master password, that protects saved connection passwords in pgAdmin. It is separate from the database password.

Register a server using these settings:

Display name:         Docker Appraisal Demo
Host name/address:    127.0.0.1
Port:                 5433
Maintenance database: appraisal
Username:             appraisal_app
Password:             the APP_DB_PASSWORD value from .env
Enter fullscreen mode Exit fullscreen mode

To view your local settings:

notepad .\.env
Enter fullscreen mode Exit fullscreen mode

Copy the value after APP_DB_PASSWORD= into pgAdmin’s password field.

Do not include the setting name or the equals sign.

Do not include passwords or the contents of .env in screenshots.

After connecting, select the appraisal database and open its Query Tool.

Run:

SELECT
    id,
    employee_name,
    score,
    comments,
    created_at
FROM public.appraisals
ORDER BY id DESC;
Enter fullscreen mode Exit fullscreen mode

You should see the same record that you entered through the website.

Because pgAdmin is running on Windows, it uses 127.0.0.1 and port 5433.

The app container uses db and port 5432.

They are two different routes to the same database.

Step 13, Learn the Daily Start and Stop Commands

The initial setup is complete.

The following sections are a maintenance reference. Choose the command for the action you want, rather than treating every command as one setup script.

Whenever you open a new PowerShell window, return to the project folder:

Set-Location (Join-Path $env:USERPROFILE "docker-appraisal-demo")
Enter fullscreen mode Exit fullscreen mode

Make sure Docker Desktop is running.

Stop only the web application

docker compose stop app
Enter fullscreen mode Exit fullscreen mode

The website stops.

PostgreSQL stays running, so pgAdmin can still connect.

Start only the web application

docker compose up -d --wait app
Enter fullscreen mode Exit fullscreen mode

Compose will also start its database dependency if needed.

Restart only the web application

docker compose restart app
Enter fullscreen mode Exit fullscreen mode

This is useful when the application appears stuck.

It does not rebuild the image or apply changed Compose settings. Docker restart documentation

Stop everything

docker compose stop
Enter fullscreen mode Exit fullscreen mode

Both the application and PostgreSQL stop.

The website and database connection will be unavailable until you start them again.

Start everything

docker compose up -d --wait
Enter fullscreen mode Exit fullscreen mode

Restart everything

docker compose restart
Enter fullscreen mode Exit fullscreen mode

A restart command finishing does not necessarily mean both services are healthy yet. Check their status afterward.

Confirm that the data survives

After saving your sample record, stop the project and start it again:

docker compose stop
docker compose up -d --wait
Enter fullscreen mode Exit fullscreen mode

Refresh the website.

Your record should still be there.

In this setup, stopping or restarting the containers does not delete the saved records. The records live in the persistent database volume.

Step 14, Check Status, Logs, and Resource Usage

When something goes wrong, start with status and logs.

Repeatedly restarting without reading the error usually just repeats the same problem.

Check service status

docker compose ps -a
Enter fullscreen mode Exit fullscreen mode

The -a option includes stopped containers.

Check the database connection

Invoke-RestMethod -Uri "http://127.0.0.1:8000/health"
Enter fullscreen mode Exit fullscreen mode

Read recent application logs

docker compose logs --tail=100 app
Enter fullscreen mode Exit fullscreen mode

Read recent database logs

docker compose logs --tail=100 db
Enter fullscreen mode Exit fullscreen mode

Watch application logs as they happen

docker compose logs -f --tail=50 app
Enter fullscreen mode Exit fullscreen mode

Press Ctrl+C to stop watching.

Because the services were started in the background, this does not stop the application.

Check memory and processor usage

docker stats --no-stream
Enter fullscreen mode Exit fullscreen mode

Check Docker disk usage

docker system df
Enter fullscreen mode Exit fullscreen mode

This reports usage. It does not delete anything.

Avoid treating disk cleanup as a reason to run unfamiliar volume deletion commands.

Step 15, Back Up the Database

A persistent volume is useful, but it is not a backup.

It does not protect you from a failed disk, accidental deletion, or a Docker Desktop factory reset.

For this demo, we will create a database archive and copy it into the project’s backups folder.

Run:

$ErrorActionPreference = "Stop"

Set-Location (Join-Path $env:USERPROFILE "docker-appraisal-demo")

docker compose up -d --wait db

if ($LASTEXITCODE -ne 0) {
    throw "The database is not ready. Backup cancelled."
}

New-Item -ItemType Directory -Force -Path ".\backups" | Out-Null

$stamp = Get-Date -Format "yyyyMMdd_HHmmss"
$containerDump = "/tmp/appraisal_$stamp.dump"
$backupFile = Join-Path (Get-Location).Path "backups\appraisal_$stamp.dump"

docker compose exec -T db pg_dump -U postgres -d appraisal -Fc -f $containerDump

if ($LASTEXITCODE -ne 0) {
    throw "Database dump failed. No successful backup has been confirmed."
}

docker compose cp "db:$containerDump" $backupFile

if ($LASTEXITCODE -ne 0) {
    throw "The copy failed. The dump remains inside the database container."
}

docker compose exec -T db rm -f $containerDump

if ($LASTEXITCODE -ne 0) {
    Write-Warning "The backup was copied, but the temporary container file was not removed."
}

Get-Item -LiteralPath $backupFile |
    Select-Object FullName, Length
Enter fullscreen mode Exit fullscreen mode

The steps are:

  1. Make sure PostgreSQL is running.
  2. Create a database archive inside the container.
  3. Copy it to Windows.
  4. Remove the temporary container copy only after the copy succeeds.
  5. Display the saved file.

The -Fc option creates PostgreSQL’s custom archive format, which we can restore using pg_restore.

We deliberately avoid sending the binary archive through PowerShell’s text output redirection. This prevents encoding problems, particularly in Windows PowerShell 5.1.

PostgreSQL can create this database snapshot while the application is running. PostgreSQL backup command documentation

What this backup includes

It includes this database’s objects and records.

It does not include PostgreSQL server roles and their passwords, your project files, or your Docker configuration.

Privately back up the project and .env as well.

Keep an additional protected copy outside this computer. A backup on the same disk does not help if that disk fails.

Step 16, Test the Backup Without Replacing the Live Database

A backup file existing is good.

Knowing that it can be restored is better.

The following optional test restores the newest backup into a new temporary database.

It does not overwrite the live appraisal database.

Run it while the database service is running:

$ErrorActionPreference = "Stop"

Set-Location (Join-Path $env:USERPROFILE "docker-appraisal-demo")

$backup = Get-ChildItem -Path ".\backups" -Filter "appraisal_*.dump" -File |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1

if ($null -eq $backup) {
    throw "No database backup was found."
}

$testDb = "appraisal_restore_" + (Get-Date -Format "yyyyMMdd_HHmmss")
$restoreFile = "/tmp/$testDb.dump"

docker compose cp $backup.FullName "db:$restoreFile"

if ($LASTEXITCODE -ne 0) {
    throw "Could not copy the backup into the container."
}

docker compose exec -T db createdb -U postgres --template=template0 $testDb

if ($LASTEXITCODE -ne 0) {
    throw "Could not create the separate test database."
}

docker compose exec -T db pg_restore -U postgres -d $testDb --no-owner --no-privileges --exit-on-error $restoreFile

if ($LASTEXITCODE -ne 0) {
    throw "The restore test failed. The live appraisal database was not replaced."
}

docker compose exec -T db psql -U postgres -d $testDb -v ON_ERROR_STOP=1 -c "SELECT count(*) AS restored_records FROM public.appraisals; SELECT id, employee_name, score FROM public.appraisals ORDER BY id LIMIT 5;"

if ($LASTEXITCODE -ne 0) {
    throw "The restored data could not be queried."
}

docker compose exec -T db rm -f $restoreFile

if ($LASTEXITCODE -ne 0) {
    Write-Warning "The restore succeeded, but the temporary archive was not removed."
}

Write-Host "Backup restored into the separate database: $testDb"
Write-Host "The live appraisal database was not replaced."
Enter fullscreen mode Exit fullscreen mode

Check that the restored record count and sample records are sensible.

The ownership and permission options deliberately simplify this scratch restore. This tests restoration of the database structure and data, not a complete recovery of users, permissions, and application configuration.

After inspection, you can remove only the generated test database in the same PowerShell session:

if ($testDb -notmatch '^appraisal_restore_\d{8}_\d{6}$') {
    throw "No valid tutorial test database is selected."
}

docker compose exec -T db dropdb -U postgres $testDb

if ($LASTEXITCODE -ne 0) {
    throw "Could not remove the test database."
}
Enter fullscreen mode Exit fullscreen mode

The name check prevents this cleanup block from targeting the live database named appraisal.

Step 17, Apply Changes Correctly

There are several different kinds of changes, and they do not all use the same command.

Back up your database before significant maintenance.

After changing Python code or HTML

Our application files are copied into the image.

Editing the Windows files alone does not update the running container.

Rebuild and start the app:

docker compose up -d --build --wait app
Enter fullscreen mode Exit fullscreen mode

This also applies changes to requirements.txt or the Dockerfile.

After changing Compose settings

Validate the configuration, then apply it:

docker compose config --quiet

if ($LASTEXITCODE -ne 0) {
    throw "The Compose configuration is invalid."
}

docker compose up -d --wait
Enter fullscreen mode Exit fullscreen mode

Compose can recreate containers when settings change, while preserving the mounted database volume.

A plain restart does not apply those configuration changes.

After changing .env

Compose can pass updated environment values when it recreates a container.

However, there is an important database exception:

Editing a password in .env does not change the password already stored inside PostgreSQL.

Likewise, editing the initialization script does not rerun it on an existing database.

Password rotation and database schema changes need deliberate database operations, not deletion of the data volume.

Updating downloaded software

For later maintenance, after making a backup, you can pull a newer PostgreSQL image within the selected major release and rebuild the app using an updated base image:

docker compose pull db

if ($LASTEXITCODE -ne 0) {
    throw "The database image download failed."
}

docker compose build --pull app

if ($LASTEXITCODE -ne 0) {
    throw "The application build failed."
}

docker compose up -d --wait
Enter fullscreen mode Exit fullscreen mode

Expect brief downtime when containers are replaced.

The tag postgres:17-bookworm keeps us within PostgreSQL 17, but it is not an exact patch version lock.

Do not treat changing 17 to another major version as routine maintenance.

Step 18, Shut Down and Start Again Tomorrow

For a clean manual shutdown:

Set-Location (Join-Path $env:USERPROFILE "docker-appraisal-demo")
docker compose stop
Enter fullscreen mode Exit fullscreen mode

You can then close Docker Desktop and shut down Windows.

Next time:

  1. Start Docker Desktop.
  2. Wait until the engine is ready.
  3. Open PowerShell.
  4. Run:
Set-Location (Join-Path $env:USERPROFILE "docker-appraisal-demo")
docker compose up -d --wait
docker compose ps
Enter fullscreen mode Exit fullscreen mode

Open the website:

Start-Process "http://127.0.0.1:8000/"
Enter fullscreen mode Exit fullscreen mode

The restart policy can restart eligible containers when Docker is running, but a manual stop is respected. It does not make the application run while Docker Desktop or the computer is off.

Important Data Safety Rules

The most important name in this example is:

appraisal_demo_pgdata
Enter fullscreen mode Exit fullscreen mode

That is the volume holding the database files.

Keep these rules in mind:

  1. Stopping a container is not the same as deleting its stored data.

  2. Rebuilding the app does not erase this database volume.

  3. docker compose down removes project containers and the Compose network. The external database volume in this configuration remains.

  4. External volume storage is still local to this computer, it is not a remote backup.

  5. Manually deleting the volume, resetting Docker Desktop, or using certain cleanup commands can destroy the records.

  6. Copying the project folder alone does not copy the database volume.

  7. Keep protected backups and test restoration before you need it urgently.

For everyday shutdown, use docker compose stop. There is no need to remove the project containers.

Common Problems

Docker is not recognized

Close and reopen PowerShell after installation.

If it still fails, check that Docker Desktop installed successfully.

PowerShell cannot connect to the Docker engine

Open Docker Desktop and wait for it to become ready.

Confirm that it is using the Linux container environment.

Do not jump straight to a factory reset.

Compose cannot find a configuration file

Return to the project folder:

Set-Location (Join-Path $env:USERPROFILE "docker-appraisal-demo")
Enter fullscreen mode Exit fullscreen mode

Then try the command again.

Port 8000 is already in use

Another application may be using it.

In compose.yaml, change the application’s port entry from:

- "127.0.0.1:8000:8000"
Enter fullscreen mode Exit fullscreen mode

to:

- "127.0.0.1:8001:8000"
Enter fullscreen mode Exit fullscreen mode

Apply the change:

docker compose up -d --wait
Enter fullscreen mode Exit fullscreen mode

Then use:

http://127.0.0.1:8001/
Enter fullscreen mode Exit fullscreen mode

Only the Windows facing port changed. The container still listens internally on port 8000.

Use port 8001 for PowerShell health requests too.

If the database’s Windows port 5433 is occupied, the same idea applies, choose another available left hand port and use that port in pgAdmin.

The app or database is unhealthy

Read the logs:

docker compose logs --tail=100 db app
Enter fullscreen mode Exit fullscreen mode

A health failure is a symptom, the logs usually contain the useful explanation.

The app reports a password problem

Check whether .env was changed or regenerated after the database was initialized.

An existing database does not automatically adopt the new password from the file.

Restore the matching private settings or perform a proper password change. Do not delete saved records just to make a login error disappear.

Final Thoughts

Docker becomes much less mysterious when we separate a few ideas.

The image contains the application.

The container runs it.

Compose coordinates the services.

The volume holds the database files.

The backup gives us another copy when something happens to that volume.

We do not need to memorize every Docker command to manage a small local project. We need a reliable routine:

Start Docker Desktop, start the services, check health, read logs when something fails, and back up before important changes.

This demo is deliberately small. Before using an application like this for real users or employee information, add proper login and permission controls, form security, secure connections, dependency management, and a tested recovery process.

But for learning the everyday workflow, we now have the useful part:

A working application, saved records, clear maintenance commands, and a way to test that the backup actually restores.

Getting the page to load is the first win.

Knowing how to run it again tomorrow is the part that makes it useful.

Top comments (0)