Skip to content

Ops: Self-Hosting Source Graph ​

A Source Graph instance is one container or one process with a persistent data directory. The fastest way to try it is the Docker image built from the repository:

bash
docker build -t context-sourcegraph .
docker volume create sourcegraph-data
docker run --rm -p 8080:8080 -v sourcegraph-data:/data \
  -e SOURCEGRAPH_ORIGIN=http://localhost:8080 \
  -e SOURCEGRAPH_SEED_DEMO=true \
  context-sourcegraph

Open http://localhost:8080/sourcegraph/. With SOURCEGRAPH_SEED_DEMO=true it registers two public example repositories; public GitHub repositories need no token, and a custom Git host can be added under Settings or in a startup file, as described in Registering and Managing Repositories. Without sign-in providers the site is anonymous and read-only. Add Google or GitHub sign-in to administer it, as described in Ops: Sign-in and Permissions.

The image contains four binaries: the service repo-service, the command-line client sourcegraph-cli, the Git credential helper and the Zoekt search server. It runs as an unprivileged user with /data as its data root and port 8080 exposed.

Build from source ​

Building locally needs Go, Bun and Git, at the versions the repository's build files require. Monorepo path groups need Git 2.30 or newer for selective file hydration; the supplied container already includes a compatible Git:

bash
bun install --frozen-lockfile
bun run build:web
bun run build
SOURCEGRAPH_DATA_ROOT="$PWD/.tmp/data" SOURCEGRAPH_ORIGIN=http://localhost:8080 output/bin/repo-service

output/bin then holds the same four binaries. The service starts the search server itself and manages background indexing; there is nothing else to run. Every setting is an environment variable, and code sources can also be overridden by the startup file that SOURCEGRAPH_CONFIG_FILE names; all are listed in Configuration. Put credentials only in environment variables or your platform's secret store, never in the deployment JSON, source code or images; on first start Source Graph imports them into its database, as described in Application secrets.

Choose a shape ​

Each instance owns its Git mirrors, search indexes and data directory on local disk, and a database holds the shared application state. Choosing a shape is therefore about disk and repository ownership, not about adding replicas.

QuestionOne instance with a large diskSharded instances
RepositoriesFit on one persistent volume, with Git mirrors plus indexesMore than one volume can hold, or you want to spread indexing load
DatabaseSQLite (default) is enoughPostgreSQL or MongoDB shared by every instance; SQLite cannot be shared
RoutingNone; every request goes to the one instanceAn access layer routes each request to the instance that owns its repository
OperationsOne machine, one volume, one backupOne volume per instance, a stable repository mapping and one shared database that also holds the credentials

Start with one instance unless you already know the repositories will not fit. Moving to sharding later means adding a shared database and an access layer; repositories moved to a new instance are fetched and indexed again there.

In both shapes, place instances in the same region as the Agents and services that call them. Search speed comes from local indexes, so cross-region calls add latency that a larger machine does not remove.

mermaid
flowchart TB
  subgraph single["One instance"]
    s1["Instance + large volume<br/>all repositories<br/>SQLite"]
  end
  subgraph sharded["Sharded instances"]
    router["Access layer<br/>routes by repo"] --> a["Instance A + own volume<br/>repositories of shard A"]
    router --> b["Instance B + own volume<br/>repositories of shard B"]
    a --> db[("Shared PostgreSQL<br/>or MongoDB")]
    b --> db
  end

Running one instance ​

  • Size the volume for bare Git repositories plus their indexes. Each repository's storage budget, 100 GiB by default, is enforced by releasing its oldest unprotected snapshots, so the budgets of the repositories you register bound most of the space they use. On top of that, Git compaction and ref-discovery downloads need temporary space under the data directory: ref downloads take at most 4 GiB together, each catalog refresh at most 256 MiB. Keep free space above SOURCEGRAPH_MIN_FREE_BYTES, 1 GiB by default, which stays the instance-wide floor below which fetching, indexing and ref downloads stop, plus room for replacement packs and index builds. See Ops: Day-to-Day Operations.
  • Run exactly one machine for the volume. Two processes must never serve the same repositories or share one data directory, because index ownership is per process.
  • Keep the default SQLite database unless you already operate PostgreSQL or MongoDB.
  • Measure before resizing. Index memory and disk needs depend on repository size, so observe real indexing before changing capacity.
  • Expect brief interruptions on redeploy. Restarting a single instance may interrupt requests and indexing for a moment; persisted tasks recover after the restart.

