[SKIP TO CONTENT]
LAST_UPDATE: 23 November 2026
Go back
BY Junrong Li

> Self-Hosted CI/CD for Laravel and React Application

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:

PlaceholderMeaning
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

  1. Architecture and decisions
  2. The server
  3. Docker
  4. PostgreSQL on the host
  5. Gitea
  6. Cloudflare Tunnel and Cloudflare Access
  7. Pushing code from your PC through Cloudflare Access
  8. The Gitea Actions runner (host mode)
  9. Pipeline 1: Laravel
  10. Pipeline 2: React
  11. Nightly backups
  12. Branches and environments: dev, test and prod
  13. Recommended next steps
  14. Troubleshooting
  15. 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:

  1. Code in: your PC pushes to Gitea through Cloudflare Access (section 7).
  2. 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).
  3. Traffic in: visitors reach Cloudflare, and cloudflared forwards each hostname to its own local port. Nothing on the server listens on a public port.
DecisionWhat I choseWhy
Where apps runDocker containersEvery app brings its own runtime (PHP 8.5, nginx…), so nothing app-specific is installed on the host
Git server and CIGitea + Gitea ActionsSelf-hosted, lightweight, and its workflow syntax is almost the same as GitHub Actions
How Gitea is installedNative binary + systemdSimple to update and back up, and it doesn’t depend on Docker
Runner modeHost 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 registryNoneImages are built where they run. A commit-SHA tag on every image makes rollbacks possible
Public accessCloudflare TunnelNo open inbound ports, HTTPS handled by Cloudflare, and no reverse proxy needed: each hostname maps to one local port
Protecting GiteaCloudflare AccessEmail one-time PIN for the web UI, plus a service token for git clients
DatabasePostgreSQL on the hostOne instance for all apps, simple to back up
Secrets.env files on the serverNever committed and never inside the image
MigrationsRun automatically on every deployBefore the new container starts

My hardware

PartSpec
CPUIntel N150 (4 cores)
RAM16 GB
OS disk512 GB NVMe
Backup disk128 GB eMMC, mounted at /backup
OSUbuntu 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 docker group is effectively root access. Anyone who can run docker can mount the host’s filesystem into a container. Only add users you’d also trust with sudo.


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 postgresql shows active (exited). That’s normal: postgresql.service is only a wrapper, and the real server runs as postgresql@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:

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 in pg_hba.conf instead.

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 public schema by default. If the database belongs to sa or postgres, php artisan migrate fails with permission denied for schema public. Making the app role the owner fixes that. Also give the app role no superuser, CREATEDB or CREATEROLE rights.

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:

FieldValueNotes
Database typeSQLite3Fine for a small instance. PostgreSQL is also an option, since it’s already running.
Server domaingit-server.example.com
SSH server domaingit-server.example.com (or the LAN IP, see below)
Gitea Base URLhttps://git-server.example.com/The public HTTPS address. See the warning below.
HTTP port3000
Administrator account settingsExpand this section and create the adminIf 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 at http://192.168.1.227:3000. Every login silently returned to the sign-in page, with no error message.

Cause: when ROOT_URL starts with https://, 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 = false in app.ini temporarily, 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

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:

  1. Name the tunnel, for example all-in-one.
  2. Choose Debian / Ubuntu, 64-bit. The dashboard shows commands that (a) add Cloudflare’s apt repository and install cloudflared, and (b) run sudo cloudflared service install <token>. Run them on the server. This installs cloudflared as a systemd service, with its configuration managed from the dashboard.
  3. Add a public hostname for Gitea:
SubdomainDomainTypeURL
git-serverexample.comHTTPlocalhost: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:

PolicyActionIncludeUsed by
HumansAllowEmails → your address (login method: One-time PIN)Your browser: Cloudflare emails you a code before showing Gitea
Git clientsService AuthService Token → the token created belowgit 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 push prints 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>"

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:

LabelSteps run…Consequence
ubuntu-latest:docker://… (default)Inside a fresh container per jobIsolated, 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 userSimple: 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/checkout run with node from the host. Docker-mode job images already include Node. In host mode, if Node is missing, the very first step fails with exec: "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, but sudo -u gitea-runner node -v printed command not found. fnm and nvm install Node under your home directory and add it to PATH from your shell profile. A systemd service account never loads your profile, and on Ubuntu it can’t read your home directory anyway (it’s mode 750).

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:

🔴 My first attempt was cd /var/lib/gitea-runner in my own shell, followed by sudo -u gitea-runner gitea-runner register …. The cd failed silently (the directory is private to gitea-runner), so registration ran in my home directory and ended with failed 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

  1. Checkout from http://localhost:3000.
  2. 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.
  3. Build: the production image, tagged cicd-laravel:<commit-sha> and cicd-laravel:latest.
  4. Migrate: php artisan migrate --force in a throwaway container from the new image, before the running app is replaced.
  5. Deploy: docker compose up -d recreates the container from the new image, then php artisan optimize runs.
  6. Health check: curl Laravel’s /up route. The pipeline goes red if the app doesn’t respond.
  7. 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

