Bootstrap a working Docker Compose config on first boot so the WebUI works out of the box

A fresh 'docker compose up' started with no config (the entrypoint only
bootstrapped for Render), so every published port was unreachable: the
gateway and WebSocket channel defaulted to a container-local 127.0.0.1
bind, and nanobot-api exited into a restart loop because serve refuses a
non-loopback host without an api_key.

Bootstrap config.json for container runs (NANOBOT_DOCKER_BOOTSTRAP, set
by docker-compose.yml) from a committed docker-config.json with binds
that survive the container boundary, baking the WebUI token and API key
at first boot (env value if provided, generated otherwise, printed to
the log). Move nanobot-api under the 'api' profile since it cannot
serve before a provider is configured. Install curl in the image and
document the new first-boot flow.

Fixes #6165
This commit is contained in:
LuckVd authored and chengyongru committed 2026-10-19 13:02:26 +08:00
1 parent 53e0edf709
commit ddd22a26f8
6 files changed
+153 -14

No files matched your search

+6 -1
View File
@@ -12,7 +12,7 @@ RUN mkdir -p /app/nanobot/web && npm run build
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim
RUN apt-get update && \
apt-get install -y --no-install-recommends ca-certificates git bubblewrap openssh-client libmagic1 && \
apt-get install -y --no-install-recommends ca-certificates curl git bubblewrap openssh-client libmagic1 && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
@@ -54,6 +54,11 @@ RUN for channel in $(printf '%s' "$NANOBOT_CHANNELS" | tr ',' ' '); do \
# won't shadow it. Only used when RENDER=true; ignored by local runs.
COPY render-config.json ./
# Local Docker deploy template (see docker-compose.yml): container-appropriate
# binds with the WebUI token and API key baked in by the entrypoint at first
# boot. Same /app location so a mounted data dir can't shadow it.
COPY docker-config.json ./
# Create the non-root user and hand ownership of the writable virtualenv to it.
RUN useradd -m -u 1000 -s /bin/bash nanobot && \
mkdir -p /home/nanobot/.nanobot && \
+11
View File
@@ -4,6 +4,12 @@ x-common-config: &common-config
dockerfile: Dockerfile
args:
NANOBOT_CHANNELS: ${NANOBOT_CHANNELS:-whatsapp}
environment:
# Bootstrap a working config.json on first boot (binds that work across
# the container boundary; secrets generated if not provided).
NANOBOT_DOCKER_BOOTSTRAP: "1"
NANOBOT_WEB_TOKEN: ${NANOBOT_WEB_TOKEN:-}
NANOBOT_API_KEY: ${NANOBOT_API_KEY:-}
volumes:
- ~/.nanobot:/home/nanobot/.nanobot
cap_drop:
@@ -39,6 +45,11 @@ services:
nanobot-api:
container_name: nanobot-api
<<: *common-config
# Optional: the OpenAI-compatible API needs a configured provider before it
# can serve, so it is not part of the default `docker compose up`. Start it
# with `docker compose --profile api up -d` once a provider is configured.
profiles:
- api
command:
["serve", "--host", "0.0.0.0", "-w", "/home/nanobot/.nanobot/api-workspace"]
restart: unless-stopped
+19
View File
@@ -0,0 +1,19 @@
{
"gateway": {
"host": "0.0.0.0",
"port": 18790
},
"channels": {
"websocket": {
"enabled": true,
"host": "0.0.0.0",
"port": 8765,
"tokenIssueSecret": "${NANOBOT_WEB_TOKEN}",
"websocketRequiresToken": true
}
},
"api": {
"host": "0.0.0.0",
"api_key": "${NANOBOT_API_KEY}"
}
}
+15
View File
@@ -131,6 +131,21 @@ NANOBOT_CHANNELS=telegram,slack docker compose build
The image keeps nanobot in a virtual environment owned by its built-in non-root runtime user (UID 1000). If an enabled channel was not preinstalled, gateway startup can therefore install its manifest-declared dependencies. Rebuilding with `NANOBOT_CHANNELS` keeps that installation reproducible instead of relying on the container's writable layer. If you override the container with a different `--user`, bake every enabled channel into the image because that UID is not guaranteed write access to the virtual environment.
The first `docker compose up` bootstraps `~/.nanobot/config.json` with container-appropriate binds and generated secrets: the WebUI password (`NANOBOT_WEB_TOKEN`) and the OpenAI-compatible API key (`NANOBOT_API_KEY`). Export either variable before `up` to pin your own; otherwise the entrypoint generates one and prints it to the container log. An existing `config.json` is left untouched. Add provider keys afterwards in the WebUI settings or with `onboard`:
```bash
docker compose up -d nanobot-gateway # first boot writes ~/.nanobot/config.json
docker compose logs nanobot-gateway # shows the generated WebUI password and API key
```
The `nanobot-api` service (OpenAI-compatible endpoint on `127.0.0.1:8900`) needs a configured provider before it can serve, so it is opt-in via the `api` profile:
```bash
docker compose --profile api up -d # also start the API once a provider is configured
```
For a fully pre-configured setup, keep using first-time onboarding:
```bash
docker compose run --rm nanobot-cli status
docker compose run --rm nanobot-cli agent -m "Hello!"
+30 -13
View File
@@ -1,24 +1,41 @@
#!/bin/sh
dir="$HOME/.nanobot"
# Render deploy path (see render.yaml + render-config.json). Gated on Render's
# automatic RENDER=true env var so local Docker/podman usage is unaffected.
# Initializes the on-disk config from the committed template (wiring secrets via
# ${VAR} env vars, keeping runtime data on the persistent disk) and appends the
# --config flag. Logs each decision so a failed start is diagnosable in Render's
# logs. Privilege dropping is handled below, for every root start (not just here).
if [ "$RENDER" = "true" ]; then
echo "[entrypoint] Render deploy — starting as $(id)"
# Container config bootstrap. Two deploy paths share the init-once logic:
# - Render (RENDER=true): template wires secrets via ${VAR} env vars, resolved
# at startup by the config loader.
# - Local Docker (NANOBOT_DOCKER_BOOTSTRAP=1, set by docker-compose.yml): a
# template with binds that work across the container boundary, and secrets
# baked in at first boot (env value if provided, otherwise generated) so a
# missing env var can never crash-loop the containers.
# Initializes the on-disk config only when it does not already exist, so
# WebUI/provider settings edited at runtime survive restarts.
# Logs each decision so a failed start is diagnosable in the container logs.
# Privilege dropping is handled below, for every root start (not just here).
if [ "$RENDER" = "true" ] || [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ]; then
echo "[entrypoint] container deploy — starting as $(id)"
mkdir -p "$dir" || echo "[entrypoint] warning: mkdir $dir failed"
config="$dir/config.json"
# Initialize config only when it does not already exist, so WebUI/provider
# settings edited at runtime survive restarts. The disk persists config.json
# across deploys; overwriting it every boot would discard those changes.
if [ ! -f "$config" ]; then
echo "[entrypoint] initializing $config from render-config.json"
cp /app/render-config.json "$config" || echo "[entrypoint] warning: cp config failed"
if [ "$RENDER" = "true" ]; then
echo "[entrypoint] initializing $config from render-config.json"
cp /app/render-config.json "$config" || echo "[entrypoint] warning: cp config failed"
else
web_token="${NANOBOT_WEB_TOKEN:-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')}"
api_key="${NANOBOT_API_KEY:-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')}"
echo "[entrypoint] initializing $config from docker-config.json"
sed -e "s|\${NANOBOT_WEB_TOKEN}|$web_token|" \
-e "s|\${NANOBOT_API_KEY}|$api_key|" \
/app/docker-config.json > "$config" \
|| echo "[entrypoint] warning: config bootstrap failed"
echo "[entrypoint] WebUI: http://localhost:8765 — password: $web_token"
echo "[entrypoint] OpenAI-compatible API: http://127.0.0.1:8900/v1 — api key: $api_key"
fi
else
echo "[entrypoint] existing $config found — leaving it in place"
if [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ]; then
echo "[entrypoint] WebUI password lives in $config (channels.websocket.tokenIssueSecret)"
fi
fi
set -- "$@" --config "$config"
fi
+72
View File
@@ -0,0 +1,72 @@
"""The committed Docker deploy template must always bake into a startable config.
`entrypoint.sh` initializes `~/.nanobot/config.json` from `docker-config.json`
on first boot (see docker-compose.yml). A template that drifts out of sync with
the config schema would crash-loop every container on a fresh `docker compose
up`, so pin the contract here: the baked config validates, and its wildcard
binds carry the secrets their security validators require.
"""
import json
from pathlib import Path
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.config.schema import Config
repo_root = Path(__file__).resolve().parents[1]
WEB_TOKEN_PLACEHOLDER = "${NANOBOT_WEB_TOKEN}"
API_KEY_PLACEHOLDER = "${NANOBOT_API_KEY}"
def _template() -> dict:
return json.loads((repo_root / "docker-config.json").read_text())
def _baked() -> dict:
"""The template as the entrypoint writes it, with both secrets substituted."""
raw = (repo_root / "docker-config.json").read_text()
raw = raw.replace(WEB_TOKEN_PLACEHOLDER, "test-web-token")
raw = raw.replace(API_KEY_PLACEHOLDER, "test-api-key")
return json.loads(raw)
def test_docker_template_bakes_to_a_valid_container_config():
config = Config.model_validate(_baked())
# Binds must survive the container boundary: a loopback bind inside the
# container is unreachable through the ports docker-compose.yml publishes.
assert config.gateway.host == "0.0.0.0"
assert config.api.host == "0.0.0.0"
assert config.api.api_key == "test-api-key"
def test_docker_template_websocket_satisfies_wildcard_host_auth():
ws = WebSocketConfig.model_validate(_baked()["channels"]["websocket"])
assert ws.enabled is True
assert ws.host == "0.0.0.0"
assert ws.port == 8765
assert ws.token_issue_secret
assert ws.websocket_requires_token is True
def test_docker_template_secrets_are_wired_for_entrypoint_substitution():
# entrypoint.sh substitutes exactly these placeholders when writing
# config.json (env value if provided, generated otherwise). A renamed
# placeholder would survive substitution and reach the runtime as a
# literal string, breaking every client that needs the real secret.
template = _template()
assert template["channels"]["websocket"]["tokenIssueSecret"] == WEB_TOKEN_PLACEHOLDER
assert template["api"]["api_key"] == API_KEY_PLACEHOLDER
assert "${" not in json.dumps(_baked())
def test_docker_template_uses_the_same_shape_as_the_render_template():
docker_template = _template()
render_template = json.loads((repo_root / "render-config.json").read_text())
assert set(docker_template["channels"]["websocket"]) == set(
render_template["channels"]["websocket"]
)