Running sharded instances ​

  • Share one PostgreSQL or MongoDB database across all instances, and give each instance its own data volume.
  • Keep credentials in the shared database. Application secrets and their encryption key are stored there, so every instance reads the same ones. When upgrading existing instances, import the original credential key before a replacement instance initializes the database; never replace it with a new key.
  • Give each repository exactly one owner. Assign repositories to instances with consistent hashing or an explicit repository-to-instance table, and keep that mapping stable.
  • Route by the repository named in the request: the repo query parameter over HTTP and the repo argument of an MCP tool call, in owner/repository form. Requests not tied to one repository, such as listing repositories, may go to any instance.
  • Scale by adding shards, never replicas. On Fly.io this means one App per shard behind your routing layer, not several Machines in one App, because Machines of one App would share repositories.

Choose a database ​

DatabaseSOURCEGRAPH_DATABASEUse when
SQLite (default)sqliteOne instance. The file defaults to /data/sourcegraph.db, with write-ahead logging and full synchronous commits
PostgreSQLpostgresShared state for sharded instances, or an existing managed database. Uses serializable transactions
MongoDBmongodbShared state on MongoDB. Sign-in admission needs transactions, so use a replica set or a managed cluster

Pass the connection in DATABASE_URL: a SQLite file path, a PostgreSQL DSN or a MongoDB URI. Changing the database does not migrate data, so start with an empty destination or run a separately reviewed export and import. An external database never replaces the instance's persistent volume, which still holds Git mirrors and indexes.

Application secrets ​

The database also stores the instance's application secrets, encrypted with AES-256-GCM together with their key: code-source tokens, the service API credential and the Google/GitHub sign-in configuration. This removes the separate key file on the host; it does not protect against disclosure of the whole database, so restrict database access and protect its backups.

  • Upgrading an existing instance: the first start imports SOURCEGRAPH_CREDENTIAL_KEY if it is set, otherwise the existing code-credentials.key in the data root, so stored tokens stay readable. Keep the environment secrets and the old key file during the first rollout so the previous image still works on its volume. Never start a replacement host against an old database without importing its original key first.
  • Fresh databases generate their own key and create no key file.
  • Afterwards the database is authoritative: environment values only fill missing records, and changing one does not rotate an existing secret. Rotating a secret is a maintenance change to the database record, followed by checking the new credential; do not delete the encryption key to rotate a token.

Example: Fly.io and the public demo ​

The repository's fly.toml deploys one instance with a sourcegraph_data volume mounted at /data and a platform health check on the liveness endpoint. To deploy your own, create the App and a volume of at least 20 GB, then deploy once:

bash
fly apps create <app-name>
fly volumes create sourcegraph_data --region <region> --size 20 --app <app-name>
fly deploy --remote-only --ha=false

After a deployment, check liveness and readiness as described in Ops: Day-to-Day Operations.

The Source Graph behind this documentation site is deployed this way. It is a demo, not a capacity recommendation: two Fly.io Apps in the sin region.

AppRoleMachine
Portalnginx serving the home page, the Context documentation site and llms.txt, and reverse-proxying /sourcegraph/One shared CPU, 256 MB, auto-stop off
Source GraphOne instance deployed from the repository's fly.tomlOne shared CPU, 1 GB, auto-stop off, volume sourcegraph_data at /data, SQLite, demo seeding on

The Portal forwards the whole /sourcegraph/ prefix to the Source Graph App over the Fly private network, so the instance is reachable under the site's own domain, https://context4ai.org/sourcegraph/, without a second public hop. It is also reachable through each App's own Fly address:

The MCP endpoint is /sourcegraph/mcp under every entrance. The demo serves four repositories anonymously and read-only, each following its main branch:

RepositoryHow it got there
context4ai/context, context4ai/sourcegraphRegistered by demo seeding
context4ai/portal, context4ai/agent-graphRegistered by the maintainers

