# Describe your app

> Stagd reads stagd.yaml and your compose file to know which parts make up your app and which ones get a URL.

Stagd reads your app's description at the exact commit it previews. Every service in your compose file becomes a component of the preview.

- With a **`stagd.yaml`** (or `.stagd.yaml`) at the root of your repository, that file decides: where the compose file is, which services get a URL, and how images are made.
- Without one, Stagd finds `compose.yaml` at the root (or `compose.yml`, `docker-compose.yaml`, `docker-compose.yml`) and reads a few labels on its services. That's enough for most apps.

> **Before you start** Turn previews on for the repository: `stagd repos enable owner/name`. Stagd never reads a repository's code until you do.

## Previews as code

There's no settings page in Stagd where you click your app together. What a preview runs is described in your repository, next to the code it runs, and Stagd reads it from the commit it previews.

- **A pull request can change its own preview.** Add a worker service, a second URL or mail capture in the same pull request as the code that needs it, and that pull request's preview already runs with it. You see the change working before it reaches main.
- **Reviewed like code.** A change to how previews run shows up in the diff, gets reviewed and leaves a history. `git blame` tells you why a port changed.
- **Every branch gets the right setup.** An old branch keeps the setup it was written for; a revert puts the old one back. Nothing in a UI drifts from what the code expects.
- **Nothing to set up twice.** A new repository, a fork or a teammate gets the same previews from the same file. `stagd validate` checks it before you push, or in CI.
- **Agents can do it too.** A coding agent that adds a service can describe it for previews in the same change, without an account in a UI.

One thing is never in the repository: who may open previews. A pull request mustn't be able to open up its own preview, so access is set in Stagd, with `stagd preview policy`.

## The short way: labels in compose.yaml

A few labels tell Stagd what reviewers should open:

```yaml
services:
  web:
    build: .
    ports: ["3000:3000"]
    labels:
      dev.stagd.ingress: "true"
      dev.stagd.primary: "true"
  api:
    build: ./api
    expose: ["8080"]
    labels:
      dev.stagd.ingress: api
  db:
    image: postgres:17
    volumes: ["pgdata:/var/lib/postgresql/data"]
volumes:
  pgdata: {}
```

| Label | Meaning |
|---|---|
| `dev.stagd.ingress` | Give the service a URL. `"true"` names it after the service; any other value is the name, e.g. `api`. Names are lower-case letters, digits and dashes, and one letter or at least three: two-letter names would make URLs DNS reserves |
| `dev.stagd.primary` | `"true"` on the URL the pull request links to. Not needed when only one service has a URL |
| `dev.stagd.port` | Which port the URL goes to, when the service listens on several |
| `dev.stagd.ignore` | `"true"` leaves the service out of previews, e.g. local admin tools |

The preview above gets two URLs: `https://pr-42-web-acme.stagd.run` for `web`, and `https://api--pr-42-web-acme.stagd.run` for `api`. `db` has no URL; the other services reach it as `db`, as they do locally.

## stagd.yaml

Use `stagd.yaml` when the compose file isn't at the root, when you'd rather keep Stagd's settings out of it, or when an image is built somewhere else. When it lists ingresses, labels are ignored. The [stagd.yaml reference](https://stagd.dev/docs/reference/stagd-yaml.md) lists every setting.

```yaml
version: 1
app:
  compose: deploy/compose.preview.yaml
ingress:
  site: { service: web, port: 3000, primary: true }
  api: { service: api, port: 8080 }
build:
  web: { context: ., dockerfile: Dockerfile, target: prod }
  api: { image: ghcr.io/acme/api }   # built in your CI: use it, don't build it
services:
  mail: {}                           # capture the mail the app sends
```

| Setting | Meaning |
|---|---|
| `app.compose` | The compose file, as a path from the repository's root. Helm charts, kustomize and Kubernetes manifests come later |
| `ingress` | URLs: a name, the service and the port. One is `primary: true` when there are several |
| `build` | How a service's image is made: `context` (with `dockerfile`, `target`, `args`) to build it, or `image` to use one built elsewhere |
| `services` | Services Stagd runs and wires in for you: `mail`, `sms`, and the databases `postgres`, `mysql`, `mariadb` and `mongodb` (see below). Off unless listed |
| `wait` | GitHub checks on the commit to pass before it deploys, e.g. the workflow that pushes its images (see below) |
| `registries` | Logins for pulling private images, their passwords from Stagd's secrets (see below) |
| `lifecycle` | How long previews stay awake and live, instead of your org's setting (see below) |
| `previews` | When pull requests get previews: on demand, always, or while they have a label (see below) |
| `compute` | Which of your compute connections previews run on, by its name on Settings → Compute; your default when left out. Changing it moves an existing preview on its next deploy, without what was in the old instance |

