I wanted a CI/CD setup like the one GitHub Actions gives me, but running entirely on a small server at home: push to main, run the tests, build a Docker image, deploy it and serve it publicly over HTTPS. I didn’t want to open router ports, pay for a container registry or manage TLS certificates by hand.
This post covers the whole build, step by step. I deploy two independent apps with their own pipelines: a Laravel backend and a React frontend. I’ve included every command and config file, and the mistakes I made along the way, so you can follow the steps without getting stuck where I did.
About the examples. Replace these placeholders with your own values throughout:
Placeholder Meaning example.comYour domain, managed in Cloudflare git-server.example.comGitea’s public hostname cicd-laravel.example.comThe Laravel app’s public hostname cicd-react.example.comThe React app’s public hostname 192.168.1.227The server’s LAN IP 192.168.1.0/24Your LAN subnet myuserYour Gitea username
Table of contents
- Architecture and decisions
- The server
- Docker
- PostgreSQL on the host
- Gitea
- Cloudflare Tunnel and Cloudflare Access
- Pushing code from your PC through Cloudflare Access
- The Gitea Actions runner (host mode)
- Pipeline 1: Laravel
- Pipeline 2: React
- Nightly backups
- Branches and environments: dev, test and prod
- Recommended next steps
- Troubleshooting
- Wrap-up
1. Architecture and decisions
flowchart LR
dev["Developer PC<br/>git push"]
browser["Browser"]
subgraph CF["Cloudflare"]
access["Cloudflare Access<br/>email PIN or service token"]
edge["Cloudflare edge<br/>HTTPS termination"]
end
subgraph SRV["Ubuntu server (one machine)"]
cfd["cloudflared<br/>systemd service"]
gitea["Gitea<br/>localhost:3000"]
runner["gitea-runner<br/>host mode"]
docker["Docker Engine"]
lar["Laravel container<br/>127.0.0.1:8081"]
react["React container<br/>127.0.0.1:8082"]
pg[("PostgreSQL 18<br/>on the host")]
bk[("/backup<br/>second disk")]
end
dev -->|"git-server.example.com"| access
access --> edge
browser -->|"cicd-laravel / cicd-react<br/>.example.com"| edge
edge <-->|"outbound tunnel<br/>no open ports"| cfd
cfd --> gitea
cfd --> lar
cfd --> react
runner -->|"poll jobs + checkout<br/>localhost:3000"| gitea
runner -->|"docker build<br/>docker compose up"| docker
docker --- lar
docker --- react
lar -->|"host.docker.internal:5432"| pg
pg -.->|"nightly pg_dump"| bk
gitea -.->|"nightly gitea dump"| bk
There are three separate flows in this picture:
- Code in: your PC pushes to Gitea through Cloudflare Access (section 7).
- Build and deploy: the runner, on the same machine, picks up the job from Gitea over
localhost, then builds and starts containers on the local Docker Engine (sections 8–10). - Traffic in: visitors reach Cloudflare, and
cloudflaredforwards each hostname to its own local port. Nothing on the server listens on a public port.
| Decision | What I chose | Why |
|---|---|---|
| Where apps run | Docker containers | Every app brings its own runtime (PHP 8.5, nginx…), so nothing app-specific is installed on the host |
| Git server and CI | Gitea + Gitea Actions | Self-hosted, lightweight, and its workflow syntax is almost the same as GitHub Actions |
| How Gitea is installed | Native binary + systemd | Simple to update and back up, and it doesn’t depend on Docker |
| Runner mode | Host mode (self-hosted:host) | Jobs run directly on the server, so docker build and docker compose up act on the same Docker that serves the apps |
| Image registry | None | Images are built where they run. A commit-SHA tag on every image makes rollbacks possible |
| Public access | Cloudflare Tunnel | No open inbound ports, HTTPS handled by Cloudflare, and no reverse proxy needed: each hostname maps to one local port |
| Protecting Gitea | Cloudflare Access | Email one-time PIN for the web UI, plus a service token for git clients |
| Database | PostgreSQL on the host | One instance for all apps, simple to back up |
| Secrets | .env files on the server | Never committed and never inside the image |
| Migrations | Run automatically on every deploy | Before the new container starts |
My hardware
| Part | Spec |
|---|---|
| CPU | Intel N150 (4 cores) |
| RAM | 16 GB |
| OS disk | 512 GB NVMe |
| Backup disk | 128 GB eMMC, mounted at /backup |
| OS | Ubuntu 26.04 |
A low-power mini PC handles this setup comfortably.
2. The server
My starting point was a fresh Ubuntu 26.04 install that I could reach over SSH on the LAN at 192.168.1.227. Everything below runs on that machine unless a step says otherwise.
sudo apt update && sudo apt upgrade -y
sudo apt install -y git curl unzip
3. Docker
I installed Docker Engine from Docker’s official apt repository, following https://docs.docker.com/engine/install/ubuntu/. I didn’t use Ubuntu’s docker.io package. The official repository provides the current Engine plus the Compose v2 plugin (docker compose, with a space), which the pipelines rely on.
# Docker's GPG key and repository
sudo apt install -y ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
sudo tee /etc/apt/sources.list.d/docker.sources > /dev/null <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
Components: stable
Signed-By: /etc/apt/keyrings/docker.asc
EOF
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
Docker’s install page is the authoritative source. If the commands above ever differ from it, follow the page.
Start Docker at boot and check that it works:
sudo systemctl enable docker.service containerd.service
sudo docker run --rm hello-world
docker version --format '{{.Server.Version}}' # I got 29.10.0
docker compose version # I got v5.8.0
Optionally, let your own user run docker without sudo (log out and back in afterwards):
sudo usermod -aG docker $USER
⚠️ Membership in the
dockergroup is effectively root access. Anyone who can rundockercan mount the host’s filesystem into a container. Only add users you’d also trust withsudo.
4. PostgreSQL on the host
I run one PostgreSQL instance directly on the host and share it between apps. Each app gets its own database and role.
sudo apt install -y postgresql
psql --version # I got PostgreSQL 18.6
ls /etc/postgresql/ # → 18
systemctl status postgresqlshowsactive (exited). That’s normal:postgresql.serviceis only a wrapper, and the real server runs aspostgresql@18-main.
4.1 Allow connections from the LAN and from containers
By default, PostgreSQL listens only on localhost. Two kinds of clients need to reach it:
- pgAdmin on my PC (LAN)
- The Laravel container. Its connections arrive from a Docker network address (
172.16.0.0/12), not fromlocalhost.
Edit /etc/postgresql/18/main/postgresql.conf:
listen_addresses = '*'
Why
*and not a list of IPs? Containers reach the host through Docker’s bridge interface. If PostgreSQL starts before Docker has created that interface, binding to the bridge IP fails. Access is controlled inpg_hba.confinstead.
Add these lines to the end of /etc/postgresql/18/main/pg_hba.conf:
# LAN admin access (pgAdmin)
host all all 192.168.1.0/24 scram-sha-256
# Docker containers (default bridge + compose networks)
host all all 172.16.0.0/12 scram-sha-256
sudo systemctl restart postgresql
sudo ss -tlnp | grep 5432 # 0.0.0.0:5432, not 127.0.0.1:5432
🔴 Don’t leave out the Docker-subnet line. Without it, the first deploy fails during migration with
no pg_hba.conf entry for host "172.x.x.x", even though pgAdmin works fine.
4.2 An admin role and the app’s database
The built-in postgres superuser has no password and can only log in locally, so pgAdmin can’t use it. I created a separate admin role instead:
sudo -u postgres psql -c "CREATE ROLE sa WITH LOGIN SUPERUSER PASSWORD 'a-strong-password';"
Then the Laravel role and database. I did this in pgAdmin; the SQL is:
CREATE ROLE laravel_dba WITH LOGIN PASSWORD 'another-strong-password';
CREATE DATABASE laravel OWNER laravel_dba;
🔴 The app role must OWN its database. Since PostgreSQL 15, ordinary roles can no longer create tables in the
publicschema by default. If the database belongs tosaorpostgres,php artisan migratefails withpermission denied for schema public. Making the app role the owner fixes that. Also give the app role no superuser,CREATEDBorCREATEROLErights.
I didn’t enable a firewall in my lab. If you do (recommended for production, see section 13), allow port 5432 from both the LAN and 172.16.0.0/12.
5. Gitea
I installed Gitea as a native binary with a systemd service, following the official “Installation from binary” guide on https://docs.gitea.com. I used Gitea Enterprise 28.4.0, but the steps are the same for the community edition.
5.1 Install the binary, user and directories
# Download the linux-amd64 binary for the current version from the Gitea docs/download page
wget -O gitea https://dl.gitea.com/gitea/<version>/gitea-<version>-linux-amd64
chmod +x gitea
sudo mv gitea /usr/local/bin/gitea
# System user that runs Gitea
sudo adduser --system --shell /bin/bash --gecos 'Git Version Control' \
--group --disabled-password --home /home/git git
# Data and config directories
sudo mkdir -p /var/lib/gitea/{custom,data,log}
sudo chown -R git:git /var/lib/gitea/
sudo chmod -R 750 /var/lib/gitea/
sudo mkdir /etc/gitea
sudo chown root:git /etc/gitea
sudo chmod 770 /etc/gitea # writable during the web installer; locked down afterwards
5.2 systemd service
/etc/systemd/system/gitea.service:
[Unit]
Description=Gitea (Git with a cup of tea)
After=network.target
After=postgresql.service
[Service]
Type=simple
User=git
Group=git
WorkingDirectory=/var/lib/gitea/
ExecStart=/usr/local/bin/gitea web --config /etc/gitea/app.ini
Restart=always
RestartSec=2s
Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/gitea
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now gitea
5.3 The web installer
Open http://192.168.1.227:3000 and fill in the form:
| Field | Value | Notes |
|---|---|---|
| Database type | SQLite3 | Fine for a small instance. PostgreSQL is also an option, since it’s already running. |
| Server domain | git-server.example.com | |
| SSH server domain | git-server.example.com (or the LAN IP, see below) | |
| Gitea Base URL | https://git-server.example.com/ | The public HTTPS address. See the warning below. |
| HTTP port | 3000 | |
| Administrator account settings | Expand this section and create the admin | If you leave it collapsed, no admin is created |
🔴 The sign-in loop. I set the Base URL to
https://git-server.example.com/and then tried to sign in athttp://192.168.1.227:3000. Every login silently returned to the sign-in page, with no error message.Cause: when
ROOT_URLstarts withhttps://, Gitea marks its session cookie as Secure, and a browser won’t store a Secure cookie on a plain-HTTP page.Fix: don’t change the Base URL. Finish the Cloudflare Tunnel (section 6) and sign in through
https://git-server.example.com. If you need LAN access in the meantime, set[session] COOKIE_SECURE = falseinapp.initemporarily, and remove it afterwards.
After the installer, lock the config down:
sudo chmod 750 /etc/gitea
sudo chmod 640 /etc/gitea/app.ini
5.4 Settings in /etc/gitea/app.ini
These are the settings that matter for this setup. Restart Gitea after any change (sudo systemctl restart gitea).
[server]
DOMAIN = git-server.example.com
ROOT_URL = https://git-server.example.com/
SSH_DOMAIN = git-server.example.com
[service]
DISABLE_REGISTRATION = true ; nobody can sign up on a public instance
[actions]
ENABLED = true ; on by default in recent versions; check if "Actions" is missing from the admin menu
- Changing the domain later means editing
DOMAIN,ROOT_URLandSSH_DOMAINhere, and the tunnel hostname in Cloudflare. Keep the trailing/onROOT_URL, and don’t add:3000to it. - Enable 2FA on your admin account after the first sign-in (Settings → Security).
Cloning over SSH: Cloudflare Tunnel doesn’t carry plain SSH (port 22) unless every client also runs
cloudflared. I clone and push over HTTPS from outside, and use SSH only on the LAN, if at all.
6. Cloudflare Tunnel and Cloudflare Access
6.1 The tunnel
A Cloudflare Tunnel is an outbound connection from cloudflared on the server to Cloudflare’s edge. Visitors connect to Cloudflare, and Cloudflare sends their requests down the tunnel. No inbound ports are opened on the router, and Cloudflare handles HTTPS.
In the Cloudflare Zero Trust dashboard → Networks → Tunnels → Create a tunnel → type Cloudflared:
- Name the tunnel, for example
all-in-one. - Choose Debian / Ubuntu, 64-bit. The dashboard shows commands that (a) add Cloudflare’s apt repository and install
cloudflared, and (b) runsudo cloudflared service install <token>. Run them on the server. This installscloudflaredas a systemd service, with its configuration managed from the dashboard. - Add a public hostname for Gitea:
| Subdomain | Domain | Type | URL |
|---|---|---|---|
git-server | example.com | HTTP | localhost:3000 |
cloudflared --version # I got 2026.11.1
systemctl status cloudflared # active (running)
You can now sign in at https://git-server.example.com.
Each app later gets its own hostname pointing to its own local port, which is why no reverse proxy (nginx, Traefik…) is needed in front of the apps.
6.2 Cloudflare Access in front of Gitea
A public Git server is a target. I put Cloudflare Access in front of Gitea, so nobody reaches Gitea’s login page without first passing Cloudflare.
Zero Trust → Access → Applications → Add an application → Self-hosted, with hostname git-server.example.com. It gets two policies:
| Policy | Action | Include | Used by |
|---|---|---|---|
| Humans | Allow | Emails → your address (login method: One-time PIN) | Your browser: Cloudflare emails you a code before showing Gitea |
| Git clients | Service Auth | Service Token → the token created below | git push/pull from your PC |
Create the service token under Zero Trust → Access → Service credentials → Service Tokens → Create. Copy the Client ID and Client Secret right away, because the secret is shown only once.
🔴 The token must be in a policy whose action is Service Auth, not Allow. If it’s in an Allow policy, Cloudflare still redirects git to the email login page, and
git pushprints a page of HTML.
⚠️ Service tokens expire (one year by default). Note the date. When the token expires, pushes and pulls suddenly fail.
Only Gitea sits behind Access. The two app hostnames are public on purpose.
7. Pushing code from your PC through Cloudflare Access
Every git request to git-server.example.com now has to pass two checks: Cloudflare Access (the service token) and then Gitea (your username and access token).
sequenceDiagram
autonumber
participant PC as Developer PC (git)
participant CA as Cloudflare Access
participant T as cloudflared on server
participant G as Gitea (localhost:3000)
PC->>CA: HTTPS request + CF-Access-Client-Id / Secret headers
alt Token valid and in a Service Auth policy
CA->>T: forward through the tunnel
T->>G: plain HTTP to localhost:3000
G-->>PC: 401, Gitea asks for credentials
PC->>G: retry with username + Gitea access token
G-->>PC: push accepted
else Headers missing, or token only in an Allow policy
CA-->>PC: 302 redirect to the login page, git prints HTML
end
If you see HTML in git’s output, the request was stopped at Cloudflare (the else branch above). If you get an authentication error, the request got through Cloudflare and Gitea rejected the credentials.
7.1 Send the service token headers with every git request
On your PC (I’m on Windows, but the commands are the same elsewhere):
git config --global --add http.https://git-server.example.com/.extraHeader "CF-Access-Client-Id: <client-id>.access"
git config --global --add http.https://git-server.example.com/.extraHeader "CF-Access-Client-Secret: <client-secret>"
- The setting is scoped to the Gitea URL, so the headers are never sent to any other host.
--addis required. Without it, the second command replaces the first header instead of adding a second one.- The Client ID ends in
.access. Copy the whole value.
Check the result:
git config --global --get-all http.https://git-server.example.com/.extraHeader
7.2 A Gitea access token as your git password
With 2FA enabled, Gitea won’t accept your account password for git over HTTPS. Create a personal access token under Gitea → Settings → Applications → Generate New Token, with scope write:repository. Use it as the password when git asks for credentials.
7.3 Create the repository, then push
Gitea doesn’t create repositories on push by default. Create an empty repository in the web UI first (no README, no .gitignore), then push:
git remote add origin https://git-server.example.com/myuser/cicd-laravel.git
git push -u origin main
# Username: myuser
# Password: <the Gitea access token>
🔴 Do the first push from a regular terminal, not the IDE. My first push from VS Code’s Git integration failed with a page of HTML. The same command in Windows Terminal worked. On the first push, Git Credential Manager has to ask for your username and token, and VS Code’s credential prompt doesn’t always show it for a non-GitHub host. Once the credential is stored, pushing from VS Code works too.
To check whether Cloudflare is blocking you, send a request with and without the headers:
curl -s -o /dev/null -w "%{http_code}\n" https://git-server.example.com/ # 302 → Access login (expected)
curl -s -o /dev/null -w "%{http_code}\n" \
-H "CF-Access-Client-Id: <client-id>.access" \
-H "CF-Access-Client-Secret: <client-secret>" \
https://git-server.example.com/ # 200 → token accepted
8. The Gitea Actions runner (host mode)
The runner is the process that executes workflows. It polls Gitea for jobs, runs them, and reports the results back. Gitea never contacts the runner: the runner always makes the connection, which is why it can use a local address.
sequenceDiagram
participant Dev as Developer
participant G as Gitea
participant R as gitea-runner (host mode)
participant D as Docker Engine
participant App as App container
Dev->>G: git push to main
G->>G: queue job for label self-hosted
loop every few seconds
R->>G: any jobs? (localhost:3000)
end
G-->>R: job + workflow steps
R->>G: actions/checkout via localhost:3000
R->>D: docker build (tests run inside the build)
R->>D: docker compose up -d
D->>App: recreate container from the new :latest image
R->>App: curl health check on 127.0.0.1
R-->>G: step logs and final status
G-->>Dev: green or red in the Actions tab
8.1 Docker mode or host mode
The runner’s labels decide where a job’s steps run:
| Label | Steps run… | Consequence |
|---|---|---|
ubuntu-latest:docker://… (default) | Inside a fresh container per job | Isolated, but building and deploying images requires mounting the host’s Docker socket into the job container |
self-hosted:host (my choice) | Directly on the server, as the runner’s user | Simple: docker build and docker compose up act on the host’s Docker directly |
Host mode suits a single server that both builds and runs the apps. The trade-off is that every tool a workflow uses (git, docker, node, curl) must be installed on the host, and the runner’s user is in the docker group, which is effectively root. Only let trusted people push to repositories with Actions enabled.
8.2 Node.js: required in host mode, and it must be system-wide
🔴 The Gitea docs don’t mention this, because it doesn’t apply in Docker mode. JavaScript actions such as
actions/checkoutrun withnodefrom the host. Docker-mode job images already include Node. In host mode, if Node is missing, the very first step fails withexec: "node": executable file not found in $PATH.
🔴 Install Node system-wide, not per user. My first attempt used the Node.js website’s recommended fnm installer, which needs
unzip. That worked in my own shell, butsudo -u gitea-runner node -vprintedcommand not found. fnm and nvm install Node under your home directory and add it toPATHfrom your shell profile. A systemd service account never loads your profile, and on Ubuntu it can’t read your home directory anyway (it’s mode750).
sudo apt install -y nodejs
node -v # v22.22.1
Node is used only to run actions. The apps are built with their own Node and PHP versions inside Docker images.
8.3 Install and register the runner
I followed https://docs.gitea.com/runner/installation/binary/ and installed the gitea-runner binary (v5.2.0) to /usr/local/bin/gitea-runner.
A dedicated system user, with access to Docker:
sudo useradd --system --home-dir /var/lib/gitea-runner --create-home gitea-runner
sudo usermod -aG docker gitea-runner
Default config file:
sudo mkdir -p /etc/gitea-runner
sudo gitea-runner config init -c /etc/gitea-runner/config.yaml
sudo chown gitea-runner /etc/gitea-runner/config.yaml
Registration token: in Gitea, open Site Administration → Actions → Runners → Create new Runner and copy the token. An instance-level runner serves every repository, so both apps share it. (Organisation- and repository-level runners are also available under their own Settings → Actions → Runners.)
Register:
sudo -u gitea-runner -H bash -c 'cd /var/lib/gitea-runner && gitea-runner register \
-c /etc/gitea-runner/config.yaml \
--instance http://localhost:3000 \
--token <registration-token> \
--name all-in-one \
--labels self-hosted:host \
--no-interactive'
Each part matters:
--instance http://localhost:3000, not the public URL. The public URL is behind Cloudflare Access, which would block the runner. A local address also keeps CI traffic inside the server and keeps CI working during an internet outage.--labels self-hosted:hostselects host mode. Workflows target it withruns-on: self-hosted.cdinside thebash -c, asgitea-runner. Registration writes a credentials file called.runnerinto the current directory.
🔴 My first attempt was
cd /var/lib/gitea-runnerin my own shell, followed bysudo -u gitea-runner gitea-runner register …. Thecdfailed silently (the directory is private togitea-runner), so registration ran in my home directory and ended withfailed to save runner config: open .runner: permission denied. Changing directory as the runner user fixes it.
The registration token can be reused until you reset it. Treat it like a password, and reset it if it leaks.
8.4 Run the runner as a systemd service
/etc/systemd/system/gitea-runner.service:
[Unit]
Description=Gitea Actions runner
After=network-online.target docker.service gitea.service
Wants=network-online.target docker.service
[Service]
Type=simple
User=gitea-runner
Group=gitea-runner
WorkingDirectory=/var/lib/gitea-runner
Environment=HOME=/var/lib/gitea-runner
ExecStart=/usr/local/bin/gitea-runner daemon -c /etc/gitea-runner/config.yaml
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now gitea-runner
sudo journalctl -u gitea-runner -n 20
WorkingDirectory is what lets the daemon find the .runner file created during registration.
8.5 Verify
In Gitea, Site Administration → Actions → Runners should list all-in-one as Idle with the label self-hosted. “Idle” means it’s connected and waiting. Then confirm the tools work as the runner user:
sudo -u gitea-runner docker ps # no "permission denied"
sudo -u gitea-runner -H bash -lc 'node -v'
sudo -u gitea-runner git --version
8.6 One more consequence of Cloudflare Access: checkout
Gitea gives every job its public ROOT_URL as the server address, so actions/checkout would clone from https://git-server.example.com and get Cloudflare’s login page. Every workflow in this post therefore sets the local address:
- uses: actions/checkout@v4
with:
github-server-url: http://localhost:3000
9. Pipeline 1: Laravel
The Laravel app is a standard Laravel 13 project using Pest. Both composer.lock and package-lock.json are committed. It uses Vite + Tailwind for its pages, and its tests run on in-memory SQLite (phpunit.xml).
What happens on every push to main
- Checkout from
http://localhost:3000. - Test:
docker build --target test .builds the front-end assets, installs dev dependencies and runs Pest. A failing test fails the build, and nothing is deployed. - Build: the production image, tagged
cicd-laravel:<commit-sha>andcicd-laravel:latest. - Migrate:
php artisan migrate --forcein a throwaway container from the new image, before the running app is replaced. - Deploy:
docker compose up -drecreates the container from the new image, thenphp artisan optimizeruns. - Health check: curl Laravel’s
/uproute. The pipeline goes red if the app doesn’t respond. - Clean up: remove untagged images. SHA-tagged images are kept for rollback.
flowchart TD
A["git push to main"] --> B["Checkout<br/>from localhost:3000"]
B --> C{"Test<br/>docker build --target test"}
C -- "a test fails" --> X["❌ Pipeline stops<br/>running site untouched"]
C -- "tests pass" --> D["Build image<br/>cicd-laravel:SHA + :latest"]
D --> E{"Migrate<br/>compose run --rm app<br/>php artisan migrate --force"}
E -- "migration fails" --> X
E -- "ok" --> F["Deploy<br/>compose up -d<br/>php artisan optimize"]
F --> G{"Health check<br/>curl /up"}
G -- "no 200 within ~30 s" --> Y["❌ Pipeline red<br/>investigate or roll back"]
G -- "200 OK" --> H["Prune untagged images"]
H --> I["✅ New version live"]
Every check that can fail runs before the running container is replaced, except the final health check. Failing tests and failing migrations leave the live site exactly as it was.
Files involved
| File | Where | Committed? |
|---|---|---|
Dockerfile | repo root | ✅ |
.dockerignore | repo root | ✅ |
bootstrap/app.php (trusted proxies) | repo | ✅ |
.gitea/workflows/deploy.yml | repo | ✅ |
compose.prod.yaml | server: /opt/apps/cicd-laravel/ | ❌ server only |
.env (production secrets) | server: /opt/apps/cicd-laravel/ | ❌ never |
9.1 Dockerfile
# syntax=docker/dockerfile:1
# ---- build frontend assets ----
FROM node:22-alpine AS assets
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY . .
RUN npm run build
# ---- install PHP deps without dev packages ----
FROM composer:2 AS vendor
ENV COMPOSER_CACHE_DIR=/tmp/composer-cache
WORKDIR /app
COPY composer.json composer.lock ./
RUN --mount=type=cache,target=/tmp/composer-cache \
composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
COPY . .
RUN composer dump-autoload --optimize --no-dev
# ---- test: the build fails if tests fail (run with --target test) ----
FROM dunglas/frankenphp:1-php8.5 AS test
RUN install-php-extensions pdo_sqlite pdo_pgsql intl zip pcntl
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
ENV COMPOSER_CACHE_DIR=/tmp/composer-cache
WORKDIR /app
# Dependencies first: this layer is reused until composer.lock changes.
COPY composer.json composer.lock ./
RUN --mount=type=cache,target=/tmp/composer-cache \
composer install --no-interaction --prefer-dist --no-scripts --no-autoloader
COPY . .
COPY --from=assets /app/public/build /app/public/build
RUN composer dump-autoload \
&& cp .env.example .env \
&& php artisan key:generate \
&& php artisan test --compact
# ---- runtime (must stay the last stage) ----
FROM dunglas/frankenphp:1-php8.5
RUN install-php-extensions pdo_pgsql intl zip opcache pcntl
WORKDIR /app
ENV APP_ENV=production APP_DEBUG=false
COPY --from=vendor /app /app
COPY --from=assets /app/public/build /app/public/build
RUN rm -rf public/hot tests phpunit.xml .env.example
EXPOSE 80
CMD ["frankenphp", "php-server", "--root", "public/", "--listen", ":80"]
| Stage | Base image | What it does |
|---|---|---|
assets | node:22-alpine | npm ci + npm run build → public/build |
vendor | composer:2 | Production Composer dependencies with an optimized autoloader |
test | dunglas/frankenphp:1-php8.5 | Dev dependencies + php artisan test. Built only with --target test |
| (final) | dunglas/frankenphp:1-php8.5 | PostgreSQL driver + opcache. Copies vendor and assets output, removes test files, serves public/ on port 80 |
How the stages feed each other:
flowchart LR
ctx["Build context<br/>repo minus .dockerignore"]
assets["assets<br/>node:22-alpine<br/>npm ci + npm run build"]
vendor["vendor<br/>composer:2<br/>install --no-dev"]
test["test<br/>frankenphp php8.5<br/>dev deps + Pest"]
final["final image<br/>frankenphp php8.5<br/>serves public/ on :80"]
ctx --> assets
ctx --> vendor
ctx --> test
assets -->|"public/build"| test
assets -->|"public/build"| final
vendor -->|"app + vendor/"| final
docker build --target test builds assets and test. A plain docker build builds assets, vendor and final, and skips test because nothing in the final image depends on it.
Details worth understanding:
- The production stage must be the last stage. A plain
docker build(with no--target) builds the last stage. Theteststage is built only when requested with--target test. - Manifests are copied before the code.
composer.json/composer.lockandpackage*.jsonare installed beforeCOPY . .. An ordinary code change then reuses the cached dependency layers, and dependencies are only reinstalled when a lock file changes. My first version of this file hadCOPY . .first, which meant every push downloaded all dependencies again. RUN --mount=type=cachekeeps npm’s and Composer’s download caches on the server between builds.- Tests need no database server.
phpunit.xmlsetsDB_CONNECTION=sqliteandDB_DATABASE=:memory:, which is why the test stage installspdo_sqlite.cp .env.example .env+key:generategives the tests an app key. - Why FrankenPHP? It’s a single image that serves PHP directly (Caddy plus PHP), with no separate PHP-FPM and nginx containers to coordinate.
- The test step reuses work. The production build in the next step reuses the
assetsandvendorlayers from the test build.
9.2 .dockerignore
.git
.gitea
node_modules
vendor
public/build
public/hot
.env
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
database/*.sqlite
# Secrets
.env.*
!.env.example
auth.json
storage/*.key
# AI / agent tooling
.claude
.mcp.json
.ai
AGENTS.md
CLAUDE.md
boost.json
.codex
.cursor
# Editors / OS
.idea
.vscode
.zed
.nova
.editorconfig
.DS_Store
Thumbs.db
# Dev and test leftovers
storage/pail
storage/app/private/*
storage/app/public/*
.phpunit.cache
.phpunit.result.cache
*.log
_ide_helper.php
# Docker files themselves
Dockerfile
.dockerignore
README.md
.envand.env.*are excluded, so your local secrets never end up in an image..env.exampleis re-included with!.env.example, because the test stage copies it.tests/andphpunit.xmlare not excluded, because the test stage needs them. The final stage deletes them.- Leaving out
vendor,node_modulesand.gitkeeps the build context small, and stops Windows-built dependencies from getting into a Linux image.
9.3 Trust Cloudflare’s proxy headers: bootstrap/app.php
Cloudflare handles HTTPS, so requests reach the container as plain HTTP. Without this setting, Laravel generates http:// URLs and redirects:
->withMiddleware(function (Middleware $middleware): void {
$middleware->trustProxies(at: '*');
})
Trusting * is safe here because the container port is bound to 127.0.0.1 (see 9.5), so only cloudflared on the same machine can send it requests. If the port were reachable from the LAN, any device could forge X-Forwarded-* headers.
9.4 The workflow: .gitea/workflows/deploy.yml
name: Test & Deploy
on:
push:
branches: [main]
env:
APP_DIR: /opt/apps/cicd-laravel
IMAGE: cicd-laravel
jobs:
deploy:
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@v4
with:
github-server-url: http://localhost:3000 # avoid Cloudflare Access
- name: Test
run: docker build --target test .
- name: Build image
run: docker build -t $IMAGE:${{ gitea.sha }} -t $IMAGE:latest .
- name: Migrate database
working-directory: ${{ env.APP_DIR }}
run: docker compose -f compose.prod.yaml run --rm app php artisan migrate --force
- name: Deploy
working-directory: ${{ env.APP_DIR }}
run: |
docker compose -f compose.prod.yaml up -d
docker compose -f compose.prod.yaml exec -T app php artisan optimize
- name: Health check
run: curl -fsS --retry 10 --retry-delay 3 --retry-all-errors http://127.0.0.1:8081/up
- name: Clean up untagged images
run: docker image prune -f
runs-on: self-hostedmatches the runner’s label.- No secrets in Gitea. The runner is on the same machine as the deploy, so there’s no registry login and no SSH step. Production secrets live in
/opt/apps/cicd-laravel/.env. - Migrate before
up -d.compose run --rmstarts a temporary container from the new:latestimage (with the same.envand network), runs the migrations, and removes it. If the migrations fail, the old container keeps serving and the pipeline stops. The new code never runs against the old schema. exec -Tturns off TTY allocation, which a CI job doesn’t have.php artisan optimizecaches config, routes and views at runtime, inside the container, where the production.envvalues are available. Doing this duringdocker buildwould cache an environment with no secrets in it.- The health check retries for about 30 seconds, giving the container time to start, and fails the run if
/upnever returns 200. docker image prune -fremoves only untagged images. The:<sha>tags stay and act as rollback points.
9.5 Server: the deploy folder and compose.prod.yaml
The deploy folder belongs to the runner user, because the workflow cds into it and runs compose there:
sudo mkdir -p /opt/apps/cicd-laravel
sudo chown gitea-runner:gitea-runner /opt/apps/cicd-laravel
sudo nano /opt/apps/cicd-laravel/compose.prod.yaml
name: cicd-laravel
services:
app:
image: cicd-laravel:latest
restart: unless-stopped
ports: ["127.0.0.1:8081:80"]
env_file: .env
extra_hosts:
- "host.docker.internal:host-gateway"
volumes:
- storage:/app/storage
healthcheck:
test: ["CMD", "curl", "-fsS", "http://localhost/up"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
volumes:
storage:
| Line | Why |
|---|---|
name: cicd-laravel | Readable names (container cicd-laravel-app-1, volume cicd-laravel_storage), instead of names derived from the folder |
image: cicd-laravel:latest | The tag the pipeline just built. Rollback = re-tag an older SHA as latest |
127.0.0.1:8081:80 | Bound to localhost. cloudflared on the same host can reach it, the LAN can’t. ⚠️ Without the 127.0.0.1: prefix, Docker publishes the port on every interface, and Docker’s iptables rules bypass UFW. |
env_file: .env | Production settings and secrets, loaded as environment variables |
extra_hosts: host.docker.internal:host-gateway | Lets the container reach the host’s PostgreSQL by name. It keeps working if the server’s LAN IP changes. |
storage volume | Logs, uploads and framework cache survive redeploys |
healthcheck on /up | The FrankenPHP image’s built-in healthcheck polls Caddy’s admin port, which php-server doesn’t serve, so the container is always reported as unhealthy. Laravel’s /up route is a meaningful check. |
If
cloudflaredran on a different machine, you’d bind to the server’s LAN IP instead (for example192.168.1.227:8081:80). In that case, restricttrustProxiesto that machine’s IP.
9.6 Server: the production .env
Generate a new app key on your PC. Don’t reuse your local one:
php artisan key:generate --show
sudo nano /opt/apps/cicd-laravel/.env
APP_NAME="CICD Laravel"
APP_ENV=production
APP_KEY=base64:... # from key:generate --show
APP_DEBUG=false
APP_URL=https://cicd-laravel.example.com
LOG_CHANNEL=stderr # logs show up in `docker compose logs`
LOG_LEVEL=warning
DB_CONNECTION=pgsql # don't leave this out, or Laravel falls back to SQLite
DB_HOST=host.docker.internal
DB_PORT=5432
DB_DATABASE=laravel
DB_USERNAME=laravel_dba
DB_PASSWORD=...
SESSION_DRIVER=database
CACHE_STORE=database
QUEUE_CONNECTION=database
Set ownership and permissions:
sudo chown gitea-runner:gitea-runner /opt/apps/cicd-laravel/compose.prod.yaml /opt/apps/cicd-laravel/.env
sudo chmod 600 /opt/apps/cicd-laravel/.env
ls -la /opt/apps/cicd-laravel
🔴 Compose reads
env_fileas the user runningdocker compose, which isgitea-runner, not the container. If the.envis owned by root or by you with mode600, every deploy fails withpermission denied.
🔴 Keep a copy of the production
APP_KEYsomewhere safe, such as a password manager. It’s not in Git, not in the image, and not in the backups in section 11. Without the original key, data that Laravel encrypted can’t be decrypted.
9.7 Test the database connection before the first deploy
This command checks listen_addresses, the pg_hba.conf Docker rule, the credentials and host-gateway all at once, from a container, as the runner user:
sudo -u gitea-runner docker run --rm --add-host host.docker.internal:host-gateway postgres:18 \
psql "postgresql://laravel_dba:<password>@host.docker.internal:5432/laravel" -c 'select 1'
If it prints 1, the pipeline’s migrate step will be able to connect. Fixing a connection problem here is much easier than inside a failing pipeline.
9.8 Cloudflare hostname, enable Actions, push
- Cloudflare Tunnel → your tunnel → add a public hostname:
cicd-laravel.example.com→ HTTP →localhost:8081. Don’t add it to the Gitea Access application, because the app is meant to be public. It must matchAPP_URL. - Gitea → the repository → Settings → enable Actions.
- Commit and push from your PC:
git add Dockerfile .dockerignore bootstrap/app.php .gitea/workflows/deploy.yml
git commit -m "Add Docker build and Gitea deploy pipeline"
git push
Watch the run under the repository’s Actions tab. The first run takes several minutes, because it pulls base images and downloads every dependency. Later runs reuse the cache.
9.9 Verify
cd /opt/apps/cicd-laravel
sudo -u gitea-runner docker compose -f compose.prod.yaml ps # STATUS: Up (healthy)
curl -I http://127.0.0.1:8081/up # 200 OK
sudo -u gitea-runner docker compose -f compose.prod.yaml exec app php artisan migrate:status
Then open https://cicd-laravel.example.com.
9.10 Everyday operations
| Task | Command (in /opt/apps/cicd-laravel, prefixed with sudo -u gitea-runner) |
|---|---|
| Deploy | git push to main |
| Logs | docker compose -f compose.prod.yaml logs -f app |
| Artisan command | docker compose -f compose.prod.yaml exec app php artisan <command> |
| Change a production setting | Edit .env, then docker compose -f compose.prod.yaml up -d and … exec -T app php artisan optimize |
| Roll back | See section 13.1 |
10. Pipeline 2: React
The second app is a React + TypeScript SPA built with Vite. It’s deployed completely separately from Laravel, with its own repository, image, port and hostname.
10.0 Create the project with the right template
npm create vite@latest react -- --template react-ts
cd react
npm install
npm run build # produces dist/
🔴 Check
package.jsonbefore going further. My first attempt picked Vite’s vanilla TypeScript template by mistake in the interactive prompt: there was noreactdependency, andsrc/heldmain.tsandcounter.ts. The pipeline would have worked anyway, but it wasn’t React. Passing--template react-tsavoids the prompt.
The react-ts template provides the two scripts the pipeline relies on:
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
}
build type-checks before bundling, and lint runs ESLint. Together they’re this pipeline’s test gate.
Which web server for a static SPA?
A Vite build is just static files in dist/. I serve them with nginx (nginx:alpine), the usual choice for SPAs in containers: a small image (~50 MB) with plenty of documentation. Caddy would also work, but its main advantage, automatic HTTPS, isn’t needed because Cloudflare already provides it. Don’t use a Node server (serve, vite preview) in production. It adds a whole Node runtime just to serve files, and vite preview isn’t designed for production use.
What happens on every push to main
- Checkout from
http://localhost:3000. - Build:
npm ci→ lint → type-check + bundle, insidedocker build. Any error fails the build, and nothing is deployed. The image is taggedcicd-react:<sha>+cicd-react:latest. - Deploy:
docker compose up -d. - Health check: curl
/. - Clean up untagged images.
There’s no migration step and no runtime .env, because a static site has no server-side secrets.
flowchart TD
A["git push to main"] --> B["Checkout<br/>from localhost:3000"]
B --> C{"docker build<br/>npm ci, lint,<br/>tsc + vite build"}
C -- "lint or type error" --> X["❌ Pipeline stops<br/>running site untouched"]
C -- "ok" --> D["Image cicd-react:SHA + :latest<br/>nginx + dist/ only"]
D --> E["compose up -d"]
E --> F{"Health check<br/>curl 127.0.0.1:8082/"}
F -- "fail" --> Y["❌ Pipeline red"]
F -- "200 OK" --> G["Prune untagged images"]
G --> H["✅ New version live"]
10.1 nginx.conf (repo root)
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
server_tokens off;
# Hashed build files: cache forever
location /assets/ {
add_header Cache-Control "public, max-age=31536000, immutable";
try_files $uri =404;
}
# index.html: always revalidate, so new deploys show up immediately
location = /index.html {
add_header Cache-Control "no-cache";
}
# SPA fallback: unknown paths serve index.html (client-side routing)
location / {
try_files $uri $uri/ /index.html;
}
}
/assets/is cached for a year. Vite puts a content hash in every asset’s filename (index-a1b2c3.js), so a new build always produces new names and the cache can never serve an outdated file.index.htmlisno-cache. It’s the only file that refers to the new asset names. If browsers cached it, users would keep loading the old version after a deploy.- SPA fallback. With client-side routing,
/aboutdoesn’t exist as a file. Withouttry_files … /index.html, refreshing that page returns a 404.
How nginx handles each request:
flowchart TD
R["Incoming request"] --> A{"Path starts with /assets/ ?"}
A -- "yes" --> A1{"File exists?"}
A1 -- "yes" --> A2["Serve it<br/>Cache-Control: max-age=1 year, immutable"]
A1 -- "no" --> A3["404"]
A -- "no" --> B{"Real file or folder?<br/>e.g. /favicon.svg"}
B -- "yes" --> B1["Serve it"]
B -- "no, e.g. /about" --> C["Serve /index.html<br/>Cache-Control: no-cache"]
C --> D["React router renders /about"]
10.2 Dockerfile
# syntax=docker/dockerfile:1
# ---- build: lint, type-check and bundle (fails the pipeline on error) ----
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY . .
RUN npm run lint
RUN npm run build
# ---- runtime: static files only, no Node (must stay the last stage) ----
FROM nginx:1.29-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
- The same caching pattern as Laravel:
package*.jsonfirst,npm ciwith a cache mount, then the code. node:24-alpinematches my local Node version. Use whichever major version you develop with.- The final image contains only nginx and
dist/: no Node, no source code, nonode_modules. - To add unit tests later (for example Vitest), add
RUN npm testafter the lint step.
⚠️
VITE_*environment variables are fixed at build time. Vite writes them into the JavaScript bundle duringnpm run build. A runtime.envorenv_fileon the container has no effect. If you need one, for example an API URL, pass it into the build withARG/--build-arg.
10.3 .dockerignore
node_modules
dist
.git
.gitea
.env
.env.*
.vscode
.idea
*.log
Dockerfile
.dockerignore
Excluding node_modules matters most. Your local (for example Windows) node_modules must never get into a Linux build, because npm ci installs a fresh, platform-correct set.
10.4 The workflow: .gitea/workflows/deploy.yml
name: Build & Deploy
on:
push:
branches: [main]
env:
APP_DIR: /opt/apps/cicd-react
IMAGE: cicd-react
jobs:
deploy:
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@v4
with:
github-server-url: http://localhost:3000
- name: Build image (lint + type-check + bundle)
run: docker build -t $IMAGE:${{ gitea.sha }} -t $IMAGE:latest .
- name: Deploy
working-directory: ${{ env.APP_DIR }}
run: docker compose -f compose.prod.yaml up -d
- name: Health check
run: curl -fsS --retry 10 --retry-delay 2 --retry-all-errors -o /dev/null http://127.0.0.1:8082/
- name: Clean up untagged images
run: docker image prune -f
10.5 Server: deploy folder and compose.prod.yaml
sudo mkdir -p /opt/apps/cicd-react
sudo chown gitea-runner:gitea-runner /opt/apps/cicd-react
sudo nano /opt/apps/cicd-react/compose.prod.yaml
name: cicd-react
services:
web:
image: cicd-react:latest
restart: unless-stopped
ports: ["127.0.0.1:8082:80"]
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/"]
interval: 30s
timeout: 5s
retries: 3
start_period: 5s
sudo chown gitea-runner:gitea-runner /opt/apps/cicd-react/compose.prod.yaml
- Port 8082. Each app gets its own local port, and the tunnel maps a hostname to each port.
wget, notcurl. The nginx Alpine image ships BusyBoxwgetbut nocurl.127.0.0.1, notlocalhost, in the healthcheck.localhostcan resolve to IPv6::1, where this nginx config isn’t listening.- No
.env.
10.6 Gitea, Cloudflare, push
- Gitea: create an empty repository
cicd-react, then enable Actions in its settings. - Cloudflare Tunnel: add a public hostname
cicd-react.example.com→ HTTP →localhost:8082. Like the Laravel app, it’s not behind Access. - Push:
cd react
git init -b main
git add .
git commit -m "Initial React app with Docker build and Gitea deploy pipeline"
git remote add origin https://git-server.example.com/myuser/cicd-react.git
git push -u origin main
The Cloudflare headers from section 7 apply to every repository on that host, and the Gitea token is already stored, so this push works without further setup.
10.7 Verify
cd /opt/apps/cicd-react
sudo -u gitea-runner docker compose -f compose.prod.yaml ps # Up (healthy)
curl -I https://cicd-react.example.com/ # 200, Cache-Control: no-cache
curl -I https://cicd-react.example.com/some/deep/link # 200, not 404 (SPA fallback)
In the browser’s DevTools → Network tab, files under /assets/ should show Cache-Control: public, max-age=31536000, immutable.
11. Nightly backups
Both pipelines can rebuild the apps from Git at any time. What can’t be rebuilt is the data: the PostgreSQL databases, and Gitea itself (repositories, issues, users, settings).
11.1 On the server, not in CI/CD
I considered running backups as a scheduled workflow, and decided against it:
| systemd timer on the server | Scheduled CI/CD workflow | |
|---|---|---|
| Runs when | On schedule, whatever state Gitea is in | Only when Gitea and the runner are up |
| Credentials | Local peer auth as postgres, so no stored password | The runner would need credentials for every database |
| Failure isolation | A broken pipeline doesn’t stop backups | When CI breaks, backups silently stop too |
11.2 What gets backed up, and where
My server has a second disk (eMMC) mounted at /backup. Every night at 02:30, a new folder is created:
/backup/nightly/
├── 2026-11-22_0239/
│ ├── postgres/
│ │ ├── globals.sql ← roles and passwords (pg_dump alone doesn't include them)
│ │ └── laravel.dump ← one compressed dump per database
│ └── gitea/
│ └── gitea-dump.zip ← repositories, Gitea's SQLite DB, app.ini, attachments
├── 2026-11-23_0230/
│ └── …
- One folder per run, named
YYYY-MM-DD_HHMM, solssorts the folders by date. A manual run during the day creates an extra folder, and nothing is overwritten. - Each run is a full backup, so any folder can be restored on its own.
- Every database is included automatically. The script asks PostgreSQL for the list on each run, so a new app’s database is picked up without editing anything. It skips
template0,template1and the emptypostgresmaintenance database. - Rotation: folders older than 14 days are deleted. What a nightly run does:
flowchart TD
T["server-backup.timer<br/>daily at 02:30<br/>Persistent=true"] --> S["server-backup.sh<br/>runs as root"]
S --> M{"Is /backup a mounted disk?"}
M -- "no" --> E["Exit with error<br/>visible in journalctl<br/>OS disk untouched"]
M -- "yes" --> P["As postgres:<br/>pg_dumpall --globals-only<br/>pg_dump -Fc for every database"]
P --> GD["As git:<br/>gitea dump into staging folder"]
GD --> MV["Move zip into<br/>/backup/nightly/STAMP/gitea/"]
MV --> RO["Delete folders<br/>older than 14 days"]
RO --> OK["Backup OK + size<br/>in journalctl"]
- Not included, by design:
/opt/apps(compose files,.env) and Docker volumes. The apps can be redeployed from Git. Keep the production.envvalues, especiallyAPP_KEY, in a password manager.
11.3 Check the disk and Gitea paths
findmnt /backup # the second disk is mounted here
grep /backup /etc/fstab # it will mount again after a reboot
systemctl cat gitea | grep -E 'User=|WorkingDirectory=|ExecStart='
# User=git
# WorkingDirectory=/var/lib/gitea
# ExecStart=/usr/local/bin/gitea web --config /etc/gitea/app.ini
If your Gitea values differ, adjust the GITEA_* variables in the script below.
11.4 Backup folder
sudo mkdir -p /backup/nightly
sudo chmod 700 /backup/nightly
The folder is root-only because it contains every secret on the server: password hashes in globals.sql, and Gitea’s app.ini with its internal tokens. As a result, cd /backup/nightly as your own user gives Permission denied, which is intended. Use sudo ls.
11.5 The script: /usr/local/bin/server-backup.sh
sudo nano /usr/local/bin/server-backup.sh
#!/usr/bin/env bash
set -euo pipefail
umask 077
cd /tmp
BACKUP_ROOT=/backup
DEST_ROOT=$BACKUP_ROOT/nightly
KEEP_DAYS=14
STAMP=$(date +%F_%H%M)
DEST=$DEST_ROOT/$STAMP
GITEA_USER=git
GITEA_CONFIG=/etc/gitea/app.ini
GITEA_WORK=/var/lib/gitea
GITEA_STAGING=$GITEA_WORK/backup-staging
# Refuse to run if the backup disk isn't mounted
mountpoint -q "$BACKUP_ROOT" || { echo "$BACKUP_ROOT is not mounted" >&2; exit 1; }
mkdir -p "$DEST"/{postgres,gitea}
echo "== PostgreSQL"
runuser -u postgres -- pg_dumpall --globals-only > "$DEST/postgres/globals.sql"
for db in $(runuser -u postgres -- psql -AtX -c \
"SELECT datname FROM pg_database WHERE NOT datistemplate AND datname <> 'postgres'"); do
runuser -u postgres -- pg_dump -Fc "$db" > "$DEST/postgres/$db.dump"
done
echo "== Gitea"
install -d -o "$GITEA_USER" -g "$GITEA_USER" -m 700 "$GITEA_STAGING"
runuser -u "$GITEA_USER" -- gitea dump \
--config "$GITEA_CONFIG" --work-path "$GITEA_WORK" \
--tempdir "$GITEA_STAGING" --file "$GITEA_STAGING/gitea-dump.zip"
mv "$GITEA_STAGING/gitea-dump.zip" "$DEST/gitea/"
echo "== Rotation"
find "$DEST_ROOT" -mindepth 1 -maxdepth 1 -type d -mtime +"$KEEP_DAYS" -exec rm -rf {} +
echo "Backup OK: $DEST"
du -sh "$DEST"
sudo chmod 700 /usr/local/bin/server-backup.sh
How it works:
- It runs as root and switches user for each task with
runuser:postgresfor the dumps (local peer auth, no password needed) andgitforgitea dump. Root’s shell performs the>redirections, so every file in the backup belongs to root. - The
mountpointguard. If the backup disk isn’t mounted,/backup/nightlywould silently be created on the OS disk and fill it. Instead, the script stops with an error. This guard caught a real mistake of mine: I first wrote/backinstead of/backup. pg_dump -Fcproduces compressed, custom-format dumps, whichpg_restorecan restore whole or table by table.globals.sqlholds roles and passwords. Without it, restoring to a fresh server fails on missing owners.- Gitea staging:
gitea dumpruns asgit, which can’t write to the root-only backup folder. It writes into its own work directory, and root then moves the zip. set -euo pipefail: if any step fails, the whole job fails and appears in the journal. A half-finished backup never reports “OK”.
11.6 systemd service and timer
/etc/systemd/system/server-backup.service:
[Unit]
Description=Nightly backup: PostgreSQL and Gitea
After=postgresql.service gitea.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/server-backup.sh
/etc/systemd/system/server-backup.timer:
[Unit]
Description=Run server backup nightly
[Timer]
OnCalendar=*-*-* 02:30
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now server-backup.timer
sudo systemctl start server-backup.service # run once now
I used a timer rather than cron because Persistent=true runs a missed backup as soon as the machine is back on, and the output goes to journalctl.
11.7 Verify
journalctl -u server-backup.service -n 30 # ends with "Backup OK: …" and the size
sudo ls -laR /backup/nightly
systemctl list-timers server-backup.timer # next run
LATEST=$(sudo ls -1 /backup/nightly | tail -n1)
sudo unzip -l "/backup/nightly/$LATEST/gitea/gitea-dump.zip" | head -20
11.8 Test a restore at least once
A backup you’ve never restored can’t be relied on:
LATEST=$(sudo ls -1 /backup/nightly | tail -n1)
echo "$LATEST"
sudo -u postgres createdb laravel_restore_test
sudo cat "/backup/nightly/$LATEST/postgres/laravel.dump" \
| sudo -u postgres pg_restore -d laravel_restore_test
sudo -u postgres psql -d laravel_restore_test -c '\dt'
sudo -u postgres dropdb laravel_restore_test
My restore brought back all of Laravel’s tables (migrations, users, sessions, cache, jobs…), still owned by laravel_dba.
Two traps here: (1) don’t type a placeholder such as
<stamp>literally. Bash treats<as input redirection, the restore silently does nothing, and\dtshows an empty database. That’s why the commands use theLATEST=…variable. (2) Thepostgresuser can’t read the root-only backup folder, so root reads the file (sudo cat) and pipes it intopg_restore.
Restoring Gitea from gitea-dump.zip is a manual process (put back the repositories and data, import the database, restore app.ini), described in Gitea’s “Backup and Restore” documentation.
12. Branches and environments: dev, test and prod
Both pipelines deploy on every push to main. That’s convenient, but it also means anyone who can push to main can change production, including me with a typo and a tired git push. Nothing checks the code before it goes live, apart from the tests inside the build.
In practice, teams don’t push to the production branch at all. Production changes only when a pull request is merged, and the merge is what triggers the deploy. This section shows how to set that up in Gitea, how to add a separate dev environment, and when a third test branch is worth it.
12.1 Protect main and deploy through pull requests
The pipeline doesn’t change. Merging a PR creates a push to main, so deploy.yml runs exactly as before. The only change is in Gitea, which blocks every other way onto main.
Gitea → repository → Settings → Branches → Add new rule, with the branch name pattern main:
| Setting | Value | Why |
|---|---|---|
| Push | Disable push | git push to main is rejected. Merging a PR is still allowed. |
| Required approvals | 0 if you work alone, 1+ with a team | Gitea doesn’t let you approve your own PR, so a solo developer would be locked out |
| Status checks | Enable after the CI workflow below has run once | The Merge button stays disabled until the tests pass |
| Block merge on outdated branch | Optional | Forces the PR to include the latest main before merging |
Then confirm the rule actually blocks you:
git checkout main
git commit --allow-empty -m "should be rejected"
git push # expected: rejected, protected branch
git reset --hard HEAD~1 # drop the test commit
If the push goes through, the rule isn’t matching your account or branch. Fix it before you rely on it.
Run the tests on the PR itself. At the moment, tests run only once code is already on a branch. A separate workflow triggered by pull_request runs them before the merge, without deploying anything. .gitea/workflows/ci.yml:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@v4
with:
github-server-url: http://localhost:3000 # same reason as in deploy.yml
- name: Test
run: docker build --target test .
For React, replace the last step with a build that stops before the runtime stage, or simply docker build ., since the build stage runs lint and the type-check.
Open a PR once so the check appears. Then go back to the branch rule, tick Enable status check, and select it. It shows up with a name like CI / test (pull_request).
flowchart LR
D["push to dev"] --> PR["Pull request<br/>dev → main"]
PR --> CI["ci.yml<br/>tests on the PR"]
CI -- red --> X["Merge blocked"]
CI -- green --> M["Merge<br/>(only way into main)"]
M --> DEP["deploy.yml"] --> P["Production"]
Direct["git push to main"] -. rejected .-> X2["Branch protection"]
The same rule belongs on every repository that deploys from main. This ties in with hardening item 9 in section 13: the runner user is effectively root, so whoever can merge to main can run commands on the server.
12.2 A dev environment next to production
A pull request needs somewhere to try the change first. That’s a second, fully separate copy of the app, deployed from a dev branch. Nothing is shared with production:
Production (main) | Dev (dev) | |
|---|---|---|
| Workflow | deploy.yml | deploy-dev.yml |
| Image | cicd-laravel | cicd-laravel-dev |
| Server folder | /opt/apps/cicd-laravel | /opt/apps/cicd-laravel-dev |
Compose project name: | cicd-laravel | cicd-laravel-dev |
| Port | 127.0.0.1:8081 | 127.0.0.1:8083 |
| Database / role | laravel / laravel_dba | laravel_dev / laravel_dev_dba |
APP_KEY | its own | its own, never copied |
| Hostname | cicd-laravel.example.com | cicd-laravel-dev.example.com, behind Cloudflare Access |
The image name matters most. If both branches built cicd-laravel:latest, a push to dev would replace the image that production restarts from.
Steps, all following the patterns from section 9:
- Database:
CREATE ROLE laravel_dev_dba WITH LOGIN PASSWORD '…';andCREATE DATABASE laravel_dev OWNER laravel_dev_dba;. If yourpg_hba.confrules name databases explicitly, add a line forlaravel_dev. The nightly backup picks the new database up automatically. - Folder:
sudo mkdir -p /opt/apps/cicd-laravel-dev && sudo chown gitea-runner:gitea-runner /opt/apps/cicd-laravel-dev. Check that the port is free withsudo ss -tlnp | grep 8083. compose.prod.yaml: copy the production file and change three things:name: cicd-laravel-dev,image: cicd-laravel-dev:latest, and the port"127.0.0.1:8083:80". The storage volume is prefixed with the project name, so it’s separate automatically..env: copy the production file, keep the ownergitea-runnerand mode600, and changeAPP_ENV=staging,APP_URL,DB_DATABASE,DB_USERNAMEandDB_PASSWORD. Generate a new key withdocker run --rm cicd-laravel:latest php artisan key:generate --show. SetAPP_DEBUG=trueonly if the hostname is behind Access.- Cloudflare: add the public hostname
cicd-laravel-dev.example.com→http://localhost:8083, plus an Access application with the same email-PIN policy as Gitea. A debug-mode test site shouldn’t be public. - Branch and workflow:
git checkout -b dev, then create.gitea/workflows/deploy-dev.yml. It’s a copy ofdeploy.ymlwith four lines changed:
name: Test & Deploy (dev)
on:
push:
branches: [dev] # changed
env:
APP_DIR: /opt/apps/cicd-laravel-dev # changed
IMAGE: cicd-laravel-dev # changed
# … steps identical to deploy.yml, except the health check:
# run: curl -fsS --retry 10 --retry-delay 3 --retry-all-errors http://127.0.0.1:8083/up # changed
Commit it and run git push -u origin dev. The Actions tab should show only “Test & Deploy (dev)”, and production shouldn’t move.
Both workflow files live on both branches. That’s harmless, because each one only reacts to its own branch: when dev is merged into main, deploy-dev.yml comes along but never runs there.
12.3 Three branches: dev, test and prod
With testers or a client who signs off releases, a third environment sits between dev and production. Each branch maps to one environment and one audience, and code only moves forward, always by pull request:
| Branch | Environment | Who uses it | What it’s for | Who merges into it |
|---|---|---|---|---|
feature/* | none (local) | one developer | Work in progress | — |
dev | dev site | Developers | Integration: does my code work with everyone else’s? Allowed to break. Fake seed data. | Developers, by PR from feature branches (or a direct push when you’re solo) |
test (also called staging or UAT) | test site | QA, product owner, client | Acceptance: is this release ready? Kept stable and production-like. Realistic but anonymised data. | The release owner, by PR from dev |
main (prod) | production | Real users | Only what passed test | The release owner, by PR from test only |
Production is promoted from test, never from dev or a feature branch. I’d keep the name main for the production branch. Renaming it to prod means changing the workflow trigger, the protection rule and the default branch, for no real benefit.
Adding test is the same work as 12.2 one more time: deploy-test.yml on branches: [test], image cicd-laravel-test, folder /opt/apps/cicd-laravel-test, port 8084, database laravel_test, its own APP_KEY, and a hostname behind Access. Protect test the same way as main.
gitGraph
commit id: "v1.0"
branch test
branch dev
checkout dev
branch feature-login
commit id: "login form"
commit id: "login tests"
checkout dev
merge feature-login id: "PR: feature → dev"
checkout test
merge dev id: "PR: dev → test (QA)"
checkout main
merge test id: "PR: test → main = v1.1"
branch hotfix-500
commit id: "fix crash"
checkout main
merge hotfix-500 id: "hotfix PR = v1.1.1"
checkout test
merge main id: "merge back"
checkout dev
merge main id: "merge back "
12.4 Hotfixes: the one exception
When production is broken and the fix can’t wait for a full dev → test → prod cycle, branch from main, fix it, and merge back by PR so CI still runs:
hotfix/x (from main) ──PR──► main ──► production
└──► then merge main back into test and dev
The merge back is required. Without it, the next normal release from dev brings the bug back. This is the only time code moves backwards.
12.5 Rules that keep the model honest
- Promote forward only: dev → test → main. No cherry-picking individual commits into
testormain, or “what we tested” and “what we shipped” quietly stop being the same thing. - One database,
.envandAPP_KEYper environment. A shared key would let a session or encrypted value from dev work in production. - No production data in dev or test. Seed dev with factories, and give test anonymised data. Real customer data on a debug-mode site is a leak waiting to happen.
- Know the trade-off of branch-per-environment. In this setup, each branch rebuilds the image, so the production image isn’t byte-for-byte the one QA tested. It’s the same source, but base images or dependency resolution could differ on the day. Lock files make this a small risk, and most small teams accept it. Larger teams build once and promote: the tested
:shaimage is retagged for production instead of being rebuilt. Since all environments here share one Docker host, that’s a natural next step.
12.6 Which model fits your team?
| Team | Branches | Environments |
|---|---|---|
| Solo or 1–2 developers, nobody else tests | dev + main | dev + production |
| Has testers, or a client who approves releases | dev + test + main | dev + test + production |
| Bigger team, many deploys a day | Trunk-based: main + short feature branches | Environments promoted by tag (on: push: tags: ['v*']) or a manual button (workflow_dispatch), not by branch |
Every extra branch adds a merge step to every release. Add test when there’s someone to use it, not before.
13. Recommended next steps
The setup above works and is what I’m running. These are improvements I recommend before you rely on it for anything important.
13.1 Rollback drill
What it is: practise undoing a bad deploy before you need to under pressure.
Every deploy tags the image twice, :<commit-sha> and :latest, and the compose file runs :latest. Rolling back means pointing latest at an older SHA. Nothing is rebuilt, and it takes seconds:
flowchart LR
subgraph IMG["Local images"]
old["cicd-laravel:9f8e7d6<br/>previous deploy"]
new["cicd-laravel:abc1234<br/>bad deploy"]
latest(["tag: latest"])
end
latest -. "before rollback" .-> new
latest == "after docker tag" ==> old
latest --> C["compose up -d<br/>recreates the container<br/>from the image latest points to"]
docker images cicd-laravel # find the previous SHA tag
docker tag cicd-laravel:<previous-sha> cicd-laravel:latest
cd /opt/apps/cicd-laravel
sudo -u gitea-runner docker compose -f compose.prod.yaml up -d
curl -fsS http://127.0.0.1:8081/up
Things to know:
- The database isn’t rolled back. The old code runs against the new schema. Write migrations to be backward compatible: add columns and tables in one release, and remove old ones in a later release. For a truly destructive migration, the rollback is a
pg_restorefrom the nightly backup. - The next push overwrites a rollback. Re-tagging is the emergency fix. The proper fix is
git revert <bad-commit>and a push, so the pipeline rebuilds a known-good state. - SHA-tagged images build up over time. Delete old tags occasionally.
- React works the same way with
cicd-react:<sha>, and there’s no database to worry about.
13.2 Docker log rotation
Containers log to stdout, and Docker stores that output in JSON files with no size limit by default. An app stuck in an error loop can fill the OS disk and take down PostgreSQL, Gitea and every app with it.
/etc/docker/daemon.json:
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}
sudo systemctl restart docker # briefly restarts all containers
- The limit applies only to containers created after the change. Recreate existing ones with
docker compose -f compose.prod.yaml up -d --force-recreate, or just push to each repository. - Check it:
docker inspect cicd-laravel-app-1 --format '{{.HostConfig.LogConfig}}'.
13.3 Production hardening checklist
| # | Recommendation | Why | How |
|---|---|---|---|
| 1 | Enable a firewall (UFW) | In my lab, every listening port is open to the LAN | ufw default deny incoming, ufw allow OpenSSH (before enabling, or you’ll lock yourself out), allow 5432 from your LAN and from 172.16.0.0/12 (containers), then ufw enable. The tunnel is outbound-only and needs no rule. |
| 2 | Bind Gitea to localhost | http://<server-ip>:3000 bypasses Cloudflare Access | [server] HTTP_ADDR = 127.0.0.1 in app.ini. The runner and cloudflared both use localhost, so they keep working. |
| 3 | SSH keys only | Passwords can be brute-forced | ssh-copy-id, then PasswordAuthentication no and PermitRootLogin no |
| 4 | Automatic security updates | Unpatched packages are the easiest way in | sudo apt install unattended-upgrades && sudo dpkg-reconfigure unattended-upgrades |
| 5 | Off-site, encrypted backups | /backup is in the same box: theft, fire or a power surge takes both disks | restic or rclone crypt to cloud storage or another machine, after the nightly job. Encrypt, because the backups contain secrets. |
| 6 | Keep .env / APP_KEY in a password manager | They’re deliberately not in the backups | |
| 7 | Watch the service token’s expiry | An expired token makes git fail with 403 or HTML | Calendar reminder; rotate before it expires |
| 8 | Tighten pg_hba.conf | all all lets any role reach any database from those subnets | One line per app, for example host laravel laravel_dba 172.16.0.0/12 scram-sha-256. Restrict LAN access to your admin PC, or use pgAdmin’s SSH tunnel. |
| 9 | Treat CI access as root access | The runner user is in the docker group | Only trusted people push to repositories with Actions enabled. Protect main (section 12), and don’t run workflows from forks. |
| 10 | Pin base image versions | node:24-alpine, nginx:1.29-alpine, frankenphp:1-php8.5 can change underneath you | Pin exact versions or digests and update on purpose. The trade-off is that security patches no longer arrive automatically. |
14. Troubleshooting:
| Symptom | Cause | Fix |
|---|---|---|
| Gitea login silently returns to the sign-in page | ROOT_URL is https://… but I was browsing over http:// on the LAN IP, so the browser dropped the Secure session cookie | Sign in through the HTTPS tunnel hostname, or temporarily set [session] COOKIE_SECURE = false |
git push prints a page of HTML | Cloudflare Access returned its login page: headers missing, the token in an Allow policy instead of Service Auth, or the push ran in a shell without the global git config (WSL, another machine) | Check git config --get-all http.https://git-server.example.com/.extraHeader, and use a Service Auth policy |
| First push fails in VS Code but works in a terminal | Git Credential Manager couldn’t show its username/token prompt through VS Code | Do the first push from a terminal. The stored credential then works everywhere. |
actions/checkout fails or gets HTML | Checkout clones from the public ROOT_URL, which is behind Access | with: github-server-url: http://localhost:3000 |
register → open .runner: permission denied | Registration writes .runner to the current directory, which was my home directory | sudo -u gitea-runner -H bash -c 'cd /var/lib/gitea-runner && gitea-runner register …' |
exec: "node": executable file not found | Host-mode runner and no Node on the host | sudo apt install nodejs |
Node works for me, but not for gitea-runner | Node installed per user with fnm/nvm | Install it system-wide with apt. Check with sudo -u gitea-runner -H bash -lc 'node -v'. |
Deploy: permission denied reading .env | Compose reads env_file as gitea-runner | chown gitea-runner:gitea-runner .env && chmod 600 .env |
Container unhealthy while the app works | The FrankenPHP image’s default healthcheck polls Caddy’s admin port | Custom healthcheck on /up in compose.prod.yaml |
| Every push downloads all dependencies again | COPY . . before composer install/npm ci invalidates the cache | Copy the lock files first, install, then copy the code. Add --mount=type=cache. |
| Restore check shows “Did not find any tables” | I typed the placeholder <stamp> literally, so the restore never ran | Use LATEST=$(sudo ls -1 /backup/nightly | tail -n1) |
15. Wrap-up
What I ended up with, on one low-power Ubuntu machine:
- Gitea, reachable at
https://git-server.example.combehind Cloudflare Access (an email PIN for people, a service token for git). - Two independent pipelines that run on every push to
main:- Laravel: test (Pest, inside
docker build) → build → migrate → deploy → health check - React: lint + type-check + build → deploy → health check
- Laravel: test (Pest, inside
- Rollback-ready images tagged by commit SHA, with no registry.
- Public HTTPS for every app via Cloudflare Tunnel, with no open ports and no reverse proxy. App ports are bound to
127.0.0.1. - Nightly, tested backups of PostgreSQL and Gitea on a second disk.
- A path to safer releases: a protected
mainthat only changes through pull requests, with a dev environment (and optionally test) beside production.
Adding a third app follows the same pattern: a Dockerfile, a workflow with runs-on: self-hosted, a folder under /opt/apps/<app> owned by gitea-runner with a compose.prod.yaml on a new 127.0.0.1 port, and a new hostname in the tunnel. Its database, if it has one, is included in the nightly backup automatically.