---
title: "Deployment"
description: "Build or pull the Pug backend, run its migrations, processes and scheduled jobs, and harden it for production."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.pug.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Deployment

Build, migrate, run and harden the **backend**. The dashboard deploys separately; see [Dashboard](/self-hosting/dashboard).

Meet the [Requirements](/self-hosting/requirements) and set the variables in [Configuration](/self-hosting/configuration) first. Run the `make` commands from the backend repo root.

## 1. Build

Ship the backend as **binaries** (systemd, bare processes) or **container images** (Kubernetes, Compose).

### Option A: binaries

```bash
make build
```

`make build` compiles these into `bin/`: the unified CLI, `bin/pug`, and a single-purpose binary per process.

| Binary | Equivalent to | Role |
|--------|---------------|------|
| `bin/pug` | - | Unified CLI: every sub-command in one binary |
| `bin/pug-server` | `pug server` | API server |
| `bin/pug-migrate-postgres` | `pug postgres migrate` | Postgres migration runner (up only) |
| `bin/pug-migrate-nats` | `pug nats migrate` | NATS stream initialiser |
| `bin/pug-migrate-clickhouse` | `pug clickhouse migrate` | ClickHouse migration runner (up only) |
| `bin/pug-worker-events` | `pug worker events` | Events worker: writes events to ClickHouse |
| `bin/pug-worker-email` | `pug worker email` | Transactional email worker |
| `bin/pug-worker-compliance` | `pug worker compliance` | Compliance worker (GDPR/DPDP erasure) |
| `bin/pug-worker-profile-identify` | `pug worker profile identify` | Profile identify worker |
| `bin/pug-worker-profile-alias` | `pug worker profile alias` | Profile alias worker |
| `bin/pug-worker-profile-upsert` | `pug worker profile upsert` | Profile upsert worker |
| `bin/pug-worker-demo` | `pug worker demo` | Demo-traffic generator (only for public demos) |
| `bin/pug-cron-purge` | `pug cron purge` | [Scheduled job](#scheduled-jobs): erases deleted projects |
| `bin/pug-cron-usage` | `pug cron usage` | [Scheduled job](#scheduled-jobs): meters event usage |
| `bin/pug-cron-retention` | `pug cron retention` | [Scheduled job](#scheduled-jobs): deletes event history past its retention |
| `bin/pug-cron-expired-tokens` | `pug cron expired-tokens` | [Scheduled job](#scheduled-jobs): deletes expired tokens |
| `bin/pug-cron-billing-reconcile` | - | Pug Cloud [billing job](#scheduled-jobs) |
| `bin/pug-cron-billing-meter` | - | Pug Cloud [billing job](#scheduled-jobs) |

> **Run the binaries from the folder that holds `schema/`** (systemd `WorkingDirectory=`), and ship the repo's `schema/` folder with them. The workers and `nats migrate` read `schema/nats/*.yaml`, and the Postgres and ClickHouse migrations `schema/{postgres,clickhouse}/migrations`, relative to the working directory. `NATS_STREAMS_CONFIG` and `NATS_CONSUMERS_CONFIG` can point at the NATS files elsewhere; the migration folders can't move.

> There is **no `make migrate` or `make dev` target**: use [`pug migrate`](#2-migrations) and [`pug dev`](/self-hosting/cli#dev).

### Option B: container images

Each image runs one single-purpose binary as its entrypoint, so start the container with no arguments. The images are distroless, run as `nonroot` from `/app`, and carry the `schema/` files their role needs.

#### Published images

Every release publishes one image per role to the GitHub Container Registry, for `linux/amd64` and `linux/arm64`:

```bash
docker pull ghcr.io/pug-sh/pug-server:0.0.53
```

Each image is tagged with its full version (`0.0.53`), its minor line (`0.0`) and `latest`. Pin the full version in production, and roll every role to the same one.

| Role | Image (`ghcr.io/pug-sh/...`) | `CMD` | Target |
|------|------------------------------|-------|--------|
| Server | `pug-server` | `server` | `app` |
| Events worker | `pug-worker-events` | `workers/events` | `worker` |
| Email worker | `pug-worker-email` | `workers/email` | `worker` |
| Compliance worker | `pug-worker-compliance` | `workers/compliance` | `worker` |
| Profile identify / alias / upsert | `pug-worker-profile-identify`, `pug-worker-profile-alias`, `pug-worker-profile-upsert` | `workers/profile/identify`, `workers/profile/alias`, `workers/profile/upsert` | `worker` |
| Demo worker | `pug-worker-demo` | `workers/demo` | `worker` |
| Scheduled jobs | `pug-cron-purge`, `pug-cron-usage`, `pug-cron-retention`, `pug-cron-expired-tokens` | `cron/purge`, `cron/usage`, `cron/retention`, `cron/expired-tokens` | `app` |
| Billing jobs (Pug Cloud only) | `pug-cron-billing-reconcile`, `pug-cron-billing-meter` | `cron/billing-reconcile`, `cron/billing-meter` | `app` |
| Postgres / NATS / ClickHouse migrate | `pug-migrate-postgres`, `pug-migrate-nats`, `pug-migrate-clickhouse` | `migrate/postgres`, `migrate/nats`, `migrate/clickhouse` | `migrate` |

#### Build your own

The repo's one `Dockerfile` builds any image above, chosen by its `CMD` and Target: `--build-arg CMD=<path under ./cmd>` picks the `main` to compile, and `--target` what else lands in the image.

| Target | Contains | Used by |
|--------|----------|---------|
| `app` | distroless + the binary only | The server and the scheduled jobs (read nothing from `schema/`) |
| `worker` | binary + `schema/nats` | Workers (read `schema/nats/consumers.yaml` at startup) |
| `migrate` | binary + `schema/` migration assets | The migrate runners |

```bash
# API server
docker build --build-arg CMD=server            --target app     -t pug-server .

# a worker (swap the CMD path for any worker in the table)
docker build --build-arg CMD=workers/events    --target worker  -t pug-worker-events .

# a migration runner
docker build --build-arg CMD=migrate/postgres  --target migrate -t pug-migrate-postgres .
```

A plain `docker build` targets the host's architecture. The Dockerfile cross-compiles, so `docker buildx build --platform linux/amd64,linux/arm64 ...` builds both without QEMU.

## 2. Migrations

Run the migrations **before the first boot** and again on every upgrade. Re-running them on an up-to-date store is safe.

```bash
./bin/pug migrate              # all three: Postgres, NATS, then ClickHouse

# or one store at a time
./bin/pug postgres migrate
./bin/pug nats migrate
./bin/pug clickhouse migrate

# or the standalone binaries / migrate images
./bin/pug-migrate-postgres
./bin/pug-migrate-nats
./bin/pug-migrate-clickhouse
```

`pug migrate` runs the three in that order and stops at the first that fails. Each reads its store from `DATABASE_URL`, `NATS_URL` or `CLICKHOUSE_URL`, and `postgres migrate` and `clickhouse migrate` apply every pending migration.

To roll back, use the per-store command: `--direction down --num N` undoes N steps. **Always pass `--num`**: `--direction down` on its own rolls back every migration, dropping every table. `pug migrate`, the standalone binaries and the migrate images only migrate up and take no flags.

`nats migrate` creates or updates the JetStream streams and consumers to match `schema/nats/`, with the replica count from `NATS_STREAM_REPLICAS` (see [NATS JetStream HA](#nats-jetstream-ha)). It never deletes a stream or consumer.

## 3. Run

Run **one process per role**. On a small single box, `pug dev` can run them all in one process instead; see [Single node](#single-node).

### API server

```bash
./bin/pug server        # or ./bin/pug-server, or the pug-server image
```

Listens on `:3000` (`PUG_SERVER_PORT`), behind a [TLS-terminating load balancer](#tls-termination).

### Workers

Run each of the **6 workers** as its own process, plus `demo` only for a public demo. For high ingest, add events-worker replicas ([Horizontal scaling](#horizontal-scaling)).

| Process | Unified command | Standalone binary | Docker `CMD` |
|---------|-----------------|-------------------|--------------|
| Events | `pug worker events` | `pug-worker-events` | `workers/events` |
| Email | `pug worker email` | `pug-worker-email` | `workers/email` |
| Compliance | `pug worker compliance` | `pug-worker-compliance` | `workers/compliance` |
| Profile identify | `pug worker profile identify` | `pug-worker-profile-identify` | `workers/profile/identify` |
| Profile alias | `pug worker profile alias` | `pug-worker-profile-alias` | `workers/profile/alias` |
| Profile upsert | `pug worker profile upsert` | `pug-worker-profile-upsert` | `workers/profile/upsert` |
| Demo _(optional)_ | `pug worker demo` | `pug-worker-demo` | `workers/demo` |

### Scheduled jobs

Four jobs run on a schedule. Each runs one pass and exits, non-zero when the pass failed, so a scheduler has to run it: a Kubernetes CronJob, a systemd timer, or cron. Nothing starts them for you, `pug dev` included.

| Job | Unified command | Standalone binary / image | Schedule | If it never runs |
|-----|-----------------|---------------------------|----------|------------------|
| Project purge | `pug cron purge` | `pug-cron-purge` | Every 5 minutes | A deleted project is hidden and its keys stop working, but its data stays. The server logs an error at startup while a deletion has been open for over a day. |
| Usage metering | `pug cron usage` | `pug-cron-usage` | Hourly | The dashboard shows event usage as unknown. Nothing else reads it. |
| Retention | `pug cron retention` | `pug-cron-retention` | Daily | Event history is kept past its retention length. By default there is no length, so nothing changes. |
| Expired tokens | `pug cron expired-tokens` | `pug-cron-expired-tokens` | Daily | Expired refresh and email-action tokens and dead MCP grants pile up in Postgres. |

`cron retention` deletes each org's ClickHouse event history older than its retention length, a whole month at a time, and applies a shorter length, the first one set included, only after 30 days. With billing off, the length is `PUG_RETENTION_DAYS`, which keeps everything when empty, the default. Until `PUG_RETENTION_ENABLED=true`, the job only logs what it would delete.

Each pass holds a Postgres advisory lock, so a run that overlaps the previous one exits 0 without doing the work. On Kubernetes, set `concurrencyPolicy: Forbid` and an `activeDeadlineSeconds` shorter than the interval; Pug Cloud uses 270 seconds for purge, 3000 for usage and retention, and 600 for expired tokens. Give the jobs the server's environment; `cron usage` also reads `PUG_USAGE_RESCAN_DAYS`, and `cron retention` `PUG_RETENTION_ENABLED` ([Configuration](/self-hosting/configuration#scheduled-jobs)).

`pug-cron-billing-reconcile` and `pug-cron-billing-meter` belong to Pug Cloud's billing, which is off by default; a self-hosted instance doesn't schedule them.

### Single node

`pug dev` (alias `pug start`) runs the server and the workers in one process. It suits a low-volume single box; you can't scale or restart its processes independently. Schedule the [jobs](#scheduled-jobs) alongside it, and see [`dev`](/self-hosting/cli#dev) for which workers it starts.

## 4. Production hardening

### TLS termination

`pug server` speaks plain HTTP. Terminate TLS at a load balancer (nginx, Caddy, AWS ALB, Cloudflare) that proxies to port 3000, and don't expose port 3000 to the internet: API keys, passwords and session tokens would cross it in plaintext.

### Secrets management

Inject these from a secrets manager (Vault, AWS Secrets Manager, Kubernetes Secrets, ...), not an unencrypted file:

| Secret | Variable | Notes |
|--------|----------|-------|
| JWT signing key | `PUG_JWT_SECRET_KEY` | `openssl rand -hex 32`. Rotating it signs nobody out - see [Ending sessions](#ending-sessions). |
| Email provider encryption key | `PUG_EMAIL_PROVIDER_SECRET_KEY` | `openssl rand -base64 32`. Required for per-org email providers. |
| SSO connection encryption key | `PUG_SSO_SECRET_KEY` | `openssl rand -base64 32`. Required for org SSO connections. A new key can't read the stored client secrets. |
| Sign-in provider secrets | `PUG_CONFIG_FILE` | The file holds each provider's `clientSecret`. Mount it from a secret, read-only. |
| Email provider credentials | `PUG_RESEND_API_KEY`, or `AWS_SECRET_ACCESS_KEY` for SES | SES can use an IAM role instead of a static key. |
| Turnstile secret | `PUG_TURNSTILE_SECRET_KEY` | Only when [Turnstile](/self-hosting/authentication#turnstile) is on. |
| Postgres credentials | `DATABASE_URL` | Use a dedicated Pug database user. The first migration creates the `moddatetime` extension, so create it beforehand as a superuser, or run that migration with a role allowed to. |
| ClickHouse credentials | `CLICKHOUSE_URL` | In the URL: `clickhouse://user:pass@host:9000/pug`. |
| Dragonfly credentials | `REDIS_URL` | In the URL: `redis://:pass@host:6379`. |
| NATS credentials | `NATS_URL`, `NATS_CREDS_FILE`, or `NATS_JWT` + `NATS_SEED` | User/password or token auth goes in `NATS_URL`. For JWT auth, mount a `.creds` file and set `NATS_CREDS_FILE`, or set the user JWT and seed, which win over the file. An NKey seed on its own isn't supported. Add TLS per your NATS deployment. |

### Ending sessions

A dashboard session is a refresh token in Postgres, on a 90-day sliding expiry; the JWT it mints lasts 24 hours. The dashboard trades its refresh token for a new pair whenever a JWT is rejected, so rotating `PUG_JWT_SECRET_KEY` alone signs nobody out. To sign everyone out, revoke the refresh tokens, then rotate the key:

```sql
update refresh_tokens set revoked_at = now() where revoked_at is null;
```

Neither step ends [MCP sign-ins](/mcp#sign-in). To end those too:

```sql
update mcp_grants set revoke_time = now() where revoke_time is null;
```

### CORS origins

Set `PUG_CORS_ORIGINS` to your dashboard's exact origin (e.g. `https://app.example.com`), or several, comma-separated with no spaces. Unset, it's `*`: any website can call the dashboard API from a visitor's browser, sign-in still works, and only a warning at startup shows it. The SDK ingest services accept any origin regardless.

### NATS JetStream HA

Run a **3-node NATS cluster** with JetStream on each node; a single node is a single point of failure for all ingestion. Start each with `--jetstream --store_dir /data/nats`, give the cluster a name and configure its routes. Then set `NATS_STREAM_REPLICAS=3` and re-run `pug nats migrate`, so losing a node loses no data.

`pug nats migrate` refuses a replica count above 1 when the server reports no cluster name. It also owns the stream settings: one changed by hand (`nats stream edit`) is reset on its next run.

### ClickHouse HA and storage

A single ClickHouse node suits low-to-medium volumes. Beyond that:

- **Replication**: the migrations create plain `MergeTree`-family tables with no `ON CLUSTER`, so a self-managed replicated cluster isn't supported yet. For fault tolerance, use ClickHouse Cloud, which replicates every table, or back up the node's storage.
- **Tiered storage**: an S3-compatible object store as the cold tier for long retention.
- **`ulimits`**: `nofile` >= 262144 on every node (required).

### Horizontal scaling

The **events worker** is the bottleneck at high ingest. Its replicas share one durable JetStream consumer, so each one you add takes a share of the stream. The other workers carry lighter streams; start them at one replica each and scale as needed.

### Monitoring

Point `OTEL_EXPORTER_OTLP_ENDPOINT` at your collector's **OTLP/gRPC** endpoint (usually port 4317) to export traces, metrics and logs; with none set, Pug logs to stdout as text. Export is plaintext unless `OTEL_EXPORTER_OTLP_INSECURE=false`, which a TLS endpoint needs. OTLP over HTTP isn't supported, so a backend that accepts only HTTP needs an OpenTelemetry Collector in between. See [Telemetry](/self-hosting/configuration#telemetry).

## Health checks

The server and every worker except `demo` serve liveness and readiness probes, for your orchestrator or load balancer:

| Process | Endpoint | Port | Behavior |
|---------|----------|------|----------|
| `pug server` | `GET /healthz` | `:3000` | **Liveness**: `200 ok`, or `503` once its NATS connection has closed for good, as a repeated NATS auth error does -> restart. A connection that is reconnecting stays live. |
| `pug server` | `GET /readyz` | `:3000` | **Readiness**: `200 ok`, or `503 draining` once the server is shutting down. |
| Each worker | `GET /healthz` | `:8090` | **Liveness**: `200 ok` while its consume loops run, `503` with the failing worker's reason if one is wedged -> restart. |
| Each worker | `GET /readyz` | `:8090` | **Readiness**: `200 ok` once its consumers exist and NATS is connected, `503` otherwise -> gate rollouts. |

The server's probes don't check Postgres, ClickHouse, Dragonfly or NATS reachability. Instead, `pug server` exits at startup when one of them is unreachable.

Point your load balancer's health check at `/readyz`. On SIGTERM the server keeps serving for `PUG_SERVER_DRAIN_DELAY` (default `5s`) while `/readyz` fails, so make the delay longer than the balancer takes to notice. In-flight requests then get 10 seconds and the telemetry flush 10 more: the termination grace period must cover the delay plus 20 seconds.

Workers serve their probes on `PUG_WORKER_HEALTH_ADDR` (default `:8090`, `off` to disable) once their first JetStream consumer exists. A probe sent earlier gets a refused connection rather than a `503`, so give the probes a startup allowance (`initialDelaySeconds`, or a `startupProbe`). Give each worker process on a host its own port: one that can't bind logs an error and keeps processing, with no probes. `pug dev` turns off the worker probes and the drain delay.

Probe the backing services on their own endpoints:

| Service | Health endpoint |
|---------|----------------|
| NATS | `GET http://<host>:8222/healthz` |
| ClickHouse | `GET http://<host>:8123/ping` |
| PostgreSQL | `pg_isready` / TCP connect to `:5432` |
| Dragonfly | `redis-cli ping` |

## Further reading

- [Dashboard](/self-hosting/dashboard): build and serve the UI
- [Connect your SDKs](/self-hosting/connect-sdks): point your apps at this instance
- [CLI reference](/self-hosting/cli): every `pug` command and flag
- [Configuration](/self-hosting/configuration): all environment variables

Source: https://docs.pug.sh/self-hosting/deployment/index.mdx