Who may open previews isn't set here: a pull request can't change its own preview's access. That's set in Stagd with `stagd preview policy`.

## Your app's services

What Stagd runs next to your app (mail capture, text messages, tracing, its databases) is wired into **your app's own services**, and only those: they get the variables that point at it, and wait for it to be ready. A service is your app's own when its image comes from your repository:

- **A compose `build:`**: built from your repository.
- **An entry under `build` in `stagd.yaml`**: built from a `context`, or a prebuilt `image` your CI pushes, such as `api: { image: "ghcr.io/acme/api:sha-${STAGD_SHA}" }`.

A service with only `image:` in the compose file, such as `postgres:17`, `redis:7` or a vendor's image, is a stock image and is left alone: no variables, no waiting. To wire one in anyway, list it under `build` in `stagd.yaml` with its `image`.

A value your compose file sets for one of these variables wins over Stagd's. A bare one doesn't: `DATABASE_URL:` (or `- DATABASE_URL`) takes what the environment has, as compose does, and in a preview Stagd is that environment, so it gets Stagd's.

## Capture mail

Turn on mail capture, and everything the app sends by email stays in the preview, for reviewers to read. Nothing is delivered. Sign-up confirmations, password resets and invites become testable without a real inbox.

```yaml
version: 1
services:
  mail: {}
```

