---
url: /en/self_host/docker/deploy-v2.md
---
# SwanLab Docker-v2 Self-Hosted Deployment Guide (Recommended) &#x20;

`Docker-v2` is SwanLab's Docker Compose self-hosted deployment architecture. Compared to the [legacy single-instance deployment](./deploy.md), it adds:

* **Multi-replica application services**: Run multiple replicas of SwanLab's application containers behind a built-in load-balancing gateway.
* **High-throughput metric buffering**: Experiment metrics are persisted asynchronously through a high-performance Vector buffer queue for higher throughput and steadier load.
* **Pluggable data services**: Deploy PostgreSQL, Redis, ClickHouse, and object storage as local containers, or connect to external managed or self-hosted services.

![SwanLab Docker](https://swanlab-docs-1301372061.cos.ap-beijing.myqcloud.com/assets/en/guide_cloud/self_host/docker-deploy/swanlab-docker.jpg)

## 1. Prerequisites

| Requirement     | Specification     | Notes                                                                                                                                                                                                                                     |
| --------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Docker Engine   | `>= 20.10`        | Install via [`scripts/install-docker.sh`](https://github.com/SwanHubX/self-hosted/blob/main/scripts/install-docker.sh)                                                                                                                    |
| Docker Compose  | `>= 2.24`         | Required. `docker-v2` uses `include` and `depends_on.required`, which older versions cannot parse. Upgrade via [`scripts/install-docker-compose.sh`](https://github.com/SwanHubX/self-hosted/blob/main/scripts/install-docker-compose.sh) |
| CPU / Memory    | `>= 4 vCPU, 8 GB` | Minimum recommended spec (lower replica counts if running on constrained hardware); scale up for high concurrency or large workloads                                                                                                      |
| Free Disk Space | `>= 50 GiB`       | Each Vector instance reserves ~40 GiB of buffer space by default (+40 GiB per additional instance)                                                                                                                                        |
| Network Port    | `8000` (default)  | Only the gateway port needs to be exposed. Local MinIO S3 traffic is routed by path through the gateway—no need to open port `9000`                                                                                                       |

> When using external object storage, allow outbound network access to your storage service's endpoint and port.

## 2. Installation

:::warning

`docker-v2/` is a template directory—do **not** run `docker compose up -d` inside it. Runtime files are generated by `install.sh` into a separate runtime directory (`./swanlab` by default).

:::

All deployment management scripts (`install.sh`, `upgrade.sh`, `migrate.sh`, `configure.sh`, and `check.sh`) must be run from the `self-hosted/docker-v2/` directory. `<PATH_TO_SWANLAB>` refers to the runtime directory for your self-hosted SwanLab Docker deployment (`./swanlab` in the current directory by default).

```bash
git clone https://github.com/SwanHubX/self-hosted.git
cd self-hosted/docker-v2
./install.sh
```

Follow the prompts to confirm the data directory and port, then choose between a **local container** and an **external instance** for each data service. Press Enter through all prompts to use local containers by default.

| Option                    | Default     | Description                                                                                                           |
| ------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------- |
| `[RUNTIME_DIR]`           | `./swanlab` | First positional argument; directory where `.env`, `docker-compose.yaml`, and other runtime files are generated       |
| `-d <PATH>`               | `./data`    | Data directory (relative to the runtime directory or an absolute path)                                                |
| `-p <PORT>`               | `8000`      | Externally exposed gateway port                                                                                       |
| `-s`                      | Off         | Non-interactive mode; uses local containers for all data services (run `configure.sh` later to connect external ones) |
| `-e`, `--env-file <FILE>` | Auto        | Custom `.env` file for installation; uses `docker-v2/.env` if present, otherwise `.env.example`                       |
| `-o`, `--offline`         | Off         | Offline mode; skips pulling images and verifies that required images already exist locally                            |

To customize defaults before installing (such as port, data path, replica counts, `VECTOR_BUFFER_MAX_SIZE`, or external databases), copy the template in `docker-v2/` and edit it first. The installer picks up `.env` automatically (skipping prompts) and moves it into the runtime directory once done, keeping a single `.env`:

```bash
cp .env.example .env
# Edit .env as needed, then run:
./install.sh
```

The script runs environment checks, generates random credentials for data services, writes `.env`, pulls images, starts the stack, and runs health checks. Database schema migrations are executed automatically by a one-off `server-migrate` container before application services start.

> For air-gapped servers, package the images on an internet-connected host with `scripts/pull-images.sh --v2 --save` and follow the [Offline Deployment Guide](./offline-deployment.md). See the [Image List](./offline-deployment.md#_2-image-list) for all component images.

### 2.1 Post-Install Verification & Access

* Open `http://<SERVER_IP>:<PORT>` (default: `http://localhost:8000`) in your browser. On first visit, activate your admin account as described in [Activate the Primary Account](./deploy.md#_3-activate-the-primary-account), then connect the Python SDK following [Start Your First Experiment](./deploy.md#_4-start-your-first-experiment).
* Run a read-only health check to verify the deployment:

```bash
./check.sh <PATH_TO_SWANLAB>
```

### 2.2 Runtime Directory Layout

Once installed, all runtime files live in the runtime directory. Keep the template directory for upgrades, reconfiguration, and migrations:

```text
swanlab/
├── .env                          # Environment variables and secrets (chmod 600)
├── docker-compose.yaml           # Primary Compose file (overwritten on upgrade; do not edit directly)
├── docker-compose.vector.yaml    # Vector definitions (generated from VECTOR_REPLICAS; do not edit directly)
├── docker-compose.override.yaml  # [Optional] Custom overrides (preserved across upgrades and rollbacks)
├── config/                       # Traefik and Vector configuration files
├── backups/                      # Backups created before upgrades, migrations, and config changes
└── data/                         # postgres / redis / clickhouse / minio / vector-1..vector-N
```

> Put custom services or image overrides in `docker-compose.override.yaml`; `upgrade.sh` only overwrites template-generated files.

### 2.3 Common Environment Variables

Core configuration lives in `<PATH_TO_SWANLAB>/.env`. After changing service replica counts, ports, or other settings, run `docker compose up -d` inside the runtime directory to apply them. `VECTOR_REPLICAS` is an exception and must be changed via `configure.sh` (see [6.3 Scaling Vector Instances](#_6-3-scaling-vector-instances)). If you change `DATA_PATH`, move your existing data directory first.

| Variable                 | Default         | Description                                                                                            |
| ------------------------ | --------------- | ------------------------------------------------------------------------------------------------------ |
| `SWANLAB_VERSION`        | Current release | Application image tag; updated automatically during upgrades                                           |
| `EXPOSE_PORT`            | `8000`          | Exposed gateway port                                                                                   |
| `DATA_PATH`              | `./data`        | Data directory (relative to the runtime directory or an absolute path)                                 |
| `PUBLIC_HOST`            | Empty           | External URL when behind an HTTPS/reverse proxy, e.g. `https://swanlab.example.com` (no trailing `/`)  |
| `SERVER_REPLICAS`        | `2`             | Number of `swanlab-server` replicas                                                                    |
| `AUTH_REPLICAS`          | `2`             | Number of `swanlab-auth` replicas                                                                      |
| `HOUSE_REPLICAS`         | `2`             | Number of `swanlab-house` replicas                                                                     |
| `NEXT_REPLICAS`          | `2`             | Number of `swanlab-next` replicas                                                                      |
| `CLOUD_REPLICAS`         | `1`             | Number of `swanlab-cloud` replicas                                                                     |
| `VECTOR_REPLICAS`        | `1`             | Number of Vector instances; must be applied via `configure.sh` (editing `.env` alone has no effect)    |
| `VECTOR_BUFFER_MAX_SIZE` | `10737418240`   | Disk buffer limit per ClickHouse sink in bytes (10 GiB default; 4 sinks per Vector instance)           |
| `DOCKER_SOCKET_PATH`     | Auto-detected   | Path to the Docker socket; auto-detected when empty (supports standard Docker, Rootless, and OrbStack) |

## 3. Upgrading & Rollback

Use `upgrade.sh` to upgrade an existing Docker-v2 deployment. If you are still on the legacy single-instance setup, complete [4. Migrating from Legacy Docker Deployment](#_4-migrating-from-legacy-docker-deployment) first.

Upgrading causes brief downtime. Schedule a maintenance window and notify active users in advance.

```bash
# Pull the latest repository templates first
cd self-hosted && git pull && cd docker-v2

# Upgrade to the latest version
./upgrade.sh <PATH_TO_SWANLAB>

# Pre-upgrade read-only check
./upgrade.sh <PATH_TO_SWANLAB> --check

# Roll back to a specific backup
./upgrade.sh <PATH_TO_SWANLAB> --rollback <PATH_TO_SWANLAB>/backups/pre-upgrade-<TIMESTAMP>/
```

| Option                    | Default          | Description                                                                                                          |
| ------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |
| `[RUNTIME_DIR]`           | `./swanlab`      | Path to an existing runtime directory                                                                                |
| `(no flags)`              | —                | Run upgrade: back up configs → drain buffered metrics → pull images → run DB migrations → start stack → health check |
| `--check`                 | Off              | Read-only preflight check: version, disk space, config, rendered templates, and container status (makes no changes)  |
| `--version <X.Y.Z>`       | Template version | Target release version                                                                                               |
| `-o`, `--offline`         | Off              | Offline mode; skips pulling images and verifies local images only                                                    |
| `-y`, `--yes`             | Off              | Skip confirmation prompts                                                                                            |
| `--rollback <BACKUP_DIR>` | —                | Roll back to a backup; restores configs and image versions only without modifying the database                       |

* Before upgrading, configuration files are automatically backed up to `<PATH_TO_SWANLAB>/backups/pre-upgrade-<TIMESTAMP>/`. We recommend backing up your data separately before major version upgrades.
* Failed upgrades do not roll back automatically—the script keeps the backup and exits so you can review the saved configuration and decide whether to roll back.
* `docker-compose.override.yaml` is preserved across both upgrades and rollbacks.
* `--check` and `--rollback` cannot be used together.

## 4. Migrating from Legacy Docker Deployment

Use `migrate.sh` to migrate a legacy single-instance Docker deployment to Docker-v2:

```bash
# Recommended: migrate into a new directory while leaving the legacy directory intact (requires rsync)
./migrate.sh <PATH_TO_OLD_SWANLAB> --to <PATH_TO_SWANLAB>

# In-place migration
./migrate.sh <PATH_TO_OLD_SWANLAB>
```

| Option                   | Default  | Description                                                                                                                                                                            |
| ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<PATH_TO_OLD_SWANLAB>`  | Required | Legacy runtime directory (containing `.env`, `docker-compose.yaml`, `data/`), **not** the repository's `docker/` template directory                                                    |
| `--to <PATH_TO_SWANLAB>` | In-place | Migrate into a new directory while preserving the legacy directory; target must be empty or non-existent, requires `rsync`, and needs free space matching the legacy `data/` directory |
| `-o`, `--offline`        | Off      | Offline mode; skips pulling images and verifies local images only                                                                                                                      |
| `-y`, `--yes`            | Off      | Skip confirmation prompts (required in non-interactive environments)                                                                                                                   |

:::warning

* **Only all-local legacy to all-local Docker-v2 migrations are supported.** To switch to external database services after migrating, see [5. Configuring Data Services](#_5-configuring-data-services).
* We recommend migrating into a new directory with `--to` (requires `rsync`; install via `apt install -y rsync` or `yum install -y rsync` if missing), and removing the legacy directory only after verifying stability so you can easily roll back if needed.
* To roll back: run `docker compose down` in `<PATH_TO_SWANLAB>`, then run `docker compose up -d` in `<PATH_TO_OLD_SWANLAB>`.

:::

## 5. Configuring Data Services

PostgreSQL, Redis, ClickHouse, and object storage can each be mixed and matched between local containers and external instances. If you didn't configure external services during installation—or want to change data connections later—use `configure.sh`.

```bash
./configure.sh <PATH_TO_SWANLAB> --status    # Read-only view of current topology
./configure.sh <PATH_TO_SWANLAB>             # Interactive reconfiguration
./configure.sh <PATH_TO_SWANLAB> --vector 2  # Scale Vector instances only
```

| Option          | Default       | Description                                                                          |
| --------------- | ------------- | ------------------------------------------------------------------------------------ |
| `[RUNTIME_DIR]` | `./swanlab`   | Path to an existing runtime directory                                                |
| `--status`      | Off           | Print current data service topology and Vector replica count (safe for scripts / CI) |
| `--vector <N>`  | Current value | Set Vector instance count (`N >= 1`) without prompting for data services             |
| `(no flags)`    | —             | Interactive mode: reconfigure data services, then set the Vector instance count      |

Interactive prompt notes:

* For each service, choose `1` (local container) or `2` (external instance), or press Enter to keep the current setting.
* Values in `[brackets]` show the current `.env` setting; press Enter to keep them unchanged.
* The script updates `.env` and recreates only affected containers. Local data containers switched to external instances are removed, while their data directories are preserved in case you switch back.
* `COMPOSE_PROFILES` is managed automatically—no need to edit it manually.

When connecting external data services, `configure.sh` requires the following details:

| Service    | Variables                                                                                                                                                                                                  |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| PostgreSQL | `DATABASE_URL` (database connection string); `DATABASE_URL_REPLICA` (read-replica connection string, optional)                                                                                             |
| Redis      | `REDIS_URL`                                                                                                                                                                                                |
| ClickHouse | `CLICKHOUSE_HOST`, `CLICKHOUSE_HTTP_PORT`, `CLICKHOUSE_TCP_PORT`, `CLICKHOUSE_DATABASE`, `CLICKHOUSE_USER`, `CLICKHOUSE_PASSWORD`                                                                          |
| S3         | `SS_STORAGE_TYPE=remote`; `S3_PUBLIC_*` / `S3_PRIVATE_*` (`ENDPOINT`, `REGION`, `BUCKET`, `DOMAIN`, `ACCESS_KEY`, `SECRET_KEY`, `PORT`, `USE_SSL`, `PATH_STYLE`) — bucket configuration for object storage |

:::warning

`configure.sh` updates connection targets only—it **does not migrate data**. Before switching to external instances, create the target databases and object storage buckets in advance (custom bucket names are supported; schemas are initialized automatically by `server-migrate`, while existing data must be migrated manually).

:::

## 6. Operations & Maintenance

### 6.1 Health Checks & Logs

```bash
# Read-only health check
./check.sh <PATH_TO_SWANLAB>

# View container status
cd <PATH_TO_SWANLAB> && docker compose ps

# Follow logs for a service (see docker compose ps for service names)
cd <PATH_TO_SWANLAB> && docker compose logs -f swanlab-server
```

`check.sh` arguments and exit codes:

| Option          | Default     | Description                                       |
| --------------- | ----------- | ------------------------------------------------- |
| `[RUNTIME_DIR]` | `./swanlab` | Path to an existing runtime directory (read-only) |

Exit codes: `0` = healthy (warnings may still be printed), `1` = unhealthy / error detected, `2` = runtime directory not found.

### 6.2 Scaling Application Services

Update the corresponding `*_REPLICAS` variables in `<PATH_TO_SWANLAB>/.env`, then run `docker compose up -d` inside the runtime directory. Traffic to `server`, `auth`, `house`, and `next` is load-balanced by the gateway and can be scaled up or down anytime.

### 6.3 Scaling Vector Instances

Each Vector instance owns a dedicated buffer directory—**never use `docker compose --scale`**. Instance count is controlled by `VECTOR_REPLICAS` in `.env` and requires regenerating the Compose file via `configure.sh`:

```bash
./configure.sh <PATH_TO_SWANLAB> --vector 2   # Scale up to 2 instances
```

* **Scaling up**: New instances start with dedicated buffer directories and are registered with the gateway automatically.
* **Scaling down**: The script pauses House, waits for Vector to finish flushing buffered metrics, and then removes excess instances. Existing `data/vector-N` directories are preserved.
* Each instance reserves ~40 GiB of disk buffer (`4 × 10 GiB`); verify available disk space before scaling up.
* Editing `.env` and running `docker compose up -d` alone will not take effect.
