ai / DEPLOY_GUIDE.md
GGSheng's picture
feat: deploy Gemma 4 to hf space
17e971c verified
# Deploying OpenClaw on Hugging Face Spaces (with Auto Backup & Restore)
> **Source**: [tenfy's blog - Deploying OpenClaw on Hugging Face Spaces](https://tenfy.cn/posts/openclaw-hf-space-deploy/) (adapted for this project)
>
> **Original Author**: tenfyzhong([https://tenfy.cn](https://tenfy.cn)οΌ‰
>
> **Adapted by**: ClawCopilot Team([https://github.com/ClawCopilot/Openclaw-Hf-Docker](https://github.com/ClawCopilot/Openclaw-Hf-Docker)οΌ‰
>
> **Original Post Date**: 2026-03-25
---
## What This Solution Solves
This project builds on tenfy's `openclaw-hf` by adding **BT Panel (Baota)** as PID 1, providing a user-friendly web management interface:
- Build OpenClaw container image on top of `ubuntu:24.04`
- **BT Panel (Baota)** as container PID 1, listening on port `7860` (default HF Space port), provides web management interface
- **OpenClaw Gateway** runs on separate port `18789` (default)
- Support pre-configuring third-party OpenAI-compatible models via environment variables (`base_url + api_key`)
- OpenClaw config and workspace stored in `/root/.openclaw`
- Auto-restore latest backup from HF Dataset on startup
- Periodic backup to HF Dataset via `cron`
- **Supervisord** manages `cron` and `openclaw-gateway` processes
- Pre-installed tools: `vim`, `opencode`, `codex`, `claude`, `sshx` for debugging and interaction inside the container
- Built-in DDNS-GO for dynamic DNS updates (non-critical, installation failure doesn't break the build)
---
## Container Architecture
```
PID 1 (bt-panel)
└── /usr/local/bin/hf-entrypoint.sh
β”œβ”€β”€ /usr/bin/supervisord
β”‚ β”œβ”€β”€ cron (scheduled backup tasks)
β”‚ └── openclaw-gateway (OpenClaw Gateway, port 18789)
└── node hf-server.js (container health check)
```
- **BT Panel**: port `7860`, web management interface
- **OpenClaw Gateway**: port `18789`, AI Gateway API
- **Supervisord**: process manager, manages both `cron` and `openclaw-gateway`
- **Health check**: `curl http://localhost:7860`, called by Hugging Face platform
---
## 1. Register Hugging Face & Generate HF_TOKEN
If you don't have a Hugging Face account yet, sign up first: [https://huggingface.co/join](https://huggingface.co/join)
After preparing your account, create a token following these steps:
1. Open Hugging Face Token page: [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
2. Create a new token (recommended name: `deploy-openclaw`)
3. Grant the required permissions (need ability to create Spaces and write to Datasets)
4. Copy the token (format: `hf_xxx...`)
Login locally and verify:
```bash
hf auth login
hf auth whoami
```
When `bootstrap-hf.sh` prompts for `HF_TOKEN for backup dataset`:
- You can paste the newly created token directly
- Or leave it empty to let the script reuse the current `hf auth login` local credentials
---
## 2. One-Click Deployment (Recommended)
The repository provides an interactive script. It's recommended to use the script instead of manual setup.
### 1. Clone the Repository
```bash
git clone https://github.com/ClawCopilot/Openclaw-Hf-Docker.git
cd Openclaw-Hf-Docker
```
### 2. Run the Bootstrap Script
macOS / Linux:
```bash
./scripts/bootstrap-hf.sh
```
Windows PowerShell:
```powershell
powershell -ExecutionPolicy ByPass -File .\scripts\bootstrap-hf.ps1
```
### 3. What the Script Does Automatically
- Check and install `hf` CLI if missing
- Check Hugging Face login status (trigger `hf auth login` if needed)
- Ask for and confirm deployment parameters (including final `Proceed with these settings?` confirmation)
- Ask for BT Panel port, username, and password
- Create private Space and private backup Dataset, upload current repository to Space
- Auto-write Variables / Secrets (including backup, gateway credentials, BT Panel config, etc.)
- Write security-related variables by default:
- `OPENCLAW_GATEWAY_CONTROLUI_ALLOW_INSECURE_AUTH=false`
- `OPENCLAW_GATEWAY_CONTROLUI_DANGEROUSLY_DISABLE_DEVICE_AUTH=false`
### 4. BT Panel Username Rules
**Must satisfy the following**:
- Start with a lowercase letter
- Can only contain lowercase letters and numbers
- Length 3-32 characters
Examples: `btadmin`, `mypanel123`, `openclawspace`
---
## 3. Use Agent for Auto Deployment
Suitable for users who don't want to manually configure. You can directly send this to an AI Agent:
```
Please deploy OpenClaw to Hugging Face by strictly following the deployment skill in https://github.com/tenfyzhong/openclaw-hf/blob/main/SKILL.md
```
Agent usually does:
1. Check dependencies first (`git`, `hf`, `python3`, `huggingface_hub`)
2. Collect deployment parameters from you in fixed order
3. Call `bootstrap-hf.sh` / `bootstrap-hf.ps1` to execute deployment
4. Report Space / Dataset / App / Health URLs and version info
5. If gateway credentials are auto-generated, also report them
If you want to provide all parameters at once, send this template to the Agent:
```
space_name: openclaw-hf
dataset_name: openclaw-hf-backup
openclaw_version: latest
gateway_token: <leave empty to auto-generate, or fill manually>
gateway_password: <leave empty to auto-generate, or fill manually>
hf_token: <your HF_TOKEN, or leave empty to reuse local login>
configure_custom_llm: no
openclaw_sshx_auto_start: true
bt_panel_port: 7860
bt_panel_username: btadmin
bt_panel_password: <leave empty to auto-generate, or fill manually>
proceed_with_settings: yes
```
---
## 4. Pre-Deployment Requirements
The script depends on the following commands:
```bash
git --version
hf version
python3 --version
```
Also requires Python package:
```bash
python3 -c "import huggingface_hub" >/dev/null 2>&1 || \
python3 -m pip install --user 'huggingface_hub[cli]'
```
---
## 5. Key Variables & Secrets
In Space's `Settings -> Variables and secrets`, at minimum you need:
- Variable: `OPENCLAW_BACKUP_DATASET_REPO` (format: `username/dataset-name`)
- Secret: `HF_TOKEN` (needs write permission to the backup Dataset)
- Secret: `OPENCLAW_GATEWAY_TOKEN` (recommended)
- Secret: `OPENCLAW_GATEWAY_PASSWORD` (optional)
- Variable: `BT_PANEL_PORT` (default `7860`)
- Variable: `BT_PANEL_USERNAME` (default `btadmin`)
- Secret: `BT_PANEL_PASSWORD` (BT Panel password)
If you use `bootstrap-hf.sh` / `bootstrap-hf.ps1`, the above will be configured automatically.
### Optional: Pre-configure LLM (all three must be provided together)
- `OPENCLAW_LLM_BASE_URL`
- `OPENCLAW_LLM_MODEL`
- `OPENCLAW_LLM_API_KEY`
If only 1-2 of them are filled, the entrypoint script will skip model pre-configuration.
### Common Optional Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `OPENCLAW_VERSION` | `latest` | OpenClaw version |
| `OPENCLAW_BACKUP_CRON` | `*/30 * * * *` | Backup interval (every 30 min by default) |
| `OPENCLAW_BACKUP_KEEP_COUNT` | `48` | Number of latest backups to keep |
| `OPENCLAW_SSHX_AUTO_START` | `false` | Set to `true` to auto-start sshx |
| `OPENCLAW_GATEWAY_PORT` | `18789` | Gateway listening port |
| `BT_PANEL_PORT` | `7860` | BT Panel listening port |
| `BT_PANEL_USERNAME` | `btadmin` | BT Panel username (lowercase letter start) |
| `BT_PANEL_PASSWORD` | auto-generated | BT Panel password |
---
## 6. What the Script Will Ask You
Following the flow, main inputs are:
1. `space_name` (default `openclaw-hf`)
2. `dataset_name` (default `<space_name>-backup`)
3. `OPENCLAW_VERSION` (default auto-detect latest version)
4. `OPENCLAW_GATEWAY_TOKEN` (can leave empty for auto-generated 32-char random value)
5. `OPENCLAW_GATEWAY_PASSWORD` (can leave empty for auto-generated 16-char random value)
6. `HF_TOKEN` (can leave empty, reuse locally logged-in token)
7. Whether to configure LLM immediately (all three must be filled for it to take effect)
8. If not configuring LLM, whether to enable `OPENCLAW_SSHX_AUTO_START`
9. **BT Panel port** (default `7860`)
10. **BT Panel username** (must start with lowercase letter, only lowercase letters and numbers, 3-32 chars)
11. **BT Panel password** (can leave empty for auto-generation)
12. Final confirmation: `Proceed with these settings?` (selecting `no` will exit without remote changes)
If token/password is auto-generated by the script, it will be printed at the end. Please save it promptly.
---
## 7. How to Verify After Deployment
Assuming Space repo is `<owner>/<space_name>`, available URLs:
| Service | URL |
|---------|-----|
| BT Panel Admin | `https://<owner>-<space_name>.hf.space:7860` |
| BT Panel Health | `https://<owner>-<space_name>.hf.space` |
| OpenClaw Gateway | `https://<owner>-<space_name>.hf.space:18789` |
| Space Page | `https://huggingface.co/spaces/<owner>/<space_name>` |
For example:
```bash
OPENCLAW_HF_SPACE_ID="yourname/openclaw-hf"
SPACE_HOST="${OPENCLAW_HF_SPACE_ID/\//-}.hf.space"
echo "BT Panel: https://${SPACE_HOST}:7860"
echo "Gateway: https://${SPACE_HOST}:18789"
```
> **Note**: Some network environments may restrict direct access to port `:18789`. The BT Panel admin interface (7860) is the primary access entry point.
---
## 8. BT Panel Usage Guide
### Login to BT Panel
1. After deployment completes, wait for container to start (~2-5 minutes)
2. Visit `https://<owner>-<space_name>.hf.space:7860`
3. Login with the `BT_PANEL_USERNAME` and `BT_PANEL_PASSWORD` set during deployment
> On first login, you may need to wait for BT Panel service to fully start. If the page is inaccessible, please try again later.
### BT Panel Security Recommendations
- After deployment, it is recommended to modify `BT_PANEL_PASSWORD` in `Settings -> Variables and secrets`
- Avoid exposing BT Panel admin interface to the public internet
- `BT_PANEL_USERNAME` must conform to rules: start with lowercase letter, only lowercase letters and numbers
---
## 9. How to Do OpenClaw Initial Configuration
1. Open Hugging Face Space page, go to container logs, find the temporary access link output by `sshx`
2. Open that link in browser to enter container shell, execute `openclaw onboard` and follow the guide
3. During onboarding, OpenClaw may restart, and the `sshx` link may also change; if current link expires, go back to logs to get the new link and continue
4. Official wizard reference: [https://docs.openclaw.ai/start/wizard](https://docs.openclaw.ai/start/wizard)
5. After configuration is complete, remember to go back to `Settings -> Variables and secrets`, change `OPENCLAW_SSHX_AUTO_START` to `false` (or delete this variable), then restart Space to turn off `sshx`
If you modified OpenClaw configuration and want it to take effect immediately, you can restart the corresponding process (example):
```bash
ps -ef | grep 'openclaw-gateway' | grep -v 'grep' | awk '{print $2}' | xargs -I{} kill {}
```
---
## 10. Backup & Restore Mechanism
The data lifecycle of this project is as follows:
- **Startup Restore**: On container startup, it fetches `latest-backup.json` from Dataset to locate the latest backup and restore
- **Scheduled Backup**: Upload periodically based on `OPENCLAW_BACKUP_CRON` (every 30 minutes by default)
- **Shutdown Backup**: Do a final backup when container receives stop signal before exiting
- **Artifacts include**:
- `backups/openclaw-backup-<timestamp>.tar.gz`
- `latest-backup.json`
- **Retention Policy**: Only keep the latest `OPENCLAW_BACKUP_KEEP_COUNT` timestamped archives (default `48`)
---
## 11. Keep-Alive & 24/7 Running Suggestions
- Free `cpu-basic` will sleep (currently after about 48 hours of no access)
- Strict 24/7 requires paid hardware, set `Sleep time` to `Never`
- For private Space health checks, must include `Authorization: Bearer <HF_TOKEN>`, otherwise you'll see 404 (normal access control behavior)
If you just want to reduce cold start probability, you can periodically request the BT Panel health check address; but on free tier, this is not an officially guaranteed always-on solution.
### Using cron-job.org for Keep-Alive
If you don't want to maintain scheduled tasks yourself, you can use [https://cron-job.org/](https://cron-job.org/).
According to their official FAQ ([https://cron-job.org/faq/](https://cron-job.org/faq/)), they support custom headers, HTTPS, and up to once per minute calls. For OpenClaw Space, pinging once every 10-15 minutes is usually sufficient.
#### 1. Create a Task
1. Open [https://cron-job.org/](https://cron-job.org/) and register/login (console is at `console.cron-job.org`)
2. Create new HTTP cron job
3. URL: `https://<owner>-<space_name>.hf.space` (BT Panel health check)
4. Method: `GET`
5. Schedule: recommend once every 10-15 minutes
#### 2. Add Header for Private Space
```
Authorization: Bearer <HF_TOKEN>
```
It's recommended to create a separate low-permission token for keep-alive only, don't reuse the high-permission backup token.
#### 3. Do Test Run Before Enabling Alerts
After creating the task, test it manually once first, then enable failure notifications (email, etc.) to be notified promptly when Space is unavailable or token expires.
---
## 12. sshx Usage (Optional)
`sshx` is pre-installed in the image (along with `vim`, `opencode`, `codex`, `claude`).
### 1. Auto Start (Environment Variable)
```bash
OPENCLAW_SSHX_AUTO_START=true
```
### 2. Manual Start Inside Container
```bash
sshx
```
### 3. Start via OpenClaw Terminal in Background
```bash
nohup sshx >/proc/1/fd/1 2>/proc/1/fd/2 &
```
If you temporarily need `sshx` later, you can also let OpenClaw start it via IM; after use, remember to let OpenClaw turn off `sshx` via IM as well.
### Cleanup After Use
```bash
pgrep -fa sshx
pkill -TERM -f '(^|/)sshx($| )'
```
---
## 13. Process Management
This project uses **Supervisord** to manage processes (PM2 has been removed):
```
PID 1 (bt-panel)
└── supervisord
β”œβ”€β”€ cron
└── openclaw-gateway
```
- **Supervisord**: as a child process of bt-panel, correctly managed
- **cron**: scheduled backup tasks (runs every 30 minutes by default)
- **openclaw-gateway**: OpenClaw Gateway service, listening on port 18789
- **PM2**: removed from this project, no longer used for managing Gateway
### Check Process Status
Inside container:
```bash
supervisorctl status
```
### View Logs
```bash
# supervisord logs
tail -f /var/log/hf-entrypoint/supervisord-stdout.log
# cron logs
tail -f /var/log/hf-entrypoint/cron-stdout.log
# openclaw-gateway logs
tail -f /var/log/hf-entrypoint/openclaw-gateway-stdout.log
```
---
## 14. Summary
If your goal is "quickly running a restorable OpenClaw instance on Hugging Face", this project has covered the key aspects: deployment, configuration, backup, restore, keep-alive, and remote debugging, with BT Panel providing a more user-friendly web management interface.
It's recommended to first use the repository's `bootstrap-hf` script to get the default configuration working, then add LLM, keep-alive, and `sshx` strategies as needed.
---
## Related Links
- Repository: [https://github.com/ClawCopilot/Openclaw-Hf-Docker](https://github.com/ClawCopilot/Openclaw-Hf-Docker)
- Original Article: [https://tenfy.cn/posts/openclaw-hf-space-deploy/](https://tenfy.cn/posts/openclaw-hf-space-deploy/)
- OpenClaw Official Wizard: [https://docs.openclaw.ai/start/wizard](https://docs.openclaw.ai/start/wizard)
- BT Panel Official Site: [https://www.bt.cn/](https://www.bt.cn/)