# Mytess AI Deployment Runbook > Plain-text operational guide for AI Agents (Claude Code, Codex, Cursor, OpenClaw, SSH agents) and conversational LLMs (ChatGPT, Claude, Gemini, DeepSeek) helping a user deploy TeslaMate and `mytesla/teslamateapi` for the Mytess iOS app. > > - Chinese version (中文版 / 中国大陆镜像): `https://cn.mytess.net/ai/deploy-zh.md` > - Last updated: 2026-12-02 --- ## 0. Choose Your Operating Mode - **Mode A — AI Agent with terminal/SSH access**: 1. Run the read-only discovery commands in Section 2 first. 2. Summarize findings and confirm the plan with the user before changing any file or container. 3. Back up `docker-compose.yml` before modifying it, then edit files and run non-interactive `docker compose` commands directly. 4. **Never pipe interactive scripts** (`install-teslamate.sh`, `add-teslamateapi.sh`) in a non-TTY subshell — they prompt via `/dev/tty` and will hang or fail. 5. Run Section 5 verification, then output the private handoff summary in Section 6. - **Mode B — Conversational LLM without shell access**: 1. Ask at most 3 short questions first: - Do you already have TeslaMate running, or are you starting fresh? - Do you manage Docker via SSH/terminal or a NAS/GUI (Synology, QNAP, Unraid, Portainer)? - Are you in mainland China (Aliyun mirror needed), and do you need remote access outside home Wi-Fi? 2. **Before asking the user to share an existing Compose setup**, ask only for a **minimal redacted excerpt** (service names, images, ports, volume names, and variable names) and explicitly remind them to redact **all secrets**: `DATABASE_PASS`, `ENCRYPTION_KEY`, `API_ACCESS_KEY`, `API_SECRET_KEY`, `API_TOKEN`, Basic Auth / Grafana passwords, Tesla tokens, and any other credentials. 3. Use placeholders (``, ``) in YAML you generate, and give `openssl` commands for the user to generate secrets locally. --- ## 1. Non-Negotiable Rules & Safety Guardrails 1. **Secret hygiene (critical)**: - Never print or echo `ENCRYPTION_KEY`, `DATABASE_PASS`, or `API_SECRET_KEY` unnecessarily into chat logs. - Prefer reusing `${VAR}` references from an existing `.env` or compose file. If copying values from a running container, write them directly into the target file without printing them to stdout. - Generate all new random secrets locally on the user's machine using `openssl` — **never** invent random keys inside the LLM. - Warn the user that `API_SECRET_KEY` and `mytess://setup?...` links are private and must not be shared publicly. 2. **Required API image**: Always use `mytesla/teslamateapi:latest` (or its Aliyun mirror in mainland China). **Never** use `tobiasehlert/teslamateapi` — it lacks Mytess insights, notifications, footprint, and time-of-use billing logic. 3. **Never destroy vehicle history**: Never run `docker compose down -v`, and never overwrite an existing `ENCRYPTION_KEY` or `DATABASE_PASS`. 4. **Always persist `/opt/app/data`**: - Mount `teslamateapi-data:/opt/app/data` under `teslamateapi` and declare `teslamateapi-data:` inside the existing top-level `volumes:` map (never create a second `volumes:` map). - If `/opt/app/data` already has a volume or bind mount, keep it instead of replacing it. 5. **Two different credential pairs — never mix them**: - **TeslaMate (`:4000`)**: uses **Tesla account access/refresh tokens** to authorize vehicles with Tesla. - **Mytess iOS App (`:3030`)**: uses **`API_ACCESS_KEY` (`AK...`) + `API_SECRET_KEY` (`SK...`)** to authenticate requests to `teslamateapi`. 6. **Upgrades require recreate, not restart**: Pull the new image, then run `docker compose up -d --no-deps teslamateapi`. Plain `docker compose restart` does not update the image. --- ## 2. Read-Only Discovery (Mode A) Run read-only checks without printing secret values: ```bash # 1. Docker & Compose availability docker --version && (docker compose version || docker-compose --version) # 2. Check all containers (running AND stopped) with image, ports, and status docker ps -a --format "table {{.Names}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}" # 3. Match TeslaMate specifically (never teslamateapi) across running and stopped containers, # then build reusable COMPOSE_ARGS from its labels and inspect env var NAMES only (no secret values) TM_CID=$(docker ps -a --format "{{.Names}}\t{{.Image}}" \ | awk -F'\t' '$2 ~ /(^|\/)(teslamate|mytesla|mytess)\/teslamate([:@]|$)/ {print $1; exit}') COMPOSE_ARGS=() TM_SERVICE="teslamate" if [ -n "$TM_CID" ]; then TM_PROJECT=$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project"}}' "$TM_CID") TM_SERVICE=$(docker inspect --format '{{index .Config.Labels "com.docker.compose.service"}}' "$TM_CID") TM_SERVICE="${TM_SERVICE:-teslamate}" TM_WORKDIR=$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project.working_dir"}}' "$TM_CID") TM_CONFIG_FILES=$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project.config_files"}}' "$TM_CID") printf 'project=%s service=%s workdir=%s files=%s\n' "$TM_PROJECT" "$TM_SERVICE" "$TM_WORKDIR" "$TM_CONFIG_FILES" [ -n "$TM_PROJECT" ] && COMPOSE_ARGS+=(-p "$TM_PROJECT") [ -n "$TM_WORKDIR" ] && COMPOSE_ARGS+=(--project-directory "$TM_WORKDIR") IFS=',' read -r -a CONFIG_FILE_LIST <<< "$TM_CONFIG_FILES" for f in "${CONFIG_FILE_LIST[@]}"; do [ -n "$f" ] && COMPOSE_ARGS+=(-f "$f") done docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$TM_CID" | cut -d= -f1 | sort [ "${#COMPOSE_ARGS[@]}" -gt 0 ] && docker compose "${COMPOSE_ARGS[@]}" --profile "*" config --services fi # 4. Resolve API service and image from the selected Compose project (all profiles; never another project) API_SERVICE="" API_IMAGE="" API_CID="" COMPOSE_CONFIG_OK=false if [ "${#COMPOSE_ARGS[@]}" -gt 0 ]; then if COMPOSE_CFG=$(docker compose "${COMPOSE_ARGS[@]}" --profile "*" config); then COMPOSE_CONFIG_OK=true IFS=$'\t' read -r API_SERVICE API_IMAGE < <(printf '%s\n' "$COMPOSE_CFG" | awk ' /^services:/ { in_s=1; next } in_s && /^[^ ]/ { in_s=0 } in_s && /^ [A-Za-z0-9._-]+:/ { svc=$1; sub(/:$/, "", svc); next } in_s && /^ image:/ { img=$2; gsub(/^["'\'']|["'\'']$/, "", img); if (img ~ /(^|\/)(tobiasehlert|mytesla|mytess)\/teslamateapi([:@]|$)/) { print svc "\t" img; exit } } ') || true if [ -n "$API_SERVICE" ]; then API_CID=$(docker compose "${COMPOSE_ARGS[@]}" ps -a -q "$API_SERVICE" | head -n1) fi else echo "Compose config failed — fix missing env/files before editing or adding services." >&2 fi else # Non-Compose fallback: inspect standalone API containers only (no Compose project label) API_CID=$(docker ps -a --format '{{.Names}}\t{{.Image}}\t{{.Label "com.docker.compose.project"}}' \ | awk -F'\t' '$3 == "" && $2 ~ /(^|\/)(tobiasehlert|mytesla|mytess)\/teslamateapi([:@]|$)/ {print $1; exit}') fi printf 'compose_config_ok=%s api_service=%s api_image=%s\n' "$COMPOSE_CONFIG_OK" "${API_SERVICE:-}" "${API_IMAGE:-}" if [ -n "$API_CID" ]; then docker inspect --format 'api_container={{.Name}} project={{index .Config.Labels "com.docker.compose.project"}} service={{index .Config.Labels "com.docker.compose.service"}} image={{.Config.Image}} status={{.State.Status}} ports={{json .NetworkSettings.Ports}}' "$API_CID" fi # 5. Check port 3030/4000, existing TeslaMate volumes, & server LAN IP (ss -tlnp 2>/dev/null || netstat -tln 2>/dev/null || true) | grep -E ':(3030|4000)\b' || true docker volume ls --format '{{.Name}}' | grep -i teslamate || true ip route get 1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if ($i=="src") print $(i+1)}' | head -1 || hostname -I 2>/dev/null | awk '{print $1}' ``` ### Branching on Discovery Results - **No TeslaMate container AND no existing TeslaMate volumes/compose directory found**: Go to **Section 4 (Fresh Install)** (still check that the destination directory has no existing Compose file before writing). - **Existing TeslaMate found WITH Compose labels (`TM_WORKDIR` / `TM_CONFIG_FILES`)**: - Always reuse the exact `COMPOSE_ARGS` (`-p "$TM_PROJECT"`, `--project-directory "$TM_WORKDIR"`, and every ordered `-f` file from `TM_CONFIG_FILES`) for **every** subsequent `docker compose` command on this stack (add, upgrade, ps, logs, restart). Require `COMPOSE_CONFIG_OK=true` before taking the add-service branch: - **`COMPOSE_CONFIG_OK=false`**: **STOP** and resolve the Compose configuration error (e.g. missing `.env` file or required variable) before adding or editing any service; never treat a failed `config` check as proof that no API service exists. - **`COMPOSE_CONFIG_OK=true` and `API_SERVICE` is empty**: Go to **Section 3 (Add `mytesla/teslamateapi`)**, set `API_SERVICE="teslamateapi"`, and edit the discovered Compose file (never blindly assuming `docker-compose.yml`). - **`API_IMAGE` already uses `mytesla/teslamateapi` (or Aliyun `mytess/teslamateapi`)**: Do **not** add a duplicate service. Verify `"$API_SERVICE"` is running, has `/opt/app/data` mounted and AK/SK configured, upgrade if outdated (`docker compose "${COMPOSE_ARGS[@]}" pull "$API_SERVICE" && docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps "$API_SERVICE"`), then proceed to **Section 5 (Verification)**. - **`API_IMAGE` uses `tobiasehlert/teslamateapi`**: Back up the active Compose file defining `"$API_SERVICE"`, change `image:` to `mytesla/teslamateapi:latest`, ensure `teslamateapi-data:/opt/app/data` (and top-level `volumes: teslamateapi-data:`) and `API_ACCESS_KEY`/`API_SECRET_KEY` are configured, then run `docker compose "${COMPOSE_ARGS[@]}" pull "$API_SERVICE" && docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps "$API_SERVICE"`. - **Existing TeslaMate found WITHOUT Compose labels** (e.g. Home Assistant add-on, Unraid template, Synology GUI `docker run`, Portainer stack, Kubernetes): - **STOP and ask the user** how TeslaMate is managed. Do **not** create a new standalone `docker-compose.yml` that conflicts with or misses the existing network/volumes. - Requirements for adding `teslamateapi` in those environments: - Image: `mytesla/teslamateapi:latest` - Same Docker network as TeslaMate's `database` and `mosquitto` containers - Matching `DATABASE_USER`, `DATABASE_PASS`, `DATABASE_NAME`, `DATABASE_HOST`, `ENCRYPTION_KEY`, `MQTT_HOST` - New `API_ACCESS_KEY` and `API_SECRET_KEY` - Persistent mount at `/opt/app/data` and port mapping `3030:8080` - Equivalent `docker run` pattern (replace network and `<...>` values): ```bash docker run -d --name teslamateapi --restart unless-stopped \ --network \ -p 3030:8080 \ -v teslamateapi-data:/opt/app/data \ -e DATABASE_USER=teslamate \ -e DATABASE_PASS= \ -e DATABASE_NAME=teslamate \ -e DATABASE_HOST= \ -e ENCRYPTION_KEY= \ -e MQTT_HOST= \ -e API_ACCESS_KEY= \ -e API_SECRET_KEY= \ mytesla/teslamateapi:latest ``` --- ## 3. Scenario A — Existing TeslaMate (Add `mytesla/teslamateapi`) 1. **Generate AK/SK locally on the server** (never invent in chat): ```bash API_ACCESS_KEY="AK$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 14)" API_SECRET_KEY="SK$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9' | head -c 30)" ``` 2. **Back up the discovered active Compose file first** (replace `COMPOSE_FILE` with the file from `com.docker.compose.project.config_files`, e.g. `docker-compose.yml` or `compose.yaml`): ```bash cp "$COMPOSE_FILE" "${COMPOSE_FILE}.backup.$(date +%Y%m%d%H%M%S)" ``` 3. **Insert `teslamateapi` inside `services:` (before `volumes:`)** and add `teslamateapi-data:` under the existing top-level `volumes:` map (match the existing `DATABASE_*`, `ENCRYPTION_KEY`, `MQTT_HOST`, and `depends_on` service names; reuse `${VAR}` if the compose file already uses `.env`): ```yaml services: # ... existing teslamate, database, mosquitto services ... teslamateapi: image: mytesla/teslamateapi:latest restart: unless-stopped depends_on: - database - teslamate - mosquitto environment: - DATABASE_USER=teslamate - DATABASE_PASS= - DATABASE_NAME=teslamate - DATABASE_HOST=database - ENCRYPTION_KEY= - MQTT_HOST=mosquitto - API_ACCESS_KEY= - API_SECRET_KEY= volumes: - teslamateapi-data:/opt/app/data ports: - 3030:8080 volumes: # ... existing volumes ... teslamateapi-data: ``` 4. **Validate syntax, start API, and restart TeslaMate once** using the exact discovered `COMPOSE_ARGS` (triggers fresh MQTT state publish): ```bash docker compose "${COMPOSE_ARGS[@]}" config -q docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps teslamateapi docker compose "${COMPOSE_ARGS[@]}" restart "$TM_SERVICE" ``` > **Interactive human-terminal alternative** (only when a human is typing in an interactive TTY — do NOT run in non-TTY agent shells): > `curl -fsSL https://mytess.net/scripts/add-teslamateapi.sh -o add-api.sh && bash add-api.sh` --- ## 4. Scenario B — Fresh Install (Full Stack) 1. **Confirm no existing deployment is in the target directory, then generate 4 secrets locally on the server**: ```bash INSTALL_DIR="$HOME/teslamate" if [ -e "$INSTALL_DIR/docker-compose.yml" ] || [ -e "$INSTALL_DIR/docker-compose.yaml" ] || [ -e "$INSTALL_DIR/compose.yml" ] || [ -e "$INSTALL_DIR/compose.yaml" ]; then echo "Existing Compose file found in $INSTALL_DIR — stop and inspect instead of overwriting." >&2 exit 1 fi mkdir -p "$INSTALL_DIR" && cd "$INSTALL_DIR" ENCRYPTION_KEY="$(openssl rand -hex 16)" DATABASE_PASS="$(openssl rand -base64 18 | tr -dc 'A-Za-z0-9' | head -c 20)" API_ACCESS_KEY="AK$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 14)" API_SECRET_KEY="SK$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9' | head -c 30)" ``` 2. **Write `docker-compose.yml`** (substitute the 4 generated values directly into the file without leaking `ENCRYPTION_KEY` / `DATABASE_PASS` into logs): ```yaml services: teslamate: image: teslamate/teslamate:latest restart: always environment: - ENCRYPTION_KEY= - DATABASE_USER=teslamate - DATABASE_PASS= - DATABASE_NAME=teslamate - DATABASE_HOST=database - MQTT_HOST=mosquitto ports: - 4000:4000 cap_drop: - all teslamateapi: image: mytesla/teslamateapi:latest restart: unless-stopped depends_on: - database - teslamate - mosquitto environment: - DATABASE_USER=teslamate - DATABASE_PASS= - DATABASE_NAME=teslamate - DATABASE_HOST=database - ENCRYPTION_KEY= - MQTT_HOST=mosquitto - API_ACCESS_KEY= - API_SECRET_KEY= volumes: - teslamateapi-data:/opt/app/data ports: - 3030:8080 database: image: postgres:18-trixie restart: always environment: - POSTGRES_USER=teslamate - POSTGRES_PASSWORD= - POSTGRES_DB=teslamate volumes: - teslamate-db:/var/lib/postgresql grafana: image: teslamate/grafana:latest restart: always environment: - DATABASE_USER=teslamate - DATABASE_PASS= - DATABASE_NAME=teslamate - DATABASE_HOST=database ports: - 3000:3000 volumes: - teslamate-grafana:/var/lib/grafana mosquitto: image: eclipse-mosquitto:2 restart: always command: mosquitto -c /mosquitto-no-auth.conf volumes: - mosquitto-conf:/mosquitto/config - mosquitto-data:/mosquitto/data volumes: teslamateapi-data: teslamate-db: teslamate-grafana: mosquitto-conf: mosquitto-data: ``` > **Mainland China Aliyun mirror images** (replace each `image:` above if Docker Hub is blocked): > Prefix: `crpi-suqjmomn4ro9malo.cn-hangzhou.personal.cr.aliyuncs.com/mytess/` > - `teslamate:latest`, `teslamateapi:latest`, `postgres:18-trixie`, `grafana:latest`, `eclipse-mosquitto:2` 3. **Start the stack and authorize the vehicle**: ```bash docker compose pull docker compose up -d ``` - Tell the user to open `http://:4000` in a browser and sign in with **Tesla account access/refresh tokens** (`https://docs.teslamate.org/docs/faq#how-to-generate-your-own-tokens`). > **Interactive human-terminal alternative** (TTY only — also supports Traefik + HTTPS reverse proxy): > `curl -fsSL https://mytess.net/scripts/install-teslamate.sh -o install.sh && bash install.sh` --- ## 5. Verification Checklist First determine `API_BASE_URL` from the actual deployment (do not assume port `3030` is published — Traefik/reverse-proxy setups expose the API at `https://` or `http://` on ports 443/80 without publishing port 3030): - Direct port mapping: `API_BASE_URL="http://127.0.0.1:"` (default `3030`) - Traefik / reverse proxy routing `/api`: `API_BASE_URL="https://"` (or `http://`) Run these checks after containers start (reuse `COMPOSE_ARGS`, `TM_SERVICE`, and `API_SERVICE` from Section 2 for existing stacks; for a fresh install in `$INSTALL_DIR`, set `COMPOSE_ARGS=(-f "$INSTALL_DIR/docker-compose.yml")`, `TM_SERVICE=teslamate`, `API_SERVICE=teslamateapi`): ```bash # 1. All services running docker compose "${COMPOSE_ARGS[@]}" ps # 2. Verify API is reachable AND is mytesla/teslamateapi (expect HTTP 200, "pong", and Mt-Api-Version header) curl -i "${API_BASE_URL}/api/ping" # 3. Verify DB + MQTT readiness (HTTP 200 = ready; 503 = check MQTT/DB logs) curl -i "${API_BASE_URL}/api/readyz" # 4. Verify AK/SK auth is enforced on protected endpoints (expect HTTP 401 without credentials) curl -s -o /dev/null -w "unauth_status=%{http_code}\n" "${API_BASE_URL}/api/v1/version" # 5. Verify AK/SK auth loaded cleanly with no DB/MQTT errors docker compose "${COMPOSE_ARGS[@]}" logs --tail=50 "$API_SERVICE" ``` Expected: - `/api/ping` returns `200 OK`, body `{"message":"pong"}`, and response header `Mt-Api-Version: ...` (absence of `Mt-Api-Version` means the wrong upstream image is running). - Unauthenticated `/api/v1/version` returns `401`, and logs contain `AK/SK signature auth is set`. - Note: `/api/ping` and `/api/readyz` skip auth, so they do not verify the handoff AK/SK pair itself. Validate the actual handoff credentials by tapping **Test Connection** in Mytess (or via a signed `TESLAMATEAPI-HMAC-SHA256` request to `/api/v1/version` run locally without printing `API_SECRET_KEY`). - If `/api/readyz` stays `503` or the Mytess dashboard is empty after vehicle authorization, run `docker compose "${COMPOSE_ARGS[@]}" restart "$TM_SERVICE"`. --- ## 6. Connect Mytess iOS App & Handoff ### One-Tap Setup Deep Link (iPhone / iPad Safari) ```text mytess://setup?url=&auth=aksk&ak=&sk= ``` - Example: if API URL is `http://192.168.1.100:3030`, encode `url` as `http%3A%2F%2F192.168.1.100%3A3030`. - For self-signed HTTPS certificates, append `&insecure_ssl=1`. - Note: `mytess://setup?...` only opens on an iPhone/iPad with Mytess installed (open in Safari). Always also provide the 3 manual values below. ### Manual App Setup 1. Install Mytess from the App Store (`https://apps.apple.com/app/id6757828502`, requires iOS 18.0+). 2. Open **Mytess -> Settings -> API Configuration**. 3. Enter **API Address** (`http://:3030` or `https://your-domain.com`), **API Access Key**, and **API Secret Key**. 4. Tap **Test Connection**, then select your vehicle. ### Final Handoff Summary (Deliver Privately to User) Provide: - **TeslaMate Web URL** (fresh installs: authorize vehicle here with Tesla tokens) - **API Address** - **API Access Key** & **API Secret Key** (remind user to store privately and never share) - **Safari Quick-Setup Link** (`mytess://setup?...`, noting it opens on iPhone/iPad Safari) - **Next steps** (authorize vehicle if fresh install; configure remote access if needed away from home Wi-Fi) --- ## 7. Remote Access & HTTPS - **Home Wi-Fi / LAN**: `http://:3030` works directly in the Mytess iOS app. - **Outside home network (recommended options)**: - **Cloudflare Tunnel**: free HTTPS without opening router ports; if Cloudflare Access is enabled, configure Cloudflare Service Auth headers in Mytess. - **Tailscale / WireGuard**: private mesh VPN; connect via the server's private VPN IP without exposing ports publicly. - **Reverse Proxy + HTTPS (Nginx / Caddy / Traefik + Let's Encrypt)**: standard HTTPS domain; if using a self-signed certificate, add `&insecure_ssl=1` or enable skip SSL verification in Mytess. - **frp / ngrok**: NAT traversal tunnel. --- ## 8. Troubleshooting & Maintenance - **Empty dashboard right after setup**: Data flows `TeslaMate -> MQTT -> TeslaMateAPI -> Mytess`. Run `docker compose "${COMPOSE_ARGS[@]}" restart "$TM_SERVICE"` so TeslaMate publishes fresh live state to MQTT. - **Homepage works, but insights / billing / stats are missing**: Confirm image is `mytesla/teslamateapi:latest` and `curl -i "${API_BASE_URL}/api/ping"` returns `Mt-Api-Version`. - **401 Unauthorized**: Verify `API_ACCESS_KEY` and `API_SECRET_KEY` match the API container (not Tesla tokens), and confirm server clock drift is within ±600 seconds (`date -u` / NTP). - **Upgrade `teslamateapi` (non-interactive)**: - Manual: `docker compose "${COMPOSE_ARGS[@]}" pull "$API_SERVICE" && docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps "$API_SERVICE"` - Script: `curl -fsSL https://mytess.net/scripts/mytess-tool.sh | MYTESS_LANG=en bash -s -- upgrade-api --yes --skip-auto-upgrade` - **Backup / Restore / Diagnose (human interactive terminal)**: - Backup: `curl -fsSL https://mytess.net/scripts/mytess-tool.sh | MYTESS_LANG=en bash -s -- backup` - Restore (destructive — confirm backup file first): `curl -fsSL https://mytess.net/scripts/mytess-tool.sh | MYTESS_LANG=en bash -s -- restore ` - Diagnose: `curl -fsSL https://mytess.net/scripts/mytess-tool.sh | MYTESS_LANG=en bash -s -- diagnose` - S3 automatic backup: `curl -fsSL https://mytess.net/scripts/teslamate-s3-backup.sh | bash`