Deploying to a server¶
Every new Karni project has a production stack next to its development one.
karni new writes three files for it, and karni make deploy compose writes
them in an existing project:
| File | What it is |
|---|---|
docker-compose.prod.yml |
The services below, with health checks, restart policies, memory limits, log rotation and named volumes. No source code is mounted from the host. |
Caddyfile |
The web front: TLS, static and media files, the staff app, and the proxy to Django. |
.env.prod.example |
Every production value. Copy it to .env.prod on the server and fill it in. |
The images come from the project's Dockerfile (targets prod and
backup). The logic they run is in Karni (karni.deploy), so karni upgrade
fixes it for every project. The three files are yours to edit.
With Docker on the server, one command starts everything:
The rest of this page goes through a first deployment step by step, then updates, rollback, logs, backups and restore, and then health checks, Celery and beat, static and media files, API versions for mobile clients and scaling.
A server without Docker, where nginx already serves other sites, takes
karni make deploy systemd-nginx instead: systemd units, an nginx vhost and
a deploy script (without Docker).
What runs¶
| Service | What it does | Health check |
|---|---|---|
release |
Runs once per start, before the others: the deploy checks, migrate, collectstatic, in a project with a public site karni_site_seed (every page rendered once, so a visitor's request never stores a template's defaults), then karni_publish_web, which copies the Caddyfile, the built staff app, each game's build (--front) and the security headers into the shared volume. If it fails, nothing else starts. |
none: the others wait for it to exit with 0 |
django |
gunicorn with uvicorn workers (WEB_CONCURRENCY, default 2). It serves the API, the admin, /healthz, /readyz, /health/ and a public site app. |
/readyz, asked as Caddy asks it (health checks) |
worker |
The Celery worker (KARNI_WORKER_CONCURRENCY, default 2). |
celery inspect ping |
beat |
Celery beat. Run exactly one. | its process has passed the deploy checks |
caddy |
TLS for DOMAIN, /static/ and /media/ from the shared volume, the staff app, each game at /play/<slug>/, and everything else proxied to django. Publishes ports 80 and 443. |
its admin API |
db |
PostgreSQL (POSTGRES_VERSION, default 16). Not reachable from outside the stack. |
pg_isready |
redis |
The Celery broker and the cache. Under memory pressure it drops cache keys, never a queued task. | redis-cli ping |
backup |
Database and media backups on a schedule, with retention. | the last backup did not fail |
Every container built from the prod image starts through
python -m karni.deploy.entrypoint, which runs karni check --deploy first
(Django's check --deploy and Karni's deploy checks).
When a check fails, the container prints each finding with its code and fix,
then E520, and exits without starting its command. So a missing
SECRET_KEY, DEBUG left on or the admin at /admin/ stops the deployment
instead of reaching users.
For an emergency start with a failing check, set KARNI_SKIP_DEPLOY_CHECK=1
in .env.prod. Every container then logs, on every start, that the checks did
not run. Remove it as soon as the values are fixed.
Choices¶
karni make deploy compose takes flags for what differs between projects.
Run it again with --force to rewrite the files:
| Flag | Effect |
|---|---|
--app-path /staff/ |
Serve the staff app under another path (default /app/). / serves it at the root of the site, for a project without a public site. |
--app-domain app.example.com |
Serve the staff app on its own host, with the API on the same origin. |
--no-app |
Serve no staff app. |
--no-celery |
No worker and no beat. .env.prod.example then sets KARNI_HEALTH_CHECKS without the Celery check. |
--no-db, --no-redis |
Use a managed PostgreSQL or Redis: set DATABASE_URL or REDIS_URL to it. |
--no-backups |
No backup service. |
--domain example.com |
The host written into .env.prod.example. |
Hosts, ports, image names and sizes are variables in .env.prod, listed in
.env.prod.example.
The staff app¶
The staff app in frontend/ is built into the production image by the
Dockerfile's staff-app stage: npm ci (or npm install when
package-lock.json does not list @karni/ui yet, as the lock karni new
writes does not), then npm run build with Vite's base set to the app's path
(KARNI_APP_PATH, /app/ by default). The router in src/routes.tsx takes
the same base, so links and reloads work under it.
The release step copies the build into the shared volume, and Caddy serves it:
/app/ answers index.html, any deeper path of the app (a reload, a shared
link) answers index.html too, and the hashed files under /app/assets/ are
cached for a year. The app calls the API at /api/ on the same origin, so no
CORS setting is needed and session cookies work.
Caddy sends the security headers Django sends (the content security policy,
HSTS and the others) on the app and on static files. karni_publish_web writes
them from the project's settings on every release, so a source added to
KARNI_CSP reaches the app as well. Files of the previous build stay for seven
days, so a browser that still holds the previous index.html keeps working
during an update.
A project without frontend/package.json gets no staff app, and nothing else
changes.
The games¶
A project with games (game/<slug>/, apps and games)
builds each one in the Dockerfile's games stage: npm ci (or npm install
until the game has a package-lock.json), then npm run build. The prod
image holds the builds, the release step publishes each one with
karni_publish_web --front play/<slug>=game/<slug>/dist, and Caddy serves
/play/<slug>/ from the shared volume with the security headers, the hashed
assets cached for a year. A game-first project's / goes to its game. Only
the build is published, never the game's source. The page calls the API on
the same origin.
1. A server¶
One small server is enough to start: 2 GB of memory, 1 or 2 CPUs and 20 GB of
disk, with a current Ubuntu LTS or Debian. Install Docker Engine and its
Compose plugin as Docker documents for your distribution,
and add your user to the docker group.
Open ports 22, 80 and 443 (TCP) in the firewall, and 443 over UDP for HTTP/3. Caddy is the only service that publishes ports.
Building the image needs about 1.5 GB of memory for the staff app's build. On
a 1 GB server, add swap or build the images elsewhere and push them to a
registry (set KARNI_IMAGE to the registry's name).
2. DNS¶
Create an A record (and an AAAA record for IPv6) for the site's host,
pointing at the server's address. With --app-domain, create one for the
app's host too. Check that it resolves before the first start:
3. TLS¶
Caddy gets the certificate by itself on the first start, once DNS points at
the server and ports 80 and 443 reach it, and renews it before it expires.
Plain-http requests are redirected to https. The certificates live in the
caddy_data volume: keep it, since certificate authorities limit how often a
host may ask for a new one. To receive expiry notices, uncomment the email
line at the top of the Caddyfile.
The production profile sends HSTS for one year with preload, which browsers
remember. While you try a new domain, set SECURE_HSTS_SECONDS=3600 in
.env.prod, and remove it once https works.
4. The code and .env.prod¶
git clone https://git.example.com/you/your-project.git
cd your-project
cp .env.prod.example .env.prod
chmod 600 .env.prod
Fill in every empty value. The file shows a command that generates each secret:
SECRET_KEY: 50 or more random characters.KARNI_ADMIN_PATH: a path nobody guesses, with a trailing slash, for examplestaff-7f3a9c2e/. The admin answers there and/admin/answers 404.POSTGRES_PASSWORD, and the same password inDATABASE_URL. Use letters and digits: they need no escaping in the URL.DOMAIN,ALLOWED_HOSTS,CSRF_TRUSTED_ORIGINSandKARNI_FRONTEND_URL, already set from the domainkarni newwas given.
Then uncomment the email lines and fill them in. Password resets, account
emails and the notifications of a site's forms go through them, and the
containers refuse to start without them (karni.W520):
EMAIL_URL: the mail server, host, port, user and password in one URL,smtp+tls://user:password@smtp.example.com:587(smtps://for SSL on port 465). Write an@in the user or password as%40.DEFAULT_FROM_EMAIL: the sender, an address of the site's domain such asnoreply@example.com. The mail server must accept it as a sender.
A project that sends no email at all adds "karni.W520" to
SILENCED_SYSTEM_CHECKS in config/settings.py instead.
Copy any other setting the project changed in .env (registration, roles,
KARNI_CSP for a font host, KARNI_PHONE_COUNTRY_CODE, Sentry). Avoid $ in values: Compose reads
it as a variable. Never commit .env.prod. The scaffold's .gitignore and
.dockerignore list it, so it is neither committed nor copied into the image.
Check the file before starting:
The commands below are long, so define a short name for them in the shell on the server:
The variables that matter¶
.env.prod.example lists every value. These are the ones that change how the
site behaves, grouped by what they do:
| Variable | Default | What it does |
|---|---|---|
SECRET_KEY |
none | Signs sessions and tokens. 50 or more random characters. Changing it signs everyone out. |
DJANGO_ENV, DEBUG |
prod, off |
The production profile. karni check --deploy refuses DEBUG on. |
ALLOWED_HOSTS, CSRF_TRUSTED_ORIGINS |
the domain | The hosts Django answers and the origins whose forms it trusts. |
KARNI_ADMIN_PATH |
none | Where the admin is. |
DATABASE_URL, REDIS_URL |
the stack's | Where PostgreSQL and Redis are. A managed service is a different URL. |
WEB_CONCURRENCY, KARNI_WORKER_CONCURRENCY |
2, 2 |
Gunicorn workers and Celery processes (scaling). |
KARNI_READYZ_CHECKS, KARNI_HEALTH_CHECKS, KARNI_HEALTH_TIMEOUT |
database, cache, broker, plus Celery, 3 seconds | What /readyz and /health/ready/ check and how long each check may take (health checks). |
KARNI_LOG_QUIET_PATHS |
the probe paths | Paths whose successful requests the request log skips. |
KARNI_API_VERSION, KARNI_API_VERSIONS, KARNI_API_UNVERSIONED |
unversioned | The API's version prefix and deprecations (API versions). |
KARNI_STORAGE, MEDIA_ROOT, STATIC_ROOT |
local, /data/... |
Where uploads and static files live (files). |
KARNI_BACKUP_*, POSTGRES_VERSION |
see backups | Backup retention, interval and the bucket. |
SENTRY_DSN |
empty | Error reports. |
KARNI_SITE_URL, KARNI_SITE_ALLOW_INDEXING, KARNI_SITE_QUEUE_RENDITIONS, KARNI_SITE_SEED_ON_RENDER |
the domain, open in prod, on, on | A public site's address, whether search engines may index it (False for a staging copy), whether image copies wait for a Celery worker, and whether a visit stores a template's defaults (public site). In a project with karni-site. |
A variable in .env.prod reaches the containers through Compose's env_file.
A JSON value is written in single quotes, such as
KARNI_API_VERSIONS='{"v0": {"deprecated": true}}'.
5. First start¶
The build takes a few minutes the first time. Then release runs and exits,
and the other services start. Within a minute or two prod ps shows each of
them healthy. Check the whole stack, including the database, the cache and
the Celery broker:
/health/ready/ also needs a Celery worker to answer. Ask it to know the
worker runs (health checks).
If a service does not become healthy, its log says why:
A failing deploy check shows its code (karni.W511 for a weak key, for
example), and karni explain W511 says what the value must be.
6. The first superuser¶
Sign in at https://example.com/<KARNI_ADMIN_PATH>. The staff app is at
https://example.com/app/.
7. Updates¶
An update builds the new image while the old containers keep serving, applies the migrations, then replaces the containers.
git pull
prod exec backup karni-backup run # a backup first, for a rollback
prod build
prod run --rm release # deploy checks, migrations, static and web files
prod up -d --no-build --no-deps django worker beat backup
up stops each old container and starts the new one. While django
restarts, Caddy holds incoming requests and retries for up to 30 seconds, so
they are answered a few seconds late instead of failing. A Celery task that
is running gets 60 seconds to finish, and queued tasks wait in Redis for the
new worker.
To have no pause at all, start the new django container next to the old one,
wait until it is healthy, then stop the old one. Caddy sends requests to both
while both run:
old=$(prod ps -q django)
prod up -d --no-build --no-deps --no-recreate --scale django=2 django
new=$(prod ps -q django | grep -v "$old")
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ]; do sleep 2; done
docker stop "$old" && docker rm "$old"
When the Caddyfile changed, reload Caddy after the release step. The reload
does not drop connections:
To keep each release's image for a rollback, tag it before the next build:
tag=$(git rev-parse --short HEAD)
docker tag your_project:latest "your_project:$tag"
docker tag your_project-backup:latest "your_project-backup:$tag"
(The image is named after the project, KARNI_IMAGE in .env.prod.)
Migrations on deploy¶
Migrations run in the release step, once per deployment, before any new
container serves a request. django, worker and beat never migrate, so
two replicas cannot race, and a migration that fails stops the deployment with
the old containers still serving. Run them by hand with prod run --rm release
(the whole step) or prod exec django python manage.py migrate --check to
see whether any are pending. Take a backup first when a migration changes or
drops data: prod exec backup karni-backup run.
Migrations that the old code cannot run with¶
Between the release step and the restart, the old code runs against the new schema. Adding a table, or a column that is nullable or has a default, is safe. Removing or renaming a column, or making one required, breaks the old code during that window. Split such a change over two releases:
- Add the new column or table, nullable. The code writes both the old and the new place and reads the new one with a fallback. A data migration copies the old values.
- In the next release, once no running code reads the old column, remove it.
When a change cannot be split, take a short maintenance window instead: stop the services that use the database, run the release step, start them again. Requests get an error for that minute.
8. Rollback¶
When the release had no migration, or only migrations the previous code can run with, start the previous image:
docker tag your_project:<previous tag> your_project:latest
docker tag your_project-backup:<previous tag> your_project-backup:latest
prod run --rm release
prod up -d --no-build --no-deps django worker beat backup
The release step also restores the previous Caddyfile and staff app, so reload Caddy when the Caddyfile differs.
When a migration must be undone, reverse it with the new image first, then start the previous one:
When a migration cannot be reversed, or data was lost, restore the backup taken before the update (below).
9. Logs¶
prod logs -f django worker # follow
prod logs --since 1h caddy # the last hour
prod ps # state and health of each service
Django writes one JSON object per line in production, with the request id of
each request, so a log tool can read it. Each container's log is rotated at
10 MB and five files are kept. Caddy logs its own errors and certificate
renewals. To log every request, add a log directive to the Caddyfile.
Errors reach Sentry when SENTRY_DSN is set (karni[sentry]).
10. Backups¶
The backup service writes a backup when one is due: at start when the
newest one is older than KARNI_BACKUP_INTERVAL_HOURS (default 24), then
every interval. It keeps the newest KARNI_BACKUP_KEEP (default 7). A backup
is a folder named by its UTC time, holding the database (pg_dump, custom
format), the media files and a manifest. It is written under a temporary
name and renamed when complete, so a backup that failed half way never
counts.
When a backup fails, the service logs E521 with the step that failed, and
its health check turns unhealthy until a backup succeeds.
Backups in the backups volume do not survive the loss of the server. Set
KARNI_BACKUP_S3_BUCKET (with AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,
and AWS_S3_ENDPOINT_URL for a service other than AWS) and each backup is
also uploaded there, with the same retention. Otherwise, copy the volume's
contents off the server on a schedule.
| Variable | Default | Meaning |
|---|---|---|
KARNI_BACKUP_KEEP |
7 |
backups kept, locally and in the bucket |
KARNI_BACKUP_INTERVAL_HOURS |
24 |
hours between backups |
KARNI_BACKUP_DIR |
/backups |
where backups are written in the container |
KARNI_BACKUP_MEDIA_ROOT |
MEDIA_ROOT |
the media folder to archive (empty: none) |
KARNI_BACKUP_S3_BUCKET |
none | also upload each backup to this bucket |
KARNI_BACKUP_S3_PREFIX |
backups/ |
the key prefix in the bucket |
POSTGRES_VERSION |
16 |
the database's major version, which the backup image's pg_dump matches |
The backup service uses the PostgreSQL client tools of POSTGRES_VERSION.
Tools of a newer major version write dumps an older server may refuse to
restore, so keep it equal to the database's version, a managed one included.
The tool is a standard-library Python file of Karni, so another scheduler can
run it too: python -m karni.deploy.backup run wherever pg_dump is
installed.
11. Restore¶
Restore into a second database first, and compare it with the live one. The row counts match when nothing was written since the backup:
prod exec backup sh -c 'karni-backup restore latest --create --database-url "${DATABASE_URL%/*}/restore_check"'
prod exec backup sh -c 'karni-backup counts --database-url "$DATABASE_URL" --against "${DATABASE_URL%/*}/restore_check"'
restore runs in one transaction, so a restore that fails changes nothing.
latest is the newest backup, or name one from karni-backup list. When the
backup is only in the bucket, it is downloaded first.
To replace the live database and media with a backup, stop what writes to
them, restore with --clean, then start again:
prod stop django worker beat
prod exec backup karni-backup restore latest --clean --media-root /data/media
prod run --rm release
prod up -d --no-build django worker beat
Without --database-url, restore --clean restores over DATABASE_URL.
Restored media files are given to the owner of the media folder, so uploads
keep working. Drop the check database when you no longer need it:
12. Health checks¶
Karni answers four URLs. None needs a login, none is cached, and none is
asked of the terms gate, so a proxy, an orchestrator or a monitor can call
them at any time. The request log skips the successful ones
(KARNI_LOG_QUIET_PATHS), so a probe every few seconds does not fill it.
| URL | Means | Touches |
|---|---|---|
/healthz |
The process answers. Liveness: restart the container when this fails. | nothing |
/readyz |
The process can serve: the database, the cache and the Celery broker respond. Readiness: send no traffic when this fails. | database, cache, broker |
/health/ |
The older liveness URL. Same answer as /healthz. |
nothing |
/health/ready/ |
The older readiness URL, which also needs a Celery worker to answer. | database, cache, a worker |
{"status": "ok", "failing": [],
"checks": {"database": {"ok": true, "detail": "database responding"},
"cache": {"ok": true, "detail": "cache responding"},
"broker": {"ok": true, "detail": "broker responding"}}}
When a check fails the status is 503, status is fail and failing names
it, such as "failing": ["cache"], with the error in that check's detail.
Each check gets KARNI_HEALTH_TIMEOUT seconds (default 3). One that does not
answer in time fails with no answer within 3s, so a database that accepts the
connection and then stalls cannot hold the probe.
/readyz leaves the Celery workers out on purpose. A web container is ready
when it can enqueue a task, whether or not a worker is up this second. Ask
/health/ready/ when you want to know a worker answers, as the CI job does.
The checks are settings. KARNI_READYZ_CHECKS and KARNI_HEALTH_CHECKS list
dotted paths to functions that return (ok, detail), comma-separated in the
environment, so a project adds its own check (an object store, a mail relay)
or removes one:
The compose files' health check for django asks /readyz, and Caddy
forwards /healthz and /readyz so an outside monitor can ask too. A project
created before these URLs keeps asking /health/. Add them with
from karni.health.probe_urls import urlpatterns as probe_urls and
*probe_urls in config/urls.py, then run karni make deploy compose --force.
13. Celery and beat¶
worker runs the Celery worker with KARNI_WORKER_CONCURRENCY processes and
beat runs the scheduler. Both take their broker from REDIS_URL.
- Run exactly one
beat. Two would enqueue every scheduled task twice. The schedule is in the database (django-celery-beat), so a restart loses nothing. - A worker finishes the task it is running for up to 60 seconds when it is stopped. Queued tasks wait in Redis for the new worker. Redis is set to drop cache keys under memory pressure and never a queued task.
- A task that takes longer than the time limits (
CELERY_TASK_TIME_LIMIT, 300 seconds, andCELERY_TASK_SOFT_TIME_LIMIT, 240) is stopped. Raise them for a long job, or split it. - Without tasks to run,
karni make deploy compose --no-celeryleaves both out, and/health/ready/stops asking for a worker. /readyzfails when the broker does not answer. A worker that is down shows inprod ps(its health check iscelery inspect ping) and in/health/ready/.
14. Static and media files¶
The release step runs collectstatic into the app_data volume and
karni_publish_web copies the staff app next to it. Caddy reads the volume
and serves /static/, /media/ and the staff app with long cache lifetimes
on the hashed files, so Django never serves a file in production.
- Static files are written on every release. Nothing to back up.
- With
KARNI_STATIC_STORAGE=manifest, which a new site project's.env.prod.examplesets,collectstaticalso writes a copy of each file whose name carries a hash of its content (site.3f2a91c0b4d7.css) and a manifest, and{% static %}names the copy, in a tag, an attribute or adata-*attribute alike. A stylesheet'surl(...)is rewritten to the copies too. The Caddyfile (and the nginx vhost ofsystemd-nginx) lets browsers keep such a file for a year, and a file under its plain name for a short while only, so a release reaches every browser at once. The plain names stay inSTATIC_ROOT, so an address a script builds by hand keeps working. A file the manifest does not hold (a typo, one added withoutcollectstatic) gets its plain name and a warning in the log, not a failed page, and a stylesheet'surl(...)to a file that does not exist is kept as written instead of stoppingcollectstatic.KARNI_STATIC_STORAGE=plain(the default) keeps the names as written. - Uploads are written by Django to
MEDIA_ROOT(/data/media) in the same volume, and Caddy serves them from there. The backup service archives that folder with the database (backups). - On more than one server, or to keep uploads out of a volume, set
KARNI_STORAGE=s3with the bucket's settings. Django then writes to the bucket and the media folder stays empty. See settings. - The volume is a Docker named volume.
prod down -vdeletes it, so never run that on a server that matters.
15. API versions for mobile clients¶
A browser app is replaced on the next page load. A mobile app is not: the build a user installed last year still calls your API. A version prefix lets the API change for new builds while old ones keep a URL that does not move. It is off until you set it, and an unversioned project is unchanged. Experimental, see API versions for the whole reference.
KARNI_API_VERSION=v1 # /api/v1/products/
KARNI_API_UNVERSIONED=keep # /api/products/ still works
KARNI_API_VERSIONS='{"v0": {"deprecated": "2026-06-01", "sunset": "2027-01-31", "notes": "https://example.com/api-v0-to-v1"}}'
A response from /api/v0/ then carries these headers:
Deprecation: @1780272000
Sunset: Sun, 31 Jan 2027 00:00:00 GMT
Link: <https://example.com/api-v0-to-v1>; rel="deprecation"; type="text/html"
Ship a new version in three steps: add v2 and make it current, mark v1
deprecated with a sunset date, and read the logs for /api/v1/ until no
client calls it. Then remove v1 from KARNI_API_VERSIONS. karni check
warns (karni.W660) about a version still mounted after its sunset date.
/api/auth/, /api/schema/ and /api/docs/ are not versioned.
Each version has its own OpenAPI document at /api/<version>/schema/, and
karni types writes a typed client for each into frontend/src/api/<version>/.
Hand a mobile team the document of the version they target.
16. Scaling¶
The stack is one server. Most of what limits it is memory, and each service
has a limit in .env.prod (KARNI_DJANGO_MEMORY and the others).
- More requests: raise
WEB_CONCURRENCY, about two gunicorn workers per CPU core, and the memory limit with it. Each worker holds the application once. If that is not enough, start a seconddjangocontainer (prod up -d --scale django=2) and Caddy sends requests to both. - More background work: raise
KARNI_WORKER_CONCURRENCY, or run a secondworkerservice on its own queue. Leavebeatat one. - The database: it is the first thing to outgrow the server. Move it to a
managed PostgreSQL (
--no-db,DATABASE_URLpointing at it, andPOSTGRES_VERSIONequal to its major version), which also gives you its backups and failover. Keep thebackupservice for a copy you control. - Redis: one instance serves the cache and the queue. Point
REDIS_URLat a managed Redis (--no-redis) when the server's memory is the limit. - Files: past one server, use
KARNI_STORAGE=s3so every container sees the same uploads. - Running more than one
djangocontainer: nothing is stored in the container, so any request can go to any of them. The cache, the sessions' throttle counters and the queue are in Redis, which all of them share. - Where to look first:
karni queriesand the performance section name the slow query, anddocker statsshows which service is at its memory limit.
Without Docker: systemd and nginx¶
On a server that runs nginx and systemd, often next to other sites, a
project runs without Docker. One command writes the files for it into
deploy/:
| File | What it is |
|---|---|
deploy/deploy.sh |
The deploy, run on the server from the project's folder. |
deploy/web.service |
gunicorn with uvicorn workers on a Unix socket, installed as <project>-web.service. |
deploy/worker.service, deploy/beat.service |
The Celery worker and beat (--no-celery leaves them out). |
deploy/nginx.conf |
The vhost: TLS for the domain, /static/ and /media/ from disk, everything else proxied to the socket. |
deploy/env.example |
Every production value for this server. |
deploy/README.md |
Preparing the server, the first deploy, updates, rollback, logs. |
| Flag | Default | Effect |
|---|---|---|
--domain |
DOMAIN in .env.example |
The site's host, in the vhost and the .env. |
--root |
/srv/<project> |
The folder for the releases, the uploads and the .env. |
--user |
www-data |
The user the units run as. nginx runs as www-data on Debian and Ubuntu, so it can open the socket. |
--keep |
5 |
The releases kept for a rollback, at least 2. |
--cert, --cert-key |
Let's Encrypt's for the domain | The certificate and its key, for example a CDN's origin certificate. |
--no-celery |
Celery on | No worker and no beat. |
--single-process |
off | One process for a small server, without Redis or Celery (below). |
The values live at the top of deploy.sh. The units and the vhost hold
@APP@, @ROOT@ and the like, which the script fills in when it installs
them, so a value changes in one place. DEPLOY_<NAME> in the environment
replaces one for a single run (sudo DEPLOY_KEEP=10 deploy/deploy.sh).
What a deploy does¶
Prepare the server once (the packages, a PostgreSQL role and database, a
certificate: deploy/README.md lists the commands), put the project on it,
for example with git clone, and run the script from the project's folder:
sudo deploy/deploy.sh # the first run writes <root>/shared/.env and stops
sudo editor /srv/your_project/shared/.env
sudo deploy/deploy.sh # every later deploy: git pull, then this
Each run, in order, and each step stops the run with a message when it fails:
- Checks that Python, nginx, systemd, curl and the certificate are there,
and that
nginx -tpasses before anything changes. - Writes
<root>/shared/.envfromdeploy/env.examplewhen it does not exist, and stops so you fill it in. Once it exists, the script never writes over it or deletes it. - Copies the project into
<root>/releases/<time>-<commit>/, without.git, virtual environments,data/and the.envfiles, and installs its dependencies into the release's own.venv. - Runs
karni_check --deploy,migrateandcollectstaticwith the server's.env, as the units' user, and in a project with a public sitekarni_site_seed, which renders every page once so a visitor's request never stores a template's defaults. In a project with games, it builds each game with npm (unless the game'sdist/came with the project) and publishes the builds to<root>/shared/web/play/, which nginx serves at/play/<slug>/. That needs Node.js 20.19 or later on the server. - Points
<root>/currentat the release (an atomic switch), installs the units, restarts them and asks/readyzon gunicorn's socket until it answers 200. When it does not, the run stops before nginx and says which release--rollbackgoes back to. - Installs the vhost, links it from
sites-enabledand runsnginx -t. nginx reloads only when the test passes. When it fails, the previous vhost goes back in place, or the link is removed when there was none, so the other sites on the server keep working. - Keeps the newest
--keepreleases and removes the older ones.
Running it again is safe: a unit or a vhost that did not change is not installed again, and nginx is not reloaded. Two runs at once are refused.
The script touches only its own paths: <root>/, the units named
<project>-*.service and the vhost <project>.conf with its link.
A small server: one process¶
A server with 1 GB of memory, shared with other sites, has no room for Redis and a Celery worker. One switch runs the project as one process:
karni make deploy systemd-nginx --single-process writes the files for
it: the two lines in env.example, one web unit and no worker or beat,
and gunicorn as one WSGI worker with four threads, which share the
process's cache. The switch sets these defaults, each only where the
project, an override or the environment has no value of its own:
| Setting | With the switch | Why |
|---|---|---|
KARNI_CACHE |
locmem |
The cache lives in the process, so no Redis. |
CELERY_TASK_ALWAYS_EAGER |
True |
A task runs in the process that sends it: a queued listener (a form's notification email) runs after the request's commit, and an upload's smaller image copies are made as it is saved. |
CELERY_BROKER_URL |
memory:// |
Nothing opens a connection to a broker. |
KARNI_READYZ_CHECKS, KARNI_HEALTH_CHECKS |
the database and the cache | /readyz and /health/ready/ ask for no broker and no worker. |
karni.W501, which karni check --deploy fails on, warns that a cache
private to each process multiplies the rate limits by the worker count.
With the switch it is quiet, unless WEB_CONCURRENCY asks gunicorn for
more than one worker. Two things a worker would do do not happen: beat
does not run, so no scheduled task fires (run manage.py
flushexpiredtokens from a systemd timer for the one Karni schedules), and
a task that takes long makes its request wait. KARNI_SITE_QUEUE_RENDITIONS
can stay on: the copies are made in the process, on upload and in the
deploy's karni_site_seed.
Rollback¶
deploy/deploy.sh --list # the releases, the current one marked
sudo deploy/deploy.sh --rollback # the newest earlier release that answered its health check
sudo deploy/deploy.sh --rollback <id> # a release --list shows
A rollback runs collectstatic from that release (so its static files'
names are the ones served), switches, restarts and asks /readyz again. It
runs no migration: when the earlier code cannot run with the newer
migrations, reverse them first with the newer code, as in
rollback.
Differences from the compose stack¶
- The database and Redis are the server's:
DATABASE_URLandREDIS_URLin its.envpoint at127.0.0.1. - nginx serves
/static/and/media/from<root>/shared/. Uploads getX-Content-Type-Options: nosniffandContent-Security-Policy: script-src 'none', as in the Caddyfile. - Backups are not included: back up the database with the server's own
tools (
pg_dumpon a timer), or runpython -m karni.deploy.backup runfrom a release's.venv(backups). - The staff app in
frontend/is not served. Serve its build with alocationof your own indeploy/nginx.conf, or use the compose stack. The games are served, at/play/<slug>/. KARNI_NUM_PROXIES=1counts nginx. Behind a CDN or a load balancer as well, set it to 2, so rate limits see the visitor's address.
An existing project¶
A project created before Karni 0.5.0 has a Dockerfile without the
staff-app and backup targets and without the deploy gate. Copy those parts
from a new project's Dockerfile (karni new in a scratch folder), add the
basepath line to frontend/src/routes.tsx, then write the stack:
--force replaces an existing Caddyfile. The command stops with C105
and names the missing target when the Dockerfile lacks one.
Before Karni is published¶
To build the images from a Karni checkout instead of the releases, copy the
packages into the project, which is the image's build context, and name them
in .env.prod:
cp -r /path/to/Karni/packages/karni .karni-src
mkdir -p .karni-ui
(cd /path/to/Karni/packages/karni-ui && npm ci && npm run build && npm pack --pack-destination "$OLDPWD/.karni-ui")
Karni's CI does exactly this in its "Production stack (compose, smoke)" job.
It creates a project with karni new (with a site, and one model with its
list page), builds both images, starts the stack with generated production
values and migrates. It seeds demo rows (karni_seed) and runs
.github/ci/prod_smoke.py check, which reads /readyz and /healthz, signs
in through the API, reads a list endpoint at /api/ and at /api/v1/,
checks that a deprecated version sends its headers, opens a public page, the
admin login, a static file and the staff app, and checks the security headers.
Then one Playwright test (.github/ci/prod_e2e/signin.spec.ts) signs in to the
built staff app and sees a table of the seeded rows. The job ends with the
deploy gate and a backup restored into a second database. The smoke script
and the Playwright test run by hand against any running stack, runserver
included, as their files say.