FileWhereCommitted?
Dockerfilerepo root✅
.dockerignorerepo root✅
bootstrap/app.php (trusted proxies)repo✅
.gitea/workflows/deploy.ymlrepo✅
compose.prod.yamlserver: /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"]
StageBase imageWhat it does
assetsnode:22-alpinenpm ci + npm run build → public/build
vendorcomposer:2Production Composer dependencies with an optimized autoloader
testdunglas/frankenphp:1-php8.5Dev dependencies + php artisan test. Built only with --target test
(final)dunglas/frankenphp:1-php8.5PostgreSQL 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:

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

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

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:
LineWhy
name: cicd-laravelReadable names (container cicd-laravel-app-1, volume cicd-laravel_storage), instead of names derived from the folder
image: cicd-laravel:latestThe tag the pipeline just built. Rollback = re-tag an older SHA as latest
127.0.0.1:8081:80Bound 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: .envProduction settings and secrets, loaded as environment variables
extra_hosts: host.docker.internal:host-gatewayLets the container reach the host’s PostgreSQL by name. It keeps working if the server’s LAN IP changes.
storage volumeLogs, uploads and framework cache survive redeploys
healthcheck on /upThe 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 cloudflared ran on a different machine, you’d bind to the server’s LAN IP instead (for example 192.168.1.227:8081:80). In that case, restrict trustProxies to 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_file as the user running docker compose, which is gitea-runner, not the container. If the .env is owned by root or by you with mode 600, every deploy fails with permission denied.

🔴 Keep a copy of the production APP_KEY somewhere 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

  1. 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 match APP_URL.
  2. Gitea → the repository → Settings → enable Actions.
  3. 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

TaskCommand (in /opt/apps/cicd-laravel, prefixed with sudo -u gitea-runner)
Deploygit push to main
Logsdocker compose -f compose.prod.yaml logs -f app
Artisan commanddocker compose -f compose.prod.yaml exec app php artisan <command>
Change a production settingEdit .env, then docker compose -f compose.prod.yaml up -d and … exec -T app php artisan optimize
Roll backSee 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.json before going further. My first attempt picked Vite’s vanilla TypeScript template by mistake in the interactive prompt: there was no react dependency, and src/ held main.ts and counter.ts. The pipeline would have worked anyway, but it wasn’t React. Passing --template react-ts avoids 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

  1. Checkout from http://localhost:3000.
  2. Build: npm ci → lint → type-check + bundle, inside docker build. Any error fails the build, and nothing is deployed. The image is tagged cicd-react:<sha> + cicd-react:latest.
  3. Deploy: docker compose up -d.
  4. Health check: curl /.
  5. 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;
    }
}

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

⚠️ VITE_* environment variables are fixed at build time. Vite writes them into the JavaScript bundle during npm run build. A runtime .env or env_file on the container has no effect. If you need one, for example an API URL, pass it into the build with ARG/--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

10.6 Gitea, Cloudflare, push

  1. Gitea: create an empty repository cicd-react, then enable Actions in its settings.
  2. Cloudflare Tunnel: add a public hostname cicd-react.example.com → HTTP → localhost:8082. Like the Laravel app, it’s not behind Access.
  3. 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 serverScheduled CI/CD workflow
Runs whenOn schedule, whatever state Gitea is inOnly when Gitea and the runner are up
CredentialsLocal peer auth as postgres, so no stored passwordThe runner would need credentials for every database
Failure isolationA broken pipeline doesn’t stop backupsWhen 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/
│   └── …
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"]

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:

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 \dt shows an empty database. That’s why the commands use the LATEST=… variable. (2) The postgres user can’t read the root-only backup folder, so root reads the file (sudo cat) and pipes it into pg_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:

