NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / DOCKER RECIPES / APPLICATION STACK

Application stack

An application container and RasterizedDB in one Compose project, the application reaching the database by its service name. Use it as the shape for your own stack: swap the sample app for yours and keep the database service as it is.

What you get

  • rasterizeddb: the database, with a named volume and a healthcheck. Its ports are not published, so only containers in this project can reach it.
  • app: a small Python web app (app.py, built from Dockerfile) on 127.0.0.1:8000. It records every request in a table and answers with the count.
  • The app starts only once the database is healthy (depends_on: condition: service_healthy), and retries for a minute if the database is still not answering.

Prerequisites

  • Docker with the Compose plugin.
  • Internet access on the first build, to fetch python:3.12-slim and psycopg.

What to edit

  1. Copy .env.example to .env and set RASTERIZEDDB_PG_PASSWORD. Both services read it.
  2. To use your own application, replace the app service's build: . with your image and give it the connection settings it expects.

How the app is told where the database is: compose.yaml sets the standard libpq environment variables, which psycopg, psql and most PostgreSQL drivers read without any code.

VariableValue
PGHOSTrasterizeddbthe service name, resolved on the project network
PGPORT5432
PGUSERrasterized
PGPASSWORDfrom .env
PGDATABASEpostgresthe default database
PGSSLMODErequirethe server requires TLS by default

An application that takes one connection URL instead:

text
postgresql://rasterized:the-password@rasterizeddb:5432/postgres?sslmode=require

A password with characters such as @, : or / has to be percent-encoded inside a URL.

For production, give the application its own role with only the privileges it needs rather than the superuser rasterized. See Security.

Run it

sh
docker compose up -d --build
docker compose ps

Check that it works

sh
curl http://127.0.0.1:8000/
curl http://127.0.0.1:8000/hello
text
1 visits so far
2 visits so far

The rows are in the database:

sh
docker compose logs app
docker run --rm -it --network rasterizeddb-app_default postgres:17 \
  psql "host=rasterizeddb port=5432 user=rasterized dbname=postgres sslmode=require" -c "SELECT * FROM visits"

Stop and clean up

sh
docker compose down        # keeps the data volume
docker compose down -v     # deletes the data volume too

Remove the built app image as well:

sh
docker compose down -v --rmi local

Limits

  • The sample app opens a connection per request to stay short. A real application should use a connection pool.

The files

compose.yaml · Docker ComposeDOWNLOAD ↓
# A sample application and RasterizedDB in one Compose project. The app
# reaches the database by its service name, `rasterizeddb`, on the project's
# private network; only the app's port is published. Copy .env.example to
# .env first, then: docker compose up -d --build
name: rasterizeddb-app

services:
  rasterizeddb:
    image: ${RASTERIZEDDB_IMAGE:-milendenev/rasterizeddb:1.1.0}
    environment:
      RASTERIZEDDB_PG_PASSWORD: ${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD in .env}
    command: ["--log-level", "warn"]
    # No ports published: only containers on this project's network reach
    # the database. Add "127.0.0.1:5432:5432" to reach it from the host too.
    volumes:
      - data:/var/lib/rasterizeddb
    restart: unless-stopped
    stop_grace_period: 60s
    healthcheck:
      test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/5432"]
      interval: 10s
      timeout: 5s
      retries: 6
      start_period: 30s

  app:
    build: .
    environment:
      # libpq's own variables: psycopg, psql and most PostgreSQL drivers
      # read them.
      PGHOST: rasterizeddb
      PGPORT: "5432"
      PGUSER: rasterized
      PGPASSWORD: ${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD in .env}
      PGDATABASE: postgres
      PGSSLMODE: require
    ports:
      - "127.0.0.1:8000:8000"
    depends_on:
      rasterizeddb:
        condition: service_healthy
    restart: unless-stopped

volumes:
  data:
.env.example · Environment fileDOWNLOAD ↓
# Copy to .env next to compose.yaml and change the password.

# The password of the role `rasterized`, used on the first start only.
RASTERIZEDDB_PG_PASSWORD=change-me-to-a-long-random-password

# The image and tag. Pin a full version.
RASTERIZEDDB_IMAGE=milendenev/rasterizeddb:1.1.0
Dockerfile · DockerfileDOWNLOAD ↓
# The sample app's image: Python and the psycopg PostgreSQL driver.
FROM python:3.12-slim

RUN pip install --no-cache-dir "psycopg[binary]==3.2.3"

WORKDIR /app
COPY app.py .

# Any unprivileged user will do.
USER 65534:65534
EXPOSE 8000
CMD ["python", "-u", "app.py"]
app.py · PythonDOWNLOAD ↓
"""A small web app that keeps its data in RasterizedDB.

Every request is recorded in the table `visits`, and the page answers with
how many there have been. The connection settings come from the standard
libpq environment variables (PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE,
PGSSLMODE), which compose.yaml sets.
"""

import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import psycopg


def connect():
    """One connection, configured from the environment."""
    return psycopg.connect(autocommit=True)


def wait_for_database(attempts=30, delay=2.0):
    """The database may still be starting: try for a minute before giving up."""
    for attempt in range(1, attempts + 1):
        try:
            with connect() as conn:
                conn.execute(
                    "CREATE TABLE IF NOT EXISTS visits ("
                    " id BIGSERIAL PRIMARY KEY,"
                    " path TEXT NOT NULL)"
                )
            return
        except psycopg.OperationalError as error:
            print(f"database not ready (attempt {attempt}): {error}", flush=True)
            time.sleep(delay)
    raise SystemExit("could not reach the database")


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            with connect() as conn:
                conn.execute("INSERT INTO visits (path) VALUES (%s)", (self.path,))
                (count,) = conn.execute("SELECT COUNT(*) FROM visits").fetchone()
            body = f"{count} visits so far\n".encode()
            self.send_response(200)
        except psycopg.Error as error:
            body = f"database error: {error}\n".encode()
            self.send_response(503)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


if __name__ == "__main__":
    wait_for_database()
    print("listening on :8000", flush=True)
    ThreadingHTTPServer(("0.0.0.0", 8000), Handler).serve_forever()
✓ page rendered in 136 µs axum + tera + htmx · no other javascript