sightbox/playbook/CICD_PLAYBOOK.md

348 lines
17 KiB
Markdown

# CI/CD Playbook: Gitea → Dokploy
How to wire any Docker-Compose-deployed project to auto-deploy from a self-hosted Gitea repo
through Dokploy, gated behind a test suite instead of deploying on every push blindly. **Parts 1
and 2 are project-agnostic** — copy them into any other repo that needs this. **Part 3 is the
Sightbox-specific worked example.**
⚠ **Honesty check on this doc's confidence level:** every other guide in `playbook/` carries
"confirmed the hard way" notes because it was built by breaking the real thing and fixing it live.
**Update, first real run:** the ungated route (A) — Gitea OAuth connection, manual webhook,
Enable Submodules, Compose Path — has now been walked end-to-end for real against
`git.bettertend.net` + a live Dokploy VPS for this project's own `sightbox` repo (see Part 3).
Real gotchas came out of it, all folded in below: three separate Dokploy compose-validator
rejections (`include:`, long-form `env_file:`, `depends_on`'s `required:` — Part 3 step 3, Known
Pitfalls) and `code/` being deleted and re-cloned on every AutoDeploy, which broke the original
`backend/.env` file-based approach outright — fixed by retiring that file for plain
`environment:` vars and by building/pushing `backend-billing`'s image ahead of time instead of
building it on the VPS (`CLAUDE.md`, `INSTALLATION_PLAYBOOK.md` Stage 1). **Still unconfirmed:**
the gated route (B) — Gitea Actions, the `act_runner`, and the test-then-deploy workflow in Part
1 Stages 2-3 and Part 2 Stages 2/5/6 — remains built from Dokploy's and Gitea's own docs, not yet
run live. Treat those specific sections as the starting plan still, not a proven runbook.
---
## Architecture: the one decision that actually matters
Gitea and Dokploy are two independent systems that don't know about each other by default. There
are two ways to connect them, and they're easy to combine by accident in a way that silently
defeats the entire point of gating:
```
push to a branch
│
├─(A)─► Gitea's push webhook ──► Dokploy's webhook URL ──► deploys IMMEDIATELY
│ (no test gate — whatever
│ was pushed goes out)
│
└─(B)─► Gitea Actions workflow (runs on a self-hosted act_runner)
1. checkout
2. run the test suite
3. only if step 2 succeeds → POST to Dokploy's application.deploy API
──► deploys, but only on green tests
```
**Wire exactly one of these per application, never both.** If (A)'s webhook is attached to a
Gitea repo *and* (B)'s workflow also calls the deploy API, every push deploys twice — once
instantly regardless of test outcome, once again after tests finish — which makes the gate
theater, not a gate. (A) is simpler and fine for a low-stakes personal project where you don't
care about gating. (B) is the one to use for anything a client or a paying user depends on —
it's a small amount of extra wiring (Part 2, Stage 5-6 below) for a real guarantee: nothing
reaches production without the test suite passing first.
---
## Part 1 — One-time, per-host setup
Do this once per VPS that will run Gitea and/or Dokploy — not once per project.
### Stage 1 — Install Gitea
Standard self-hosted install (Docker image, binary, or package — whichever this host already
uses). Skip if a Gitea instance already exists; every project just gets a new repo on it.
### Stage 2 — Enable Gitea Actions instance-wide
Gitea Actions is off by default. In `app.ini`:
```ini
[actions]
ENABLED = true
```
Restart Gitea. This only turns Actions on *instance*-wide — each individual repo still needs it
enabled separately (Part 2, Stage 2).
### Stage 3 — Register a runner (`act_runner`)
Gitea Actions needs at least one runner to actually execute jobs — enabling Actions alone doesn't
give you compute. Get a registration token from **Site Administration → Actions → Runners →
Create New Runner** (instance-level, so this one runner serves every repo — a repo- or
org-scoped token also exists if you want isolation instead).
```yaml
# docker-compose.yml, run alongside Gitea (or on a separate box)
services:
runner:
image: gitea/act_runner:latest
environment:
GITEA_INSTANCE_URL: "https://<your-gitea-host>"
GITEA_RUNNER_REGISTRATION_TOKEN: "<token from above>"
GITEA_RUNNER_NAME: "primary"
volumes:
- ./runner-data:/data
- /var/run/docker.sock:/var/run/docker.sock # see gotcha below
```
⚠ **Gotcha (from Gitea's own docs, not yet hit live):** the docker socket mount is what lets a
workflow run `docker`/`docker compose` commands inside a job — most test suites for a
Docker-based project need it. It also means anything that can push a workflow file to a repo this
runner serves gets effectively root-equivalent access to this host's Docker daemon. Only point
this runner at repos you trust the committers of, or scope it to one org/repo via a scoped
registration token instead of the instance-wide one.
### Stage 4 — Install Dokploy
```
curl -sSL https://dokploy.com/install.sh | sh
```
On a fresh Ubuntu VPS this installs Docker if missing and brings up Dokploy's own stack
(dashboard on port 3000, Traefik for reverse-proxying every app it deploys, automatic Let's
Encrypt TLS per domain). Skip if Dokploy already runs on this host — every project just becomes a
new Project/Application inside it.
---
## Part 2 — Per-project setup
Do this once for every project that wants this pipeline.
### Stage 1 — Push the repo to Gitea
`git init` (if not already), first commit, create a repo on the Gitea instance, push. Real
secrets (`.env`, API keys, tenant config) must already be gitignored with `.env.example`
placeholders checked in instead — never rely on Gitea's or Dokploy's access controls alone to
keep a secret out of history; keep it out of git entirely.
### Stage 2 — Enable Actions for this specific repo
Repo → **Settings → Actions → Enable Repository Actions**. Off by default per repo even with
Stage 2 of Part 1 done instance-wide — the two settings are independent.
### Stage 3 — Create the Application/Compose service in Dokploy
Two ways to connect the repo, pick based on how much you want gating (see Architecture above):
- **Manual webhook (recommended default):** create the Application (or "Compose" service, for a
`docker-compose.yml`-based project) in Dokploy pointing at the repo by URL/branch. Dokploy's
Deployments tab shows a **Webhook URL** — copy it. **Only add this to Gitea's repo Webhooks
page if you're going the ungated route (A).** If you're gating deploys behind tests (B), skip
adding the webhook entirely — the Actions workflow in Stage 5 triggers the deploy instead.
- **OAuth App integration (nicer repo picker, one known rough edge):** Gitea → create an OAuth2
application, "Confidential Client" checked, redirect URI from Dokploy's Gitea provider screen;
paste the Client ID/Secret into Dokploy. This lets Dokploy's UI browse and pick repos directly.
⚠ As of writing there's an open Dokploy issue where this path can fail to auto-create the
webhook due to a missing `write:repository` OAuth scope — if repos aren't showing up or
webhooks aren't appearing after connecting, fall back to the manual webhook method above rather
than debugging the OAuth scope.
### Stage 4 — Set secrets in Dokploy, never in git
Application → Environment tab. Every value that's currently in this project's `.env`/gitignored
config gets typed in here directly — Dokploy injects them into the container at deploy time. This
is a manual, one-time-per-secret step; nothing here is touched by CI.
Also grab, for Stage 5: a Dokploy **API token** (profile settings) and this application's **ID**
(call the `project.all` API endpoint once and read it off the response, or copy it from the
Application's own URL in the dashboard).
### Stage 5 — Write the gated workflow
`.gitea/workflows/ci.yml` in the repo:
```yaml
name: test-and-deploy
on:
push:
branches: [main]
jobs:
test:
runs-on: docker
steps:
- uses: actions/checkout@v4
- name: Run test suite
run: <this project's actual test command, e.g. pytest backend/tests/>
- name: Deploy to Dokploy
if: success()
run: |
curl -X POST "https://<dokploy-host>/api/application.deploy" \
-H "Authorization: Bearer ${{ secrets.DOKPLOY_API_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{"applicationId": "${{ secrets.DOKPLOY_APP_ID }}"}'
```
`DOKPLOY_API_TOKEN` and `DOKPLOY_APP_ID` go into this repo's own Gitea **Settings → Actions →
Secrets** — not committed, same principle as every other secret in this pipeline.
### Stage 6 — Confirm exactly one trigger is live
Re-check Gitea's repo Webhooks page: if you went the gated route (B), it should have **no**
Dokploy webhook registered — the workflow above is the only path to a deploy. If you deliberately
want the ungated route (A) instead, the workflow's deploy step in Stage 5 shouldn't exist. Having
both wired is the single most likely mistake with this setup — it doesn't error, it just quietly
double-deploys and makes the test gate meaningless.
---
## Part 3 — Worked example: this project (Sightbox)
This project's test suite already exists and passes (98/98 in `backend/tests/` at last check).
Applying the pattern above here, concretely:
1. `git init` at the `sightbox/` root, first commit. The existing `.gitignore` already excludes
`.env`, `backup/.env`, and `backend/tenants.json` — confirm those three stay untracked in the
first `git status` before the first commit, since this is the one step where a mistake here
ships a real secret into history permanently.
2. Create a `sightbox` repo on Gitea, push, enable Actions on it (Part 2, Stage 2).
3. In Dokploy, create a **Compose** application pointing at this repo, **Compose Path
`./docker-compose.dokploy.yml`** — ⚠ not `./docker-compose.yml`. Confirmed the hard way on a
real deploy: Dokploy's own compose validator rejects `docker-compose.yml`'s top-level
`include:` directive ("Additional property include is not allowed" — matches two open,
unresolved Dokploy issues, [#3116](https://github.com/Dokploy/dokploy/issues/3116) and
[#1727](https://github.com/Dokploy/dokploy/issues/1727)). `docker-compose.dokploy.yml` is the
same deployment pre-flattened by `./generate-dokploy-compose.sh` — regenerate it any time
`docker-compose.yml` changes, never hand-edit it. Also enable this Application's **Enable
Submodules** toggle (confirmed working against our `frappe_docker` mirror submodule — see
`.gitmodules`). Set environment variables to match `.env.example`/`backup/.env.example` —
`SIGHTBOX_DATA_DIR`, `SENTRY_DSN`, `ENVIRONMENT=production`, `BACKEND_BILLING_IMAGE`/`_TAG`,
and so on. `tenants.json` and `backup/.env` are files, not env vars — those get created
directly on the VPS's filesystem per `INSTALLATION_PLAYBOOK.md` Stage 9/10; nothing about
adding CI/CD changes that. `backend/.env` no longer exists at all — confirmed the hard way that
Dokploy's AutoDeploy deletes and re-clones the git checkout on every deploy, so a file living
inside it (as `env_file:` pointed at) never survived to the next one; those four values are now
plain `environment:` vars in `docker-compose.yml`, same mechanism as everything else here.
Similarly, `backend-billing` no longer builds on the VPS at all — `./backend/build.sh` builds
and pushes it to the registry beforehand (Installation Playbook Stage 1), same
build-locally-ship-the-tested-artifact pattern as the branding image.
4. `.gitea/workflows/ci.yml`'s test step becomes:
```yaml
- name: Run backend test suite
run: docker compose run --rm backend pytest tests/ -q
```
(or however the test suite is actually invoked in this repo's own tooling — match what's
already run manually today, don't invent a new test-running mechanism for CI.)
5. Go the gated route (B) — this is exactly the kind of project (client billing logic) the
Architecture section above says is worth the extra wiring. No webhook goes into Gitea's repo
settings; the workflow's deploy step is the only trigger.
---
## Part 4 — Minimal example: a plain Flask app, start to finish
Everything above is scoped to Sightbox's own, fairly involved setup. This part is the opposite —
the leanest possible walkthrough of the whole pattern, meant as a copy-paste starting point for
any other small app. It deliberately goes the **ungated route (A)**: a hello-world app has nothing
worth gating a deploy behind, so there's no test step and no Gitea Actions workflow at all — just
a push webhook straight to Dokploy. Add Part 2's Stages 2/4/5/6 back in once this app actually has
a test suite worth trusting.
### The app itself
```
my-flask-app/
├── app.py
├── requirements.txt
├── Dockerfile
└── docker-compose.yml
```
```python
# app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello from my-flask-app"
@app.route("/health")
def health():
return {"status": "ok"}
```
```
# requirements.txt
flask
gunicorn
```
```dockerfile
# Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
```
```yaml
# docker-compose.yml
services:
web:
build: .
restart: unless-stopped
```
No `ports:` mapping needed — Dokploy's Traefik routes to the container directly by its internal
port (set in the Domains step below), not via a host port publish.
### Push it to Gitea and connect Dokploy — the ungated way
1. `git init`, first commit, push to a new repo on Gitea.
2. In Dokploy, create a **Compose** application pointing at this repo, branch `main`.
3. Deployments tab → copy the **Webhook URL** → Gitea repo → **Settings → Webhooks → Add
Webhook** → paste it, trigger on **Push Events**, save. That's the entire CI/CD step for the
ungated route — no `.gitea/workflows/` file, no runner involvement at all. Every push to `main`
now redeploys automatically.
### Point it at a subdomain of a domain you own
1. **DNS, first, before anything in Dokploy:** at your domain registrar/DNS provider, add an
**A record** for the subdomain (e.g. `app` on `example.com`, giving `app.example.com`) pointing
at your Dokploy server's IP address. This has to actually propagate before the next steps will
work — don't debug Dokploy if this hasn't resolved yet (`dig app.example.com` from any machine
to check).
2. In Dokploy, the application's **Domains** tab → add a domain:
- **Host**: `app.example.com`
- **Container Port**: `8000` (matches this app's `EXPOSE`/gunicorn bind above)
- **HTTPS**: on
- **Certificate**: `letsencrypt`
3. For a Compose-type app specifically, Dokploy expresses this as Traefik Docker labels applied to
the service at deploy time, not a live config change — **redeploy after saving the domain
settings**, once. Docker Compose doesn't hot-reload domain/label changes the way an
`Application`-type deploy might.
That's the complete loop for a small app with nothing to gate: push → Gitea webhook → Dokploy
redeploys → reachable at `https://app.example.com`.
---
## Known pitfalls, gathered before ever running this once
- **Double-deploy from wiring both (A) and (B)** — see Part 2, Stage 6. Check for this first if a
deploy seems to happen "too early," before tests could plausibly have finished.
- **Docker socket access on the runner is root-equivalent** — see Part 1, Stage 3's gotcha.
- **Repo-level Actions is off by default even with instance-wide Actions enabled** — Part 2,
Stage 2 is easy to forget after Part 1, Stage 2 is already done once.
- **OAuth-based Gitea↔Dokploy connection has an open scope bug as of writing** — prefer the manual
webhook (or no webhook, for the gated route) over debugging it.
- **Dokploy's compose validator rejects `include:`** — confirmed on a real deploy, not just read
about: `docker-compose.yml`'s `include:` directive (used to pull in `frappe_docker`'s files
without duplicating them) fails Dokploy's own pre-flight validation with "Additional property
include is not allowed," before `docker compose` itself ever runs. Point Dokploy's Compose Path
at `docker-compose.dokploy.yml` instead (generated via `./generate-dokploy-compose.sh`) — see
Part 3, step 3.
- **Secrets never travel through git, ever** — every environment variable and credential file in
this pipeline is either typed into Dokploy's UI directly or created by hand on the VPS. If a
step in this doc ever seems to imply committing one, that's a mistake in the doc, not a
shortcut to take.