Because context4ai/portal is this site's knowledge workspace, the demo serves the knowledge and the code it cites side by side: Agents can read both remotely, including through a plain MCP client as described in Querying Through MCP in Your Agent. The demo repository's own pipeline deploys to Fly after a successful build of main.

If you put Source Graph behind another site, proxy the whole prefix while preserving query strings, cookies and authorization, keep the configured external origin fixed, and do not cache sign-in, API or MCP responses.

Back up and restore ​

Source Graph has no built-in backup job. Back up three things outside the machine, with restricted access: the entire database, including its secrets and credential records, the runtime storage configuration and the repository metadata. Indexes and bare Git mirrors can be rebuilt from the remotes; identities, settings, credentials and their key cannot. Keep a legacy code-credentials.key only for restoring backups taken before the upgrade.

  • SQLite: use the online backup API; never copy a live sourcegraph.db on its own. For example: sqlite3 /data/sourcegraph.db '.backup /data/sourcegraph-backup.db', then copy the result and the runtime configuration files away. Alternatively stop the service and copy the database with its write-ahead log.
  • PostgreSQL: pg_dump. MongoDB: your replica-set or managed-cluster backup.

To restore, stop the instance, restore the complete database and the runtime configuration (for a pre-upgrade backup, also its matching legacy key), start one instance, and check administrator access, repository metadata and index recovery. Rolling back the image and restoring the database are separate operations; keep a known-good image and take a backup before upgrades.

运维:自行部署 Source Graph ​

一个 Source Graph 实例就是一个容器或一个进程,外加一个持久化的数据目录。最快的试用方式是使用从仓库构建的 Docker 镜像:

bash
docker build -t context-sourcegraph .
docker volume create sourcegraph-data
docker run --rm -p 8080:8080 -v sourcegraph-data:/data \
  -e SOURCEGRAPH_ORIGIN=http://localhost:8080 \
  -e SOURCEGRAPH_SEED_DEMO=true \
  context-sourcegraph

打开 http://localhost:8080/sourcegraph/。设置 SOURCEGRAPH_SEED_DEMO=true 后,实例会登记两个公开示例仓库;公开的 GitHub 仓库无需令牌,自定义 Git 托管地址可以在设置中或启动文件里添加,详见 登记和管理仓库。未配置登录提供方时,站点是匿名且只读的;要管理站点,请添加 Google 或 GitHub 登录,详见 运维:登录与权限。

镜像包含四个二进制文件:服务 repo-service、命令行客户端 sourcegraph-cli、Git 凭据助手和 Zoekt 搜索服务器。它以非特权用户运行,数据根目录为 /data,暴露 8080 端口。

从源码构建 ​

本地构建需要 Go、Bun 和 Git,版本以仓库构建文件的要求为准。Monorepo 路径组需要 Git 2.30 或更高版本来按需补全文件;提供的容器已包含兼容的 Git:

bash
bun install --frozen-lockfile
bun run build:web
bun run build
SOURCEGRAPH_DATA_ROOT="$PWD/.tmp/data" SOURCEGRAPH_ORIGIN=http://localhost:8080 output/bin/repo-service

构建完成后,output/bin 中包含同样的四个二进制文件。服务会自行启动搜索服务器并管理后台建索引,无需运行其他组件。所有设置都是环境变量,代码源还可以由 SOURCEGRAPH_CONFIG_FILE 指定的启动文件覆盖;全部设置列在 配置 中。凭据只能放在环境变量或平台的密钥存储中,绝不要写进部署 JSON、源代码或镜像;Source Graph 首次启动时会把它们导入数据库,详见 应用密钥。

选择部署形态 ​

每个实例都在本地磁盘上拥有自己的 Git 镜像、搜索索引和数据目录,由数据库保存共享的应用状态。因此,选择部署形态关乎磁盘和仓库归属,而不是增加副本。

问题单个大磁盘实例分片实例
仓库连同 Git 镜像和索引能放进一个持久化卷一个卷放不下,或者你希望分摊建索引的负载
数据库SQLite(默认)即可所有实例共享的 PostgreSQL 或 MongoDB;SQLite 无法共享
路由无需路由;所有请求都发往这一个实例由接入层把每个请求路由到拥有对应仓库的实例
运维一台机器、一个卷、一份备份每个实例一个卷、稳定的仓库映射,以及一个同时保存凭据的共享数据库

