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 fromDockerfile) on127.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-slimandpsycopg.
What to edit
- Copy
.env.exampleto.envand setRASTERIZEDDB_PG_PASSWORD. Both services read it. - To use your own application, replace the
appservice'sbuild: .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.
| Variable | Value | |
|---|---|---|
PGHOST | rasterizeddb | the service name, resolved on the project network |
PGPORT | 5432 | |
PGUSER | rasterized | |
PGPASSWORD | from .env | |
PGDATABASE | postgres | the default database |
PGSSLMODE | require | the server requires TLS by default |
An application that takes one connection URL instead:
text
postgresql://rasterized:the-password@rasterizeddb:5432/postgres?sslmode=requireA 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 psCheck that it works
sh
curl http://127.0.0.1:8000/
curl http://127.0.0.1:8000/hellotext
1 visits so far
2 visits so farThe 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 tooRemove the built app image as well:
sh
docker compose down -v --rmi localLimits
- 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.0Dockerfile · 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()