Self-Host Gitea or Forgejo: Lightweight GitHub Alternative on VPS (2026)

Deploy a self-hosted Forgejo Git server, isolate runners, and test a complete recovery of repositories, metadata, LFS, packages and release assets.

Adrian Silaghi

18 min read

3,951 views

giteaforgejoself-hostedgitgithub-alternativevpsdevops
Self-Host Gitea or Forgejo: Lightweight GitHub Alternative on VPS (2026)

Gitea and Forgejo offer self-hosted Git repositories, collaboration and automation under your own domain. Operating a forge also means owning updates, account security, runner isolation and recovery. The meaningful comparison with GitHub is the complete service responsibility, not just a VM bill.

This guide preserves the VPS, Compose, TLS, SSH, LFS, registry and migration walkthrough, and expands disaster recovery into a reproducible drill. Reviewed 2 November 2026: the downloadable Forgejo 17.0.1 lab restores a stopped SQLite/local-storage instance and checks repository, issue/PR, LFS, package and release data. The separate PostgreSQL Compose and public-domain deployment steps were not executed for this update.

Gitea or Forgejo?

They share ancestry but are separate projects with diverging releases and compatibility boundaries. Compare the current Forgejo project and Gitea project for governance, licensing, enterprise integrations and supported migration routes. Do not assume databases can be exchanged in both directions or that every command differs only by its image name.

We use Forgejo below. This is an operating guide, not a claim that GitHub is inappropriate for every team. See our GitHub-to-Forgejo migration postmortem for the dependencies and failures encountered in a real migration rather than a universal feature-compatibility percentage.

Who should self-host?

  • A team that needs its own domain, access policies and deployment location.
  • A consultancy managing client repositories with explicit operational ownership.
  • An organization with a documented infrastructure/supplier requirement and staff to maintain it.
  • A small team that has compared the complete cost of hosted seats against compute, storage, backups, runners and on-call work.

European hosting is one part of a processing and supplier review; it is not a blanket GDPR, DORA or NIS2 certification. Publishing an open-source instance also does not prevent people from copying public code.

Size the forge and runners separately

Measure repository count and size, Git operation concurrency, database traffic, LFS/package growth, indexers and backup working space. Developer count alone cannot size the service. A small personal forge and a build runner have different workloads; building containers can exhaust CPU, RAM and disk even when the web UI is quiet.

Choose a current VPS plan with headroom and separate CI runners when jobs are untrusted or resource-intensive. SQLite can be practical for a smaller instance; PostgreSQL has a separate service and recovery path. Neither removes the need to back up repository and object data.

Step 1: Provision the VPS

  1. Create a VPS on DanubeData using the current plan appropriate to your repository and CI load.
  2. Choose Ubuntu 24.04 LTS as the OS.
  3. Add your SSH public key during provisioning.
  4. Note the public IPv4 and IPv6 addresses.

Initial Server Hardening

# SSH in
ssh root@YOUR_SERVER_IP

# Update everything
apt update && apt upgrade -y

# Install essentials
apt install -y curl wget git ufw fail2ban unattended-upgrades

# Firewall: HTTP(S) and a dedicated git SSH port
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 2222/tcp   # SSH port for git pushes
ufw enable

# Auto security updates
dpkg-reconfigure --priority=low unattended-upgrades

# Hostname
hostnamectl set-hostname git

Note: we'll use port 2222 for git SSH pushes instead of the default 22. This lets Forgejo listen on its own SSH port inside Docker without clashing with the host's SSH daemon.

Step 2: Install Docker

Install Docker Engine and the Compose plugin using the official instructions for your Ubuntu version. Record docker --version and docker compose version. Review scripts before executing them with root privileges.

Step 3: DNS

Create an A record and, if IPv6 routing works, an AAAA record:

Type   Name    Value              TTL
A      git     YOUR_IPV4          300
AAAA   git     YOUR_IPV6          300