除非你已经确定仓库放不下,否则先从单实例开始。之后改为分片,意味着增加共享数据库和接入层;迁到新实例的仓库会在那里重新拉取并建索引。

无论哪种形态,都应把实例部署在调用它们的 Agent 和服务所在的区域。搜索速度来自本地索引,跨区域调用增加的延迟无法靠更大的机器消除。

mermaid
flowchart TB
  subgraph single["单实例"]
    s1["实例 + 大容量卷<br/>全部仓库<br/>SQLite"]
  end
  subgraph sharded["分片实例"]
    router["接入层<br/>按仓库路由"] --> a["实例 A + 独立卷<br/>分片 A 的仓库"]
    router --> b["实例 B + 独立卷<br/>分片 B 的仓库"]
    a --> db[("共享的 PostgreSQL<br/>或 MongoDB")]
    b --> db
  end

运行单实例 ​

  • 按裸 Git 仓库及其索引规划卷容量。每个仓库的存储预算(默认 100 GiB)通过释放其最旧的未受保护快照来落实,因此你登记的各仓库的存储预算决定了它们所用空间的大部分上限。此外,Git 压缩和引用发现的下载还需要数据目录下的临时空间:引用下载合计最多 4 GiB,每次目录刷新最多 256 MiB。让剩余空间保持在 SOURCEGRAPH_MIN_FREE_BYTES(默认 1 GiB)之上,它始终是实例级的下限,低于它时拉取、建索引和引用下载会停止;此外还要为替换用的 pack 文件和索引构建留出空间。见 运维:日常运维与排障。
  • 一个卷只对应一台机器。两个进程绝不能服务同一批仓库或共享同一个数据目录,因为索引归属是按进程划分的。
  • 保留默认的 SQLite 数据库,除非你已经在运维 PostgreSQL 或 MongoDB。
  • 先测量再调整规格。索引所需的内存和磁盘取决于仓库大小,因此先观察真实的建索引情况,再改变容量。
  • 重新部署时会有短暂中断。重启单个实例可能让请求和建索引短暂中断;持久化的任务会在重启后恢复。

运行分片实例 ​

  • 所有实例共享一个 PostgreSQL 或 MongoDB 数据库,并为每个实例分配独立的数据卷。
  • 把凭据保存在共享数据库中。 应用密钥及其加密密钥都存放在那里,因此每个实例读取的是同一份。升级现有实例时,请在替换实例初始化数据库之前导入原有的凭据密钥;绝不要换成新密钥。
  • 每个仓库只能有一个归属实例。用一致性哈希或显式的仓库到实例映射表分配仓库,并保持该映射稳定。
  • 按请求中指定的仓库路由:HTTP 中的 repo 查询参数,以及 MCP 工具调用中的 repo 参数,格式为 owner/repository。不针对单个仓库的请求(例如列出仓库)可以发往任意实例。
  • 通过增加分片来扩容,绝不增加副本。在 Fly.io 上,这意味着每个分片一个 App,放在你的路由层之后,而不是在一个 App 中运行多台 Machine,因为同一个 App 的 Machine 会共享仓库。

选择数据库 ​

数据库SOURCEGRAPH_DATABASE适用场景
SQLite(默认)sqlite单实例。文件默认位于 /data/sourcegraph.db,启用预写日志和完全同步提交
PostgreSQLpostgres分片实例的共享状态,或已有的托管数据库。使用可串行化事务
MongoDBmongodb在 MongoDB 上保存共享状态。登录准入需要事务,因此请使用副本集或托管集群

通过 DATABASE_URL 传入连接信息:SQLite 文件路径、PostgreSQL DSN 或 MongoDB URI。更换数据库不会迁移数据,因此请从空的目标库开始,或执行经过单独评审的导出与导入。外部数据库无法替代实例的持久化卷,卷上仍保存着 Git 镜像和索引。

应用密钥 ​