- **What runs:** the preview gets a [Mailpit](https://mailpit.axllent.org) next to your services. If your compose file already runs Mailpit or MailHog, Stagd uses that one instead of starting a second.
- **How your app finds it:** the services built from your repository get `SMTP_HOST`, `SMTP_PORT` (1025), `SMTP_URL`, `MAIL_HOST` and `EMAIL_HOST`, pointing at it. A value your compose file sets wins; `stagd validate` tells you which services keep their own.
- **Where to read it:**
  - on the preview's Mail tab in the dashboard, which previews have only with `mail` on
  - with `stagd preview mail <id>`
  - in Mailpit itself, at the preview's `mail--` URL

  The pull request's comment says how many emails were captured.
- **Who can read it:** only members of your org, signed in to Stagd, even when the preview is open to anyone. Captured mail holds password-reset links and invite tokens.
- **How long it lasts:** the mail lives and dies with the preview. It survives sleep; wake the preview to read it.

Mail sent through **Resend** or **Amazon SES** is caught too, with no change to your app: their SDKs read where to send from the environment, and Stagd points them at `stagd-mock` in the preview (`RESEND_BASE_URL` and `RESEND_API_URL`; `AWS_ENDPOINT_URL_SES` and `AWS_ENDPOINT_URL_SESV2`). It answers as the vendor would and hands each email to the preview's inbox. The AWS SDKs still want credentials, though nothing checks them. Mail sent through other providers' APIs (SendGrid, Postmark, Mailgun) isn't caught yet: in previews, send it over SMTP.

### Catch only some ways

Without settings, every way of sending mail Stagd catches is pointed at the preview, and ways it learns later are caught too, so a preview never sends real mail by surprise. Name the ways under `catch` to catch only those, such as SMTP alone for an app whose own SES calls the mock doesn't answer:

```yaml
services:
  mail: { catch: [smtp] }   # smtp, resend, ses
```

| Name | Your services get |
|---|---|
| `smtp` | `SMTP_HOST`, `SMTP_PORT`, `SMTP_URL`, `MAIL_HOST`, `EMAIL_HOST` |
| `resend` | `RESEND_BASE_URL`, `RESEND_API_URL` |
| `ses` | `AWS_ENDPOINT_URL_SES`, `AWS_ENDPOINT_URL_SESV2` |

Mail sent a way that isn't caught leaves the preview for real, and a way Stagd learns later isn't caught either. With `catch: [smtp]` the preview runs only Mailpit, with no `stagd-mock` next to it. To catch nothing, turn mail off with `mail: false`. `skip`, which `catch` replaces, still works: it names the ways left alone.

On your own machine, [outbox](https://github.com/stagdhq/outbox), the open-source mock previews run, does the same next to a Mailpit: `outbox serve --smtp localhost:1025`, or its image `ghcr.io/stagdhq/outbox` in your compose file.

In a script or CI job, wait for an email and read it:

```sh
stagd preview mail <id> --wait --to kari@acme.test --subject confirm
```

## Databases

Stagd can run your preview's database itself, on a volume of its own, and start it from a seed: a dump of your data, restored once when the preview is made.

```yaml
version: 1
services:
  postgres:
    version: "18"           # 16, 17, 18 (the default) or 19
    seed: app-anonymized    # a seed on the Seeds page, or an https URL of a dump
    extensions: [vector, pg_trgm]
```

| Database | Versions | Your app gets | A seed is |
|---|---|---|---|
| `postgres` | 16, 17, **18**, 19 | `DATABASE_URL` | `pg_dump`: SQL, custom or tar format |
| `mysql` `beta` | **8.4**, 9 | `MYSQL_URL`, `DATABASE_URL` | SQL from `mysqldump` |
| `mariadb` `beta` | 11.4, **11.8** | `MYSQL_URL`, `DATABASE_URL` | SQL from `mariadb-dump` or `mysqldump` |
| `mongodb` `beta` | 7.0, **8.0** | `MONGODB_URI`, `MONGO_URL` | `mongodump --archive` |

The default version is in bold; write versions in quotes. Every kind of seed can be compressed with gzip, zstd or xz, or not: Stagd tells by the file.

- **How your app finds it:** the services built from your repository get the URLs above, and wait for the database before they start. A value your compose file sets wins. With two databases, the first in the list keeps `DATABASE_URL`.
- **Seeds:** a seed is a dump in your own blob store: connect Azure Blob Storage, an S3 bucket (Amazon S3, R2, MinIO) or Google Cloud Storage under Settings → Integrations ([Connect integrations](https://stagd.dev/docs/guides/connect-integrations.md)), then add the seed on the Seeds page, or with `stagd seeds add app-anonymized --from <integration> --path dumps/`. A pattern such as `dumps/*.dump` picks the newest file it matches, so a nightly dump is used without anyone changing anything (`*` and `?` don't cross a `/`). A path ending in `/` picks the newest file under it, passing over files without an extension, such as a `latest` file a backup job writes beside its dumps. Previews download the file through Stagd: your store's credentials never reach the preview. Take the personal data out before the dump goes to your storage: [Seed data without personal data](https://stagd.dev/docs/guides/seed-data.md).
- **Once, when the preview is made:** new commits and sleep keep the data. Only a preview that has to be made again starts over from its seed, and its events say why ([Compute providers](https://stagd.dev/docs/concepts/compute.md#databases-and-seeds)). Errors in a dump, such as roles your preview hasn't got, are shown in the database's logs and the rest restores. A seed that can't be downloaded, or that makes no tables, fails the preview and says why.
- **An Azure SAS token ends:** Home warns admins 30 days before it does, and once it has. Give the integration a new token under Settings → Integrations.

### Postgres extensions

List them under `extensions`, by the name `CREATE EXTENSION` takes. Each is made in the database when it's created, before the seed restores, so a dump that uses one restores whole.

- **Postgres's own** (`pg_trgm`, `pgcrypto`, `uuid-ossp`, `citext`, `hstore`, `pg_stat_statements` and the rest of contrib) are always there.
- **Any other the [PostgreSQL apt repository](https://wiki.postgresql.org/wiki/Apt) packages:** `vector` (pgvector), `postgis` and its family, `pg_cron`, `timescaledb`, `h3`, `hypopg`, `pg_partman`, `pgaudit` and more. Stagd runs the official Debian image of your version and installs them as the database starts, in seconds. A name it finds no package for stops the start and says so.
- **Those that load at start**, such as `pg_cron`, `pg_stat_statements` and `timescaledb`, are preloaded for you; `pg_cron` runs in your preview's database.

Extensions are made when the database is new. Added to a preview that already has its data, they're installed, and your app's own `CREATE EXTENSION` makes them. The first one that needs installing also moves the database from Postgres's Alpine image to Debian's, which sort text differently: destroy the preview to start it over, so its indexes are built the new way.

Beta means it works and we use it, and it may still change. Tell us what breaks.

## Files: a fork of your blob storage

A preview with a copy of lab's database has rows pointing at lab's files. Without them, its images and attachments are broken; with lab's storage writable, the preview writes into lab. A fork gives it both: every file of the real container or bucket, and what it writes kept to itself.

```yaml
version: 1
services:
  postgres:
    seed: lab-nightly
  azure_blob:
    from: [lab-files]     # an Azure Blob Storage integration on Settings → Integrations
```

`s3: { from: [lab-uploads] }` does the same for S3 buckets: Amazon S3, R2, MinIO and others that speak S3.

- **How it works:** Stagd runs [blobfork](https://github.com/stagdhq/blobfork) in the preview, in front of an emulator (Azurite, or Floci for S3). A read the fork can't answer falls through to the real container, so nothing is copied up front, however big it is. Writes and deletes stay in the preview.
- **How your app finds it:** with `azure_blob`, the services built from your repository get `AZURE_STORAGE_CONNECTION_STRING`; with `s3`, `AWS_ENDPOINT_URL_S3`, and a key unless they set their own. A value your compose file sets wins, and an app that reads another name maps it there, e.g. `AZ_BLOBSTORE_URL: ${AZURE_STORAGE_CONNECTION_STRING}`.
- **The real ones stay as they are:** the fork reads them with the integration's read-only SAS or key, which reaches blobfork's container in the preview but never your app's services.
- **Each keeps its name:** a container or bucket is called the same in the fork, so settings that name it work unchanged.
- **In a browser too:** the SAS and presigned URLs your app hands a browser work, at the preview's `blob--` and `bucket--` addresses.

Beta: S3 clients need path-style addressing (`forcePathStyle`). The [reference](https://stagd.dev/docs/reference/stagd-yaml.md#azure_blob-and-s3) has the details.

## Catch text messages

Text messages the app sends through Amazon SNS can be caught the same way, for the preview's Messages tab, instead of reaching a phone:

```yaml
version: 1
services:
  sms: {}
```

- **How your app's SNS finds it:** the services built from your repository get `AWS_ENDPOINT_URL_SNS`, pointing at `stagd-mock` in the preview. The AWS SDKs read it; your code doesn't change. A value your compose file sets wins.
- **What's caught:** messages published to a phone number. Publishing to a topic isn't caught, and fails in the preview rather than reaching anyone.
- **Where to read them:** the preview's Messages tab, which previews have only with `sms` on; `stagd preview texts <id>`; or `get_texts` for coding agents through `stagd mcp`. Only members of your org can, as with mail.

In a script or CI job, wait for a code and read it:

```sh
stagd preview texts <id> --wait --to 4791234567
```

## Images your CI builds

When your own CI builds and pushes the images, Stagd can use them instead of building. Name each image for the commit, and tell Stagd what to wait for before it deploys:

```yaml
version: 1
build:
  web: { image: "ghcr.io/acme/web:sha-${STAGD_SHA}" }
  api: { image: "ghcr.io/acme/api:sha-${STAGD_SHA}" }
wait:
  checks: [build-images]             # the workflow or job that pushes them
  timeout: 30m                       # the default
registries:
  ghcr.io: { username: acme-bot, password: "${GHCR_TOKEN}" }
```

- **Images named for the commit:** `${STAGD_SHA}` is the pull request's head commit, `${STAGD_SHORT_SHA}` its first 7 characters, `${STAGD_PR_NUMBER}` the pull request's number. Tag by commit rather than by pull request: a `pr-42` tag still holds the last commit's image until the new one is pushed.
- **`wait.checks`:** GitHub checks on the commit that must pass first: a workflow's name, or one of its jobs. Until they have, the preview waits, and its pull request comment and check say what for. One failing fails the preview at once, with a link to the run. A new push waits for the new commit's checks.
- **`wait.timeout`:** how long to wait for them, up to 2h. Then the preview fails; push again, or comment `/stagd deploy` once they're done.
- **Without GitHub checks**, give the image its own wait: `web: { image: "…:sha-${STAGD_SHA}", wait: 20m }` keeps trying to pull it for up to 20 minutes.
- **Private images:** `registries` logs in before pulling. The password is a secret you add in Stagd, written here as `${NAME}`; a password written in the file is refused.

## When pull requests get previews

By default a pull request gets a preview when someone who can push to the repository comments `/stagd deploy`. Stagd's comment on each pull request lists the other commands: `/stagd stop`, `/stagd start`, `/stagd destroy` and `/stagd status`.

```yaml
version: 1
previews: always                     # every pull request gets one
```

Or let a GitHub label decide:

```yaml
version: 1
previews:
  label: preview                     # the label's name, always given
```

- **Adding the label** deploys the pull request's preview, and pushes deploy it again while the label is on.
- **Removing it** tears the preview down, as `/stagd destroy` does.
- **The commands still work, and keep the label in step:** `/stagd deploy` puts the label on, `/stagd destroy` takes it off.
- **A pull request opened with the label on** gets a preview straight away.
- Create the label in the repository first. Like the commands, it's for people who can label pull requests, and pull requests from forks never get previews.

## How long previews run

A preview sleeps after 45 minutes without visits, and is torn down 24 hours after its last commit. An org admin can change both for the whole org, in Settings → Previews or with `stagd preview policy --sleep-after 2h --expire-after 36h`. A repository can set its own in `stagd.yaml`, which wins:

```yaml
version: 1
lifecycle:
  sleep_after: 2h                    # asleep after this long without visits: 45m to 24h
  expire_after: 36h                  # torn down after this long without a new commit: 1h to 48h
```

Leave one out to keep the org's. Both apply from the preview's next deploy. A sleeping preview wakes when someone opens its link, and a push starts its lifetime over.

## Check before you push

```sh
stagd validate
```

It sends `stagd.yaml` and your compose file to Stagd, which checks them with exactly the rules previews use, and lists what previews would run. It exits non-zero when there's something to fix, so you can run it in CI.

When a setting doesn't do what you expect, `stagd validate --explain` also prints `stagd.yaml` as Stagd reads it: shorthands written out and every default filled in, ready to paste back.

## Start order, one-shots and health checks

Stagd starts your services in the order `depends_on` gives, honouring its conditions on every kind of compute:

```yaml
services:
  migrate:
    build: .
    command: ["bun", "run", "migrate"]
    depends_on:
      db: { condition: service_healthy }
  web:
    build: .
    depends_on:
      migrate: { condition: service_completed_successfully }
      db: { condition: service_healthy }
    healthcheck:
      test: ["CMD", "curl", "-fsS", "http://localhost:3000/healthz"]
```

| Condition | What Stagd does |
|---|---|
| `service_started` (or the short form, `depends_on: [db]`) | Starts it after the other has started |
| `service_healthy` | Starts it once the other's health check passes |
| `service_completed_successfully` | The other is a **one-shot**, such as migrations or seeding: it runs once, counts as done when it exits 0, and what waits for it starts only then. On Kubernetes it runs as a Job, tried up to 6 times. If it fails, the preview fails and its logs say why |

Stagd's own databases (`services.postgres` and the others) are waited for the same way: your services start once the database, and its seed, are ready.

- **Health checks:** a service's `healthcheck` is used: its `test` (a string, `CMD` or `CMD-SHELL`). Its timing isn't: Stagd checks every 5 seconds and gives up after a few minutes, so `interval`, `timeout`, `retries` and `start_period` are ignored. On Kubernetes the check is its readiness probe. As with compose, a service others wait on with `service_healthy` needs a `healthcheck`; one without counts as healthy only on Kubernetes, so give it one.
- **A preview is live** when every service is running and healthy, and every one-shot has finished.
- **`restart` isn't read:** services keep running, restarted when they stop, and one-shots are never restarted.

## What Stagd leaves out

Previews run built images, not your working copy, so some things that only make sense on your machine are left out. Stagd notes each one in the preview's timeline:

- bind mounts like `./src:/app/src`
- services that only run with a compose profile
- `env_file`, `secrets`, `configs`, `networks`, `deploy`, `container_name`, `logging` and `ulimits`

`extends`, `network_mode`, `privileged` and device access aren't supported; a preview with them fails and says which service to change. Service names need lower-case letters, digits and dashes, because they're also how services find each other.

## When something's wrong

The preview fails with what to fix, on the pull request and in `stagd preview get`. For example:

```
compose.yaml: several services have a public URL: mark the one the pull request should link to with dev.stagd.primary: "true"
```