Wait for propagation:

dig git.yourdomain.com +short
# Should return your IPs

Step 4: Docker Compose — Forgejo + Postgres + Caddy

Create the working directory:

mkdir -p /opt/forgejo
cd /opt/forgejo

SQLite vs Postgres: Which Should You Pick?

Criterion SQLite PostgreSQL
Setup effort Zero — just works One extra container
Backup Copy the stopped database or use a supported SQLite backup pg_dump
Concurrent writes Single writer Multi-writer
Team size 1-5 active devs Size and tune for workload
CI load Struggles under high Actions load Measure database and storage pressure
Upgrade path Convert via dumper Straight upgrades

Our recommendation: start with Postgres from day one. The marginal effort is 15 lines of YAML, and you never have to think about migration later. If you're really just hosting dotfiles for yourself, SQLite is fine — swap the DB env vars in the compose file below for FORGEJO__database__DB_TYPE=sqlite3.

docker-compose.yml

cat > docker-compose.yml << 'EOF'
services:
  forgejo:
    image: codeberg.org/forgejo/forgejo:17.0.1
    container_name: forgejo
    restart: unless-stopped
    environment:
      - USER_UID=1000
      - USER_GID=1000
      - FORGEJO__database__DB_TYPE=postgres
      - FORGEJO__database__HOST=db:5432
      - FORGEJO__database__NAME=forgejo
      - FORGEJO__database__USER=forgejo
      - FORGEJO__database__PASSWD=${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
      - FORGEJO__server__DOMAIN=git.yourdomain.com
      - FORGEJO__server__ROOT_URL=https://git.yourdomain.com/
      - FORGEJO__server__SSH_DOMAIN=git.yourdomain.com
      - FORGEJO__server__SSH_PORT=2222
      - FORGEJO__service__DISABLE_REGISTRATION=true
      - FORGEJO__service__REQUIRE_SIGNIN_VIEW=false
      - FORGEJO__mailer__ENABLED=false
      - FORGEJO__server__LFS_START_SERVER=true
      - FORGEJO__lfs__PATH=/data/lfs
    volumes:
      - ./data:/data
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
    ports:
      - "2222:22"
    depends_on:
      - db

  db:
    image: postgres:16-alpine
    container_name: forgejo-db
    restart: unless-stopped
    environment:
      - POSTGRES_USER=forgejo
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
      - POSTGRES_DB=forgejo
    volumes:
      - ./postgres:/var/lib/postgresql/data

  caddy:
    image: caddy:2-alpine
    container_name: forgejo-caddy
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
      - caddy-data:/data
      - caddy-config:/config
    depends_on:
      - forgejo

volumes:
  caddy-data:
  caddy-config:
EOF

Version boundary: this example pins Forgejo 17.0.1 and PostgreSQL 16. For an existing installation, follow the documented upgrade route and version-specific breaking-change checks before changing the live database; do not copy a new-install image tag onto an existing deployment without that review. Record the image digest after pulling and preserve the original version for recovery. The local recovery fixture below tests Forgejo 17.0.1 with SQLite, not this Compose/PostgreSQL deployment.

Before starting, create an owner-only .env file containing a generated POSTGRES_PASSWORD. Keep it out of git, backups in plaintext and terminal transcripts. Compose uses the same value for both services. Review docker compose config privately because it can show resolved secrets. Gitea is a separate versioned product: follow its own installation and migration instructions rather than merely changing this image name.

Caddyfile

cat > Caddyfile << 'EOF'
git.yourdomain.com {
    reverse_proxy forgejo:3000

    # Security headers
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains"
        X-Content-Type-Options nosniff
        X-Frame-Options DENY
        Referrer-Policy strict-origin-when-cross-origin
        -Server
    }

    # Gzip and zstd
    encode gzip zstd

    # Don't buffer large pushes/LFS uploads
    request_body {
        max_size 5GB
    }

    log {
        output file /var/log/caddy/access.log
        format json
    }
}
EOF