数据库还保存实例的应用密钥,与其密钥一起用 AES-256-GCM 加密:代码源令牌、服务 API 凭据,以及 Google/GitHub 登录配置。这样主机上就不再需要单独的密钥文件;但它不能防止整个数据库泄露,因此请限制数据库访问并保护其备份。

  • 升级现有实例: 首次启动时,如果设置了 SOURCEGRAPH_CREDENTIAL_KEY 就导入它,否则导入数据根目录中已有的 code-credentials.key,已存储的令牌因此仍可读取。首次发布期间请保留环境中的密钥和旧密钥文件,以便旧镜像仍能在原有卷上运行。绝不要在未先导入原密钥的情况下,让替换主机连接旧数据库。
  • 全新数据库会生成自己的密钥,且不创建密钥文件。
  • 此后以数据库为准:环境变量只会补齐缺失的记录,修改环境变量不会轮换已有密钥。轮换密钥需要对相应数据库记录进行维护变更,并验证新的凭据;不要通过删除加密密钥来轮换令牌。

示例:Fly.io 与公开演示 ​

仓库中的 fly.toml 部署一个实例,数据卷 sourcegraph_data 挂载在 /data,并在存活端点上配置平台健康检查。要部署你自己的实例,先创建 App 和一个至少 20 GB 的卷,然后部署一次:

bash
fly apps create <app-name>
fly volumes create sourcegraph_data --region <region> --size 20 --app <app-name>
fly deploy --remote-only --ha=false

部署完成后,按 运维:日常运维与排障 中的说明检查存活和就绪状态。

本文档站背后的 Source Graph 就是这样部署的。它只是演示,不是容量建议:位于 sin 区域的两个 Fly.io App。

App角色机器
Portalnginx 提供首页、Context 文档站和 llms.txt,并反向代理 /sourcegraph/一个共享 CPU,256 MB,关闭自动停止
Source Graph由仓库的 fly.toml 部署的单个实例一个共享 CPU,1 GB,关闭自动停止,卷 sourcegraph_data 挂载在 /data,SQLite,开启演示数据

Portal 通过 Fly 私有网络把整个 /sourcegraph/ 前缀转发给 Source Graph App,因此实例可以在站点自身的域名 https://context4ai.org/sourcegraph/ 下访问,无需再经过一次公网跳转。它也可以通过两个 App 各自的 Fly 地址访问:

每个入口下的 MCP 端点都是 /sourcegraph/mcp。演示实例以匿名只读方式提供四个仓库,每个都跟随各自的 main 分支:

仓库来源
context4ai/context、context4ai/sourcegraph由演示数据自动登记
context4ai/portal、context4ai/agent-graph由维护者登记

context4ai/portal 正是本文档站的知识工作区,所以演示实例把知识和它引用的代码放在了一起:Agent 可以远程读取两者,即使只用普通的 MCP 客户端也可以,做法见 在 Agent 中通过 MCP 查询。演示仓库自身的流水线会在 main 构建成功后部署到 Fly。

如果把 Source Graph 放在其他站点之后,请代理整个前缀,并保留查询字符串、Cookie 和授权信息,保持配置的外部源地址不变,且不要缓存登录、API 或 MCP 响应。

备份与恢复 ​

Source Graph 没有内置的备份任务。请将以下三项备份到机器之外,并限制访问权限:完整的数据库(包括其中的密钥和凭据记录)、运行时存储配置和仓库元数据。索引和裸 Git 镜像可以从远程仓库重建;身份、设置、凭据及其密钥则无法重建。旧的 code-credentials.key 只需为恢复升级前的备份而保留。

  • SQLite:使用在线备份 API,绝不要单独复制正在运行的 sourcegraph.db。例如:sqlite3 /data/sourcegraph.db '.backup /data/sourcegraph-backup.db',然后将结果连同运行时配置文件复制到别处。也可以先停止服务,再将数据库连同其预写日志一起复制。
  • PostgreSQL:pg_dump。MongoDB:使用副本集或托管集群的备份方案。

恢复时,先停止实例,恢复完整的数据库和运行时配置(升级前的备份还需恢复与之匹配的旧密钥),启动一个实例,然后检查管理员访问、仓库元数据和索引恢复情况。回滚镜像和恢复数据库是两项独立的操作;请保留一个已知可用的镜像,并在升级前做好备份。