Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: A Web App and Database in a Pod

Build a small hit-counter app with Podman: write a Containerfile, create a pod, run PostgreSQL with a named volume, connect over localhost, add health checks and export the pod to YAML.

Time to combine what you know. In this project you build a tiny web app that counts page views in a PostgreSQL database, run both as one pod, persist the data in a volume, check health and finally export everything as YAML. Along the way you will use networking, building, volumes, logs and cleanup from the earlier lessons.

Podman and PostgreSQL are not available in the browser, so the commands and files are shown read-only. Two stand-ins let you run the interesting logic: the counter's SQL, and a readiness wait with backoff.

The plan

Project layout

App image Built from a Containerfile.
PostgreSQL Official image plus a volume.
Pod Shared localhost, one published port.
YAML export kube generate at the end.

One pod, two containers, one volume.

1 / 2

Because both containers share the pod's network namespace, the app reaches the database at localhost:5432, and only the app's port is published to the host.

Step 1: the application

Create a folder hits/ with app.py:

Python
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

import psycopg

DSN = os.environ["DATABASE_URL"]

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        with psycopg.connect(DSN) as conn:
            conn.execute("CREATE TABLE IF NOT EXISTS hits (id serial PRIMARY KEY, at timestamptz DEFAULT now())")
            conn.execute("INSERT INTO hits DEFAULT VALUES")
            count = conn.execute("SELECT count(*) FROM hits").fetchone()[0]
        body = f"page views: {count}\n".encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()

The server binds to 0.0.0.0, as Troubleshooting Podman Networking advised. The SQL logic is easy to try with SQLite, which Python includes:

Python The counter logic (stand-in with SQLite)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 2: the Containerfile

hits/Containerfile:

DOCKERFILE
FROM docker.io/library/python:3.13-slim
WORKDIR /app
RUN pip install --no-cache-dir "psycopg[binary]"
COPY app.py .
USER 1000
EXPOSE 8000
CMD ["python", "app.py"]

Build it:

Terminal
cd hits
podman build -t localhost/hits:1.0 .
podman images localhost/hits

The dependency install comes before the source copy, so edits to app.py rebuild in seconds (see Building Images with a Containerfile).

Step 3: the pod, volume and database

Terminal
podman volume create hitsdata
podman pod create --name hits -p 127.0.0.1:8080:8000

podman run -d --pod hits --name hits-db \
  -e POSTGRES_PASSWORD=example \
  -v hitsdata:/var/lib/postgresql/data \
  --health-cmd 'pg_isready -U postgres' --health-interval 5s --health-retries 5 \
  docker.io/library/postgres:17

Notes:

  • The port mapping belongs to the pod, so it is set in pod create.
  • 127.0.0.1: keeps the app off the network until you are ready to expose it.
  • The password in a command line is acceptable for a local experiment only; in a real setup use podman secret create and --secret.
  • Check readiness with podman healthcheck run hits-db or podman ps (look for healthy).

Step 4: wait for the database, start the app

Even after the container starts, PostgreSQL needs a few seconds before it accepts connections. A robust deployment retries instead of failing once. Here is the waiting logic with a simulated database that becomes ready on the fifth try:

Python Wait for readiness with backoff (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Start the app:

Terminal
podman run -d --pod hits --name hits-app \
  -e DATABASE_URL=postgresql://postgres:example@localhost:5432/postgres \
  --restart on-failure:5 \
  localhost/hits:1.0

If the database is not ready yet, --restart on-failure:5 gives the app more tries. (Under systemd you would order the units instead.)

Step 5: try it

Terminal
curl http://127.0.0.1:8080/
curl http://127.0.0.1:8080/
podman logs hits-app
podman exec hits-db psql -U postgres -c 'SELECT count(*) FROM hits'

The counter increases with every request. Now prove the volume works:

Terminal
podman pod rm -f hits           # removes containers and the pod, keeps the volume

Recreate the pod with the same commands from Step 3 and 4: the count continues where it stopped, because hitsdata survived. Add podman volume rm hitsdata only when you really want to delete the data.

Step 6: export and convert

Terminal
podman kube generate hits > hits.yaml
podman pod rm -f hits
podman kube play hits.yaml
podman kube down hits.yaml

The YAML file now describes the pod and can run on any machine with the image available, or be adapted for Kubernetes (see Podman and Kubernetes YAML). The next project turns the same layout into systemd services with Quadlet: Project: A Quadlet Stack.

Extensions to try

  • Replace the password with a Podman secret.
  • Add a second pod publishing port 8081 that shares the same volume (and discover why two PostgreSQL servers must not share one data directory).
  • Add --memory 256m to the app and watch podman stats.
  • Put the database on a user-defined network instead of a pod and connect by name.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the app connect to localhost:5432?

    All containers in a pod share the same network stack, so they reach each other on localhost.
  2. 2. Where must -p be set when containers belong to a pod?

    Ports are published on the pod because the containers share its network namespace.
  3. 3. What preserves the data when the pod is removed?

    podman pod rm removes containers but leaves named volumes.
  4. 4. Why wait or retry before the app connects to the database?

    A started container is not necessarily ready; use health checks, ordering or retries.

Summary

  • A pod groups the app and database so they share localhost and one published port.
  • A named volume keeps PostgreSQL data across container and pod removal.
  • Build the image with dependencies before source for fast rebuilds.
  • Readiness needs health checks or retries; started is not ready.
  • podman kube generate captures the working setup as YAML.

Next: Project: A Quadlet Stack