Step 5: Launch and Install

# Create the data dirs with correct ownership (UID 1000 = forgejo inside container)
mkdir -p data postgres
chown -R 1000:1000 data

# Bring everything up
docker compose up -d

# Watch the logs until you see "Listen: http://0.0.0.0:3000"
docker compose logs -f forgejo

Open https://git.yourdomain.com. You'll land on the installation wizard.

Key settings to confirm:

  • Database: PostgreSQL, host db:5432, database forgejo, user forgejo — should be pre-filled from env vars.
  • Application URL: https://git.yourdomain.com/
  • SSH server domain: git.yourdomain.com
  • SSH port: 2222 (what external clients see)
  • Admin account: create one now — otherwise the first user who registers becomes admin.

Click Install. After 10–20 seconds you're redirected to a logged-in dashboard.

Bootstrap privately and keep registration disabled

Keep initial setup behind a trusted firewall or private access until the administrator is created. The Compose environment above disables public registration. Set FORGEJO__service__REQUIRE_SIGNIN_VIEW=true as well if repository visibility should require login, and recreate the service after changing environment settings. An environment value can overwrite a manual app.ini edit on restart.

The standard image uses its own SSH service. The example maps host port 2222 to container port 22; it does not start an additional embedded SSH listener on that same port. Check the chosen image's SSH mode before changing these settings.

Step 6: SSH Access for Git

Clients clone over port 2222:

git clone ssh://git@git.yourdomain.com:2222/yourname/yourrepo.git

That's ugly. Make it clean by configuring a host alias in ~/.ssh/config on each developer's machine:

Host git.yourdomain.com
    HostName git.yourdomain.com
    Port 2222
    User git
    IdentityFile ~/.ssh/id_ed25519

Now clones work with the natural form:

git clone git@git.yourdomain.com:yourname/yourrepo.git

Users add their SSH public keys via Settings → SSH / GPG Keys in the web UI.

Step 7: Forgejo Actions and runner isolation

Forgejo Actions uses familiar workflow concepts but is not identical to GitHub Actions. Follow the versioned Actions administrator guide and selected runner's documentation. Check action URLs, runner labels, cache/artifact support, token scope and event semantics in the exact versions you deploy.

Use a separate runner host or strong disposable isolation for untrusted code. Mounting the host Docker socket grants jobs substantial host control; do not put that runner beside the forge database and backup credentials without an explicitly trusted workload model. Register runners through protected local configuration and keep tokens out of Compose files committed to git.

Start with a harmless canary on a runner registered only for the recovery/test repository:

name: Recovery canary
on:
  workflow_dispatch:
jobs:
  verify:
    runs-on: recovery-canary
    steps:
      - run: printf '%s\n' 'isolated recovery runner is alive'

Choose a runner label that exists in your isolated environment. Enable and run CI only after the forge restore is accepted, with no deployment secrets and no route to production. This canary was not executed by the downloadable data-recovery fixture; its Actions service is deliberately disabled.

Step 8: Container and package registries

Forgejo has package registry support, including OCI images. Use an appropriately scoped token through a credential manager and docker login --password-stdin; do not paste it into shell history. Follow the container registry documentation for the deployed version. Test token permissions rather than assuming a workflow token can publish every package.

# Supply the token through an approved local secret workflow.
printf '%s' "$FORGEJO_PACKAGE_TOKEN" |   docker login git.yourdomain.com -u yourname --password-stdin
docker tag myapp:tested git.yourdomain.com/yourname/myapp:tested
docker push git.yourdomain.com/yourname/myapp:tested

Registry/package data has its own storage backend. Backing up Git repositories alone will not recover it. Retain the selected image manifests and blob data together and test a representative pull after recovery.

Step 9: Git LFS

The Compose example explicitly enables the LFS server. In a client repository, install Git LFS, track the chosen patterns and commit .gitattributes:

git lfs install
git lfs track '*.psd' '*.mp4' 'assets/**'
git add .gitattributes
git commit -m 'Track large files with LFS'
git push

A Git commit stores an LFS pointer, not the object's bytes. Include the actual configured LFS directory or external storage in every recovery plan. Verify both a fresh clone and an LFS fetch, then hash the downloaded object. Disk sizing and proxy upload limits must accommodate real object sizes. Changing the LFS backend configuration is not, by itself, a transfer of existing objects.

Step 10: Migrate from GitHub

Rehearse the built-in repository migration flow with one representative private repository and the least-privilege source token that permits its selected data. Select the required issues, pull requests, labels, milestones, releases and wiki options, then reconcile their results. Test LFS and package assets separately. GitHub-specific projects, automation and integrations need explicit replacement work.

Move a representative workflow first. Forgejo can discover workflow directories differently from GitHub, and introducing .forgejo/workflows can change which directory is selected. Do not assume the two workflow directories merge. Validate action sources, labels, secrets, artifacts, package publishing and branch protection on the destination. The migration postmortem covers actual failures and retained dependencies.

Step 11: Back up one consistent recovery point

A Git mirror is useful but does not restore your forge's users, issues, PRs, reviews, settings, LFS objects, release assets or packages. The Forgejo 17 backup guide recommends shutting Forgejo down to coordinate its database and files. This guide uses that simpler maintenance-window approach.

Inventory every configured store before stopping

  • Database: SQLite file or an engine-native PostgreSQL/MySQL backup, with the matching version recorded.
  • Repositories: bare repository storage, wikis and custom repository paths.
  • Bulk objects: LFS, packages/OCI blobs, release and issue attachments, avatars and any retained Actions logs/artifacts.
  • Configuration: app.ini, Compose/environment files, custom templates, signing/encryption keys and SSH host keys.
  • Other state: external queues, object stores and required indexes, plus runner configuration according to your own recovery scope.

Inspect the versioned storage settings. Local defaults and rootless-image paths differ, and external S3 data does not appear in the container volume. A complete local /data copy covers the lab's default SQLite/local configuration; it is not proof of coverage for a customized deployment.

PostgreSQL Compose backup example

The following is for the earlier /opt/forgejo Compose layout, whose data/ bind mount contains all Forgejo-local storage and whose database is service db. It assumes operators have stopped external runners, Git writes and any other direct writers. If any store is remote, include its coordinated export before restarting. Run as an administrator in a planned maintenance window.

#!/usr/bin/env bash
set -euo pipefail
umask 077
cd /opt/forgejo
stamp=$(date -u +%Y%m%dT%H%M%SZ)
backup="/srv/forgejo-backups/$stamp"
mkdir -p "$backup"
# Keep exact versions and configuration with this recovery point.
docker compose images > "$backup/images.txt"
cp docker-compose.yml Caddyfile .env "$backup/"
docker compose stop forgejo
# From here, failures intentionally leave the forge stopped for investigation.
docker compose exec -T db pg_dump -U forgejo -d forgejo   --format=custom > "$backup/forgejo.dump.partial"
mv "$backup/forgejo.dump.partial" "$backup/forgejo.dump"
tar --numeric-owner -czpf "$backup/data.tar.gz" data
(cd "$backup" && sha256sum forgejo.dump data.tar.gz   docker-compose.yml Caddyfile .env images.txt > SHA256SUMS)
# Include any external-store backup and verify it before this restart.
docker compose start forgejo

This Linux example avoids a pipeline that could hide a failed dump, keeps one stopped recovery point, and does not delete older backups. Back up credential-bearing files only into encrypted storage. If recovery files are elsewhere, replace these exact paths and include them. Keep the database role/credential recovery procedure independently available.

Upload the completed bundle to an independently recoverable destination. The Restic guide covers encrypted off-host copies, observable failures and restore verification. Do not claim a fixed retention duration without checking storage growth, actual retention and the ability to recover the repository password.

Restore onto a scratch host before calling it a backup

  1. Create a separate host, Compose project or containers. Block SMTP, webhooks, mirrors and runners from reaching production; a restored database can contain active schedules and tokens.
  2. Retrieve the selected recovery bundle and verify SHA256SUMS before extracting it. Treat its configuration and database as secrets.
  3. Use the same Forgejo version and compatible database version as the backup. Recover first; perform upgrades as a separate operation afterward.
  4. Restore files to their recorded paths and ownership. Create an empty destination database and restore its archive with errors treated as fatal.
  5. Restore any external object stores and required queues to that same recovery point. Configure scratch endpoints and disable outbound integrations before starting the forge.
  6. Start only the scratch forge, verify login and content, then explicitly enable only the isolated checks required.
# Scratch-host example only. No source services or volumes may be mounted here.
cd /srv/forgejo-restore
(cd /path/to/selected-backup && sha256sum -c SHA256SUMS)
# Extract the verified local-data archive into this empty scratch layout.
tar --numeric-owner -xzpf /path/to/selected-backup/data.tar.gz
# After creating scratch Compose configuration and its empty forgejo database:
docker compose -p forgejo-restore up -d db
# Wait for pg_isready to succeed before restoring.
docker compose -p forgejo-restore exec -T db   pg_restore -U forgejo -d forgejo --exit-on-error   < /path/to/selected-backup/forgejo.dump
# Configure isolated domains/outbound settings before starting Forgejo.
docker compose -p forgejo-restore up -d forgejo

Run the checksum command from the bundle directory or use a path arrangement that resolves every manifest entry; the example path must be adjusted to the actual restored bundle. Never reuse the original Compose service's fixed container names on the same Docker host: remove/change them in the scratch file, and use different ports, directories and volumes. A different Compose project name alone does not isolate fixed names or bind mounts.

Acceptance checks for a complete forge

Authenticate as a restored user and freshly clone a private repository. Compare commit IDs, branches and tags to the pre-backup manifest; run git fsck --full. Fetch a known LFS object and verify its SHA-256, download a release/issue attachment, and pull a representative package or OCI image. Check issue/PR numbers, comments and permissions rather than accepting a working homepage as proof. Verify user access boundaries as well as administrator access.

For the earlier LFS example, run git lfs pull in a fresh clone and compare hashes to your recorded originals. Hashing an LFS pointer file alone does not check the object. If your forge has a runner, use a separate recovery-only runner without production secrets and run a harmless workflow after data acceptance. Record that result separately.

Download the executed Forgejo recovery lab

Download the Forgejo 17.0.1 restore fixture. Run python3 lab.py with Python 3, Docker, Git and curl available. It uses synthetic credentials, random loopback-only ports and uniquely named disposable containers. The application uses SQLite and local storage; no production token or remote bucket is involved.

The fixture creates a private repository, a commit, issue/PR metadata, a real LFS object, a generic package and a release attachment. It stops the source, copies the complete /data tree, restores a distinct container at the same version and verifies all stopped file hashes before startup. It then verifies an authenticated clone and commit, the issue/PR metadata, LFS SHA-256, package bytes and release attachment bytes. The download records the resolved image ID and results.

This proves the local SQLite/full-data route for the fixture's storage configuration. It does not prove the PostgreSQL Compose example, external S3, SSH clone, an OCI registry pull, the complete access model or runner recovery. Perform those additional drills where your deployment uses them. Do not point this disposable fixture at an existing instance.