SettingValueWhy
PushDisable pushgit push to main is rejected. Merging a PR is still allowed.
Required approvals0 if you work alone, 1+ with a teamGitea doesn’t let you approve your own PR, so a solo developer would be locked out
Status checksEnable after the CI workflow below has run onceThe Merge button stays disabled until the tests pass
Block merge on outdated branchOptionalForces 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)
Workflowdeploy.ymldeploy-dev.yml
Imagecicd-laravelcicd-laravel-dev
Server folder/opt/apps/cicd-laravel/opt/apps/cicd-laravel-dev
Compose project name:cicd-laravelcicd-laravel-dev
Port127.0.0.1:8081127.0.0.1:8083
Database / rolelaravel / laravel_dbalaravel_dev / laravel_dev_dba
APP_KEYits ownits own, never copied
Hostnamecicd-laravel.example.comcicd-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:

  1. Database: CREATE ROLE laravel_dev_dba WITH LOGIN PASSWORD '…'; and CREATE DATABASE laravel_dev OWNER laravel_dev_dba;. If your pg_hba.conf rules name databases explicitly, add a line for laravel_dev. The nightly backup picks the new database up automatically.
  2. 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 with sudo ss -tlnp | grep 8083.
  3. 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.
  4. .env: copy the production file, keep the owner gitea-runner and mode 600, and change APP_ENV=staging, APP_URL, DB_DATABASE, DB_USERNAME and DB_PASSWORD. Generate a new key with docker run --rm cicd-laravel:latest php artisan key:generate --show. Set APP_DEBUG=true only if the hostname is behind Access.
  5. 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.
  6. Branch and workflow: git checkout -b dev, then create .gitea/workflows/deploy-dev.yml. It’s a copy of deploy.yml with 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:

BranchEnvironmentWho uses itWhat it’s forWho merges into it
feature/*none (local)one developerWork in progress—
devdev siteDevelopersIntegration: 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 siteQA, product owner, clientAcceptance: is this release ready? Kept stable and production-like. Realistic but anonymised data.The release owner, by PR from dev
main (prod)productionReal usersOnly what passed testThe 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

12.6 Which model fits your team?

TeamBranchesEnvironments
Solo or 1–2 developers, nobody else testsdev + maindev + production
Has testers, or a client who approves releasesdev + test + maindev + test + production
Bigger team, many deploys a dayTrunk-based: main + short feature branchesEnvironments 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.


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:

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

13.3 Production hardening checklist

#RecommendationWhyHow
1Enable a firewall (UFW)In my lab, every listening port is open to the LANufw 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.
2Bind Gitea to localhosthttp://<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.
3SSH keys onlyPasswords can be brute-forcedssh-copy-id, then PasswordAuthentication no and PermitRootLogin no
4Automatic security updatesUnpatched packages are the easiest way insudo apt install unattended-upgrades && sudo dpkg-reconfigure unattended-upgrades
5Off-site, encrypted backups/backup is in the same box: theft, fire or a power surge takes both disksrestic or rclone crypt to cloud storage or another machine, after the nightly job. Encrypt, because the backups contain secrets.
6Keep .env / APP_KEY in a password managerThey’re deliberately not in the backups
7Watch the service token’s expiryAn expired token makes git fail with 403 or HTMLCalendar reminder; rotate before it expires
8Tighten pg_hba.confall all lets any role reach any database from those subnetsOne 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.
9Treat CI access as root accessThe runner user is in the docker groupOnly trusted people push to repositories with Actions enabled. Protect main (section 12), and don’t run workflows from forks.
10Pin base image versionsnode:24-alpine, nginx:1.29-alpine, frankenphp:1-php8.5 can change underneath youPin exact versions or digests and update on purpose. The trade-off is that security patches no longer arrive automatically.

14. Troubleshooting:

SymptomCauseFix
Gitea login silently returns to the sign-in pageROOT_URL is https://… but I was browsing over http:// on the LAN IP, so the browser dropped the Secure session cookieSign in through the HTTPS tunnel hostname, or temporarily set [session] COOKIE_SECURE = false
git push prints a page of HTMLCloudflare 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 terminalGit Credential Manager couldn’t show its username/token prompt through VS CodeDo the first push from a terminal. The stored credential then works everywhere.
actions/checkout fails or gets HTMLCheckout clones from the public ROOT_URL, which is behind Accesswith: github-server-url: http://localhost:3000
register → open .runner: permission deniedRegistration writes .runner to the current directory, which was my home directorysudo -u gitea-runner -H bash -c 'cd /var/lib/gitea-runner && gitea-runner register …'
exec: "node": executable file not foundHost-mode runner and no Node on the hostsudo apt install nodejs
Node works for me, but not for gitea-runnerNode installed per user with fnm/nvmInstall it system-wide with apt. Check with sudo -u gitea-runner -H bash -lc 'node -v'.
Deploy: permission denied reading .envCompose reads env_file as gitea-runnerchown gitea-runner:gitea-runner .env && chmod 600 .env
Container unhealthy while the app worksThe FrankenPHP image’s default healthcheck polls Caddy’s admin portCustom healthcheck on /up in compose.prod.yaml
Every push downloads all dependencies againCOPY . . before composer install/npm ci invalidates the cacheCopy 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 ranUse LATEST=$(sudo ls -1 /backup/nightly | tail -n1)

15. Wrap-up

What I ended up with, on one low-power Ubuntu machine:

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.

TAGGED_NODES: