Skip to content [Tab]
~/posts/devops/deploying-and-managing-git-repositories-with-self-hosted-forgejo.md
$ stat -x deploying-and-managing-git-repositories-with-self-hosted-forgejo.md POSIX filesystem
Access Mode: -rw-r--r-- (0644)
Author: uid:1000(@f7234bv9s8)
File Size: 19.2 KB (1538 words)
Modified:
Flags: --cat="devops,docker,software"

Deploying and Managing Git Repositories with Self-Hosted Forgejo

attachment://featured-image.webp
Selfhosted Forgejo

Forgejo is a lightweight, community-governed, self-hosted Git service written in Go. Because it compiles into a single binary and ships as an official container image, it runs comfortably on minimal hardware (even a 1 vCPU / 1 GB RAM VPS or home server) while providing pull requests, issue tracking, package registries, and integrated CI/CD via Forgejo Actions.

This guide covers the complete lifecycle of a self-hosted Forgejo server: deploying the stack with Docker Compose, configuring SSH and HTTP authentication, pushing and migrating repositories, and governing access and backups.

1. Architecture & Port Planning

When deploying Forgejo on a Linux host using Docker, the most common operational pitfall is SSH port collision. Your Linux host already listens on TCP port 22 for administrative SSH access.

To avoid locking yourself out of your server, you have two choices for Git SSH traffic:

  • Dedicated Container SSH Port (Simplest): Map host port 2222 (or 222) to container port 22 (2222:22). Client .ssh/config files or clone URLs specify port 2222.
  • SSH Passthrough / Separate IP: Bind the host’s administrative sshd to a secondary port or specific interface, freeing port 22 for the Forgejo container.

For the web interface, Forgejo listens on TCP port 3000 inside the container. You can expose port 3000 directly on a trusted local network (LAN/VPN) or bind it to 127.0.0.1:3000 behind a reverse proxy (Caddy, Nginx, or Traefik) for HTTPS in production.

2. Deploying Forgejo with Docker Compose

A production-ready Forgejo deployment pairs the Forgejo application container with a dedicated PostgreSQL database. Forgejo allows you to inject configuration settings directly into its app.ini file using environment variables formatted as FORGEJO__section__KEY.

Step 1: Create the Project Directory

On your server, create an isolated directory for your Compose file and persistent volumes:

Bash

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

Step 2: Create the compose.yaml File

Create /opt/forgejo/compose.yaml with the following configuration. Replace 10.33.0.1 with your server’s LAN IP or domain name:

YAML

networks:
  forgejo:
    external: false

services:
  server:
    image: codeberg.org/forgejo/forgejo:17
    container_name: forgejo
    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=super_secret_db_password
      - FORGEJO__server__DOMAIN=10.33.0.1
      - FORGEJO__server__HTTP_PORT=3000
      - FORGEJO__server__ROOT_URL=http://10.33.0.1:3000/
      - FORGEJO__server__SSH_DOMAIN=10.33.0.1
      - FORGEJO__server__SSH_PORT=2222
      - FORGEJO__server__SSH_LISTEN_PORT=22
      - FORGEJO__repository__ENABLE_PUSH_CREATE_USER=true
      - FORGEJO__repository__ENABLE_PUSH_CREATE_ORG=true
      - FORGEJO__repository__DEFAULT_PUSH_CREATE_PRIVATE=true
    restart: always
    networks:
      - forgejo
    volumes:
      - ./forgejo-data:/data
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
    ports:
      - "3000:3000"
      - "2222:22"
    depends_on:
      - db

  db:
    image: postgres:17-alpine
    container_name: forgejo-db
    restart: always
    environment:
      - POSTGRES_USER=forgejo
      - POSTGRES_PASSWORD=super_secret_db_password
      - POSTGRES_DB=forgejo
    networks:
      - forgejo
    volumes:
      - ./postgres-data:/var/lib/postgresql/data

Step 3: Launch and Initialize the Server

Start the containers in detached mode:

Bash

sudo docker compose up -d

Open [http://10.33.0.1:3000](http://10.33.0.1:3000) in your browser to complete the initial setup wizard:

  1. Verify that the Database Settings are pre-filled from your environment variables.
  2. Under Server and Third-Party Service Settings, enable Disable Self-Registration if this is a private or internal server.
  3. Expand Administrator Account Settings and create your primary admin account. (Creating the admin account here avoids having to use the default root page later).
  4. Click Install Forgejo.

3. Configuring User Access & Authentication

Developers interact with Forgejo repositories over two protocols: SSH (recommended for daily development) and HTTP/HTTPS (useful for CI scripts, submodules, and restricted networks).

Creating Users Without Web UI Friction

When an administrator creates a user via the Web UI (Site Administration -> Identity & Access -> User Accounts), Forgejo enables the User must change password flag by default. While this flag is active, all Git HTTP pushes from that user will fail with 403 Forbidden.

To create a ready-to-use developer account via the CLI without requiring an initial password reset:

Bash

docker exec -u git -it forgejo forgejo admin user create \
  --username devuser \
  --password "StrongInitialPassword123!" \
  --email [email protected] \
  --must-change-password=false

Setting Up SSH Authentication

Generate an Ed25519 SSH key pair on your workstation:

ssh-keygen -t ed25519 -C "devuser@workstation" -f ~/.ssh/id_forgejo

Copy the contents of ~/.ssh/id_forgejo.pub and paste it into Forgejo under Settings -> SSH / GPG Keys -> Add Key.

Configure ~/.ssh/config on your workstation so Git automatically uses the right key, system user (git), and container SSH port (2222):

Host forgejo
    HostName 10.10.0.1 
    User git 
    Port 2222 
    IdentityFile ~/.ssh/id_forgejo 
    IdentitiesOnly yes

Verify your handshake:

ssh -T forgejo # Expected output: Hi there, devuser! You've successfully authenticated...

Setting Up HTTP Access Tokens

For HTTP/HTTPS operations, create a scoped Personal Access Token instead of using your account password:

  1. Go to Settings -> Applications -> Generate New Token.
  2. Set the repository permission dropdown to Read and Write (generates the write:repository scope).
  3. Use your Forgejo username and paste this token as the password when prompted by Git.

4. Creating, Pushing, and Migrating Repositories

Forgejo supports three distinct workflows for bringing repositories onto the server.

Workflow A: Push-to-Create (Terminal-Only Workflow)

Because we set FORGEJO__repository__ENABLE_PUSH_CREATE_USER=true in our compose.yaml above, you do not need to open the Web UI to create a repository before pushing.

From any local directory with an initialized Git repository and at least one commit:

Bash

cd ~/projects/my-existing-app
git init
git add .
git commit -m "Initial commit"

# Push directly to a non-existent repo name; Forgejo creates it automatically:
git remote add origin forgejo:devuser/my-existing-app.git
git push -u origin --all
git push -u origin --tags

Workflow B: Standard Empty Repository Creation

If Push-to-Create is disabled, create the repository container in the Web UI first:

  1. Click + -> New Repository in the top navigation bar.
  2. Enter the Repository Name and leave Initialize Repository unchecked.
  3. Link your local repository and push:
git remote add origin forgejo:devuser/my-existing-app.git git push -u origin --all

Workflow C: Pull-Based Migration & Mirroring (From GitHub, GitLab, or Gitea)

If you are migrating repositories from another host, Forgejo’s built-in migrator can pull not only the Git history, but also issues, pull requests, labels, milestones, and releases:

  1. Click the + icon in the top-right corner and select New Migration.
  2. Select the source service (GitHub, GitLab, Gitea, Forgejo, or plain Git).
  3. Enter the clone URL and an access token from the source platform.
  4. (Optional) Check This repository will be a mirror if you want Forgejo to periodically pull changes from the upstream source automatically (pull mirror).

5. Day-to-Day Repository Management

Once your code is hosted in Forgejo, take advantage of its built-in governance and automation tools to protect your codebase.

Organizing with Organizations and Teams

Instead of hosting shared projects under a single user’s personal namespace (devuser/project), create an Organization (+ -> New Organization):

  • Group repositories under a common namespace (e.g., backend-team/api-service).
  • Create granular Teams (e.g., Developers, Reviewers, Release Managers) with repository-specific Read, Write, or Admin permissions.

Enforcing Branch Protection

To prevent accidental force-pushes or untested code from landing on main:

  1. Open the repository and navigate to Settings -> Branches.
  2. Click Add New Rule for branch name main.
  3. Enable the following safeguards:
    • Disable Push: Forces all changes to go through a Pull Request.
    • Enable Require Approvals: Set required reviewer count (e.g., 1) and enable Dismiss stale approvals when new commits are pushed.
    • Enable Status Check: Require CI pipelines (Forgejo Actions) to pass before merging is allowed.

Configuring Push Mirrors (Automated Off-Site Replication)

You can configure Forgejo to automatically push every commit made on your self-hosted repository out to an external backup host (such as Codeberg, GitHub, or a secondary Forgejo server):

  1. Go to the repository’s Settings -> Repository and scroll to Mirror Settings.
  2. Enter the remote repository URL, authentication credentials, and check Sync when commits are pushed.
  3. Click Add Push Mirror.

Enabling Forgejo Actions (CI/CD)

Forgejo includes a built-in CI/CD system compatible with GitHub Actions syntax. Workflow YAML files are stored in .forgejo/workflows/ (or .github/workflows/) inside your repository. To execute jobs:

  1. Enable Actions in compose.yaml via FORGEJO__actions__ENABLED=true.
  2. In the Web UI, navigate to Site Administration -> Actions -> Runners -> Create new runner to copy your registration token.
  3. Deploy the forgejo-runner daemon (ideally on a separate VM or container host so heavy builds do not starve the Git server of CPU and RAM) and register it using the token.

6. Backup and Maintenance Best Practices

Because your Docker Compose setup binds all persistent state into two host folders (/opt/forgejo/forgejo-data and /opt/forgejo/postgres-data), backing up your entire Git forge takes only two commands:

  1. Dump the PostgreSQL database cleanly:
    Bashdocker exec -t forgejo-db pg_dumpall -c -U forgejo > /opt/forgejo/db_backup_$(date +%F).sql
  2. Archive the data directory and database dump:
    Bashtar -czvf forgejo_full_backup_$(date +%F).tar.gz \ /opt/forgejo/forgejo-data \ /opt/forgejo/compose.yaml \ /opt/forgejo/db_backup_$(date +%F).sql

Schedule this script via cron or a systemd timer and ship the resulting archive off-server using restic, borg, or rclone so your repositories, SSH keys, and issue history remain recoverable in the event of hardware failure.

@f7234bv9s8 maintainer

Software engineer and writer at notes:own:vision:com.