Step 12: Production operation

  • Accounts: require appropriate administrator authentication and review account offboarding, active sessions, tokens and SSH keys.
  • Repositories: test branch protection, review requirements, visibility and workflow permissions.
  • Integrations: verify webhook signatures and scope tokens to their actual job.
  • Monitoring: observe disk/inodes, database health, failed jobs, backup freshness and restore-drill age; restrict any metrics endpoint appropriately.
  • Logs: rotate host/container logs without losing incident evidence required by your organization.
  • Updates: follow the official upgrade route, review breaking changes and rehearse recovery before each significant upgrade.

When to move the database to a managed service

Use measured database pressure and required operational support, not a fixed developer threshold. Managed PostgreSQL can change who operates the database; it does not back up your repositories, LFS or package storage. Rehearse the version, role/grant and extension compatibility, freeze Forgejo writes for the final move, use verified TLS and define the rollback boundary. See the PostgreSQL migration checklist for those checks.

Total cost and responsibilities

Add the forge host, database, object storage, runner CPU/RAM/disk, outbound transfer, independent backups, monitoring and staff time. Include the cost of replacing GitHub-specific workflows and integrations. Compare current hosted-seat terms with current VPS, database and storage plans. The old three-year savings table omitted much of this work and has been removed.

Troubleshooting

SSH authentication fails

Verify the user's registered public key, hostname, mapped port and SSH service mode. Use ssh -vT -p 2222 git@git.yourdomain.com and the forge logs. After recovery, preserve host-key validation rather than disabling it.

The runner cannot register or run jobs

Check the exact runner/Forgejo versions, enrollment token, outbound TLS connectivity and advertised labels. Test an isolated workflow before adding deployment credentials. Consult the runner's current error rather than assuming every registration failure is an expired token.

LFS or attachment upload receives 413

Check the reverse proxy and application's configured limits against the actual file size. Also confirm storage space and the LFS endpoint. A higher proxy limit does not repair a missing LFS object after restore.

A package pull or push is unauthorized

Check user/package ownership, token scope and the registry hostname. Test with a newly scoped credential in the scratch environment; do not broaden every token to administrator.

Frequently asked questions

Is Forgejo a drop-in GitHub Actions replacement?

No universal percentage applies. Test the workflow syntax, events, action sources, runner labels, artifacts, cache and token permissions used by your repositories. GitHub-specific APIs and services remain separate dependencies.

Does a Git mirror restore my forge?

It restores selected Git data, not the complete collaboration database, LFS bytes, packages, secrets or integrations. Recover every configured store from one coherent recovery point.

Can Gitea and Forgejo databases be swapped?

Use the exact versions' supported migration instructions. Shared ancestry does not guarantee bidirectional schema compatibility. Preserve the original backup and recover to the original version before attempting an upgrade or product migration.

Can runners stay private?

Runners can connect outward to the forge, but job execution still needs an isolation and credential model. Public inbound reachability is a separate question from whether a job can compromise a host through its Docker socket or network access.

What about SSO and LDAP?

Check the chosen project's version and edition for supported authentication sources. Test login and offboarding, including existing sessions, API tokens and SSH keys. Disabling an identity-provider account does not by itself prove every forge access path was revoked.

Will external S3 storage automatically recover with the database?

No. Configure and back up its exact subsystem paths/buckets, restore object bytes and verify representative downloads with hashes. Reconfiguring a backend or listing its keys is not proof that those bytes are recoverable.

Get started with a recovery requirement

Choose a VPS, bootstrap privately, set up Git and a deliberately isolated runner, migrate one repository, and run a complete recovery drill before expanding. Use Object Storage for independently recoverable backup data if it fits your tested design. Owning the forge means owning the evidence that your team can restore it.

Browse all articles
DevOps12 min read

GitHub Went Down. We Found It Inside Our Control Plane.

A GitHub incident stopped more than code review: it exposed a hidden dependency in our infrastructure control plane. Here is how we moved nine repositories and our core CI/CD workflows to Forgejo in one day, what broke, and why we deliberately left some systems behind.

Adrian Silaghi730 views

Ready to get started?

Deploy your infrastructure in minutes with DanubeData's managed services.