douyinWEB/scripts/bootstrap_vps.sh
eric ca9e4b6676 feat: add shared-VPS bootstrap script and public_base_url for new deploys
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 05:45:27 -05:00

530 lines
17 KiB
Bash

#!/usr/bin/env bash
# douyinWEB one-click bootstrap for a shared Ubuntu VPS.
#
# Safety:
# - Does NOT modify existing Nginx/BaoTa vhosts, Docker, Gitea, or other systemd units
# - Does NOT apt-upgrade, change timezone, install Caddy, or open extra public ports
# - Binds app ports to 127.0.0.1 only; public entry is one new server_name
# - Aborts if chosen ports are already in use
# - Nginx: test config first; reload only if test passes; rolls back new vhost on failure
#
# Usage (on the target VPS as root):
# DOMAIN=ypp.example.com \
# ADMIN_USER=dsx2016 ADMIN_PASS='***' \
# GIT_URL='https://user:pass@git.example/eric/douyinWEB.git' \
# GIT_BRANCH=test1 FRESH=1 \
# bash scripts/bootstrap_vps.sh
#
# Optional:
# APP_DIR=/opt/douyinWEB
# PUBLIC_SCHEME=https
# WEB_PORT=4015 API_PORT=8014 PB_PORT=8092 YT_PORT=8020 S3_PORT=8333
# SW_MASTER_PORT=19333 SW_VOLUME_PORT=18080 SW_FILER_PORT=18888
set -euo pipefail
DOMAIN="${DOMAIN:?set DOMAIN, e.g. ypp.smallzhiyuns.com}"
ADMIN_USER="${ADMIN_USER:?set ADMIN_USER}"
ADMIN_PASS="${ADMIN_PASS:?set ADMIN_PASS}"
GIT_URL="${GIT_URL:?set GIT_URL}"
GIT_BRANCH="${GIT_BRANCH:-test1}"
APP_DIR="${APP_DIR:-/opt/douyinWEB}"
FRESH="${FRESH:-0}"
PUBLIC_SCHEME="${PUBLIC_SCHEME:-https}"
PUBLIC_BASE="${PUBLIC_BASE:-${PUBLIC_SCHEME}://${DOMAIN}}"
WEB_PORT="${WEB_PORT:-4015}"
API_PORT="${API_PORT:-8014}"
PB_PORT="${PB_PORT:-8092}"
YT_PORT="${YT_PORT:-8020}"
S3_PORT="${S3_PORT:-8333}"
SW_MASTER_PORT="${SW_MASTER_PORT:-19333}"
SW_VOLUME_PORT="${SW_VOLUME_PORT:-18080}"
SW_FILER_PORT="${SW_FILER_PORT:-18888}"
PB_ADMIN_EMAIL="${PB_ADMIN_EMAIL:-${ADMIN_USER}@${DOMAIN}}"
S3_ACCESS="${S3_ACCESS:-douyin}"
S3_BUCKET="${S3_BUCKET:-douyin-covers}"
WEED_VER="${WEED_VER:-3.80}"
PB_VER="${PB_VER:-0.25.8}"
ENV_FILE="/etc/douyinweb.env"
SW_DATA="/data/douyinweb-seaweed"
BAOTA_NGINX="/www/server/nginx/sbin/nginx"
BAOTA_VHOST_DIR="/www/server/panel/vhost/nginx"
log() { printf '\n[%s] %s\n' "$(date '+%F %T')" "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
[[ "$(id -u)" -eq 0 ]] || die "run as root"
port_in_use() {
local p="$1"
ss -lnt | awk '{print $4}' | grep -E "[:.]${p}$" >/dev/null 2>&1
}
assert_ports_free() {
local p
if systemctl is-active --quiet douyinweb-api 2>/dev/null; then
log "douyinweb already running — skip port occupancy check"
return
fi
for p in "$WEB_PORT" "$API_PORT" "$PB_PORT" "$YT_PORT" "$S3_PORT" "$SW_MASTER_PORT" "$SW_VOLUME_PORT" "$SW_FILER_PORT"; do
if port_in_use "$p"; then
die "port ${p} is already in use — pick another via env, do not kill existing services"
fi
done
}
detect_nginx() {
if [[ -x "$BAOTA_NGINX" ]]; then
NGINX_BIN="$BAOTA_NGINX"
NGINX_MODE="baota"
return
fi
if command -v nginx >/dev/null 2>&1; then
NGINX_BIN="$(command -v nginx)"
NGINX_MODE="system"
return
fi
die "nginx not found; this script adds a vhost to existing nginx and will not install Caddy"
}
persist_secrets() {
if [[ -f "$ENV_FILE" ]]; then
# shellcheck disable=SC1090
source "$ENV_FILE"
log "loaded existing $ENV_FILE (secrets reused)"
return
fi
SESSION_SECRET="$(openssl rand -hex 24)"
S3_SECRET="$(openssl rand -hex 18)"
cat >"$ENV_FILE" <<EOF
# generated $(date -u '+%F %T') UTC — do not rotate casually (login hash depends on SESSION_SECRET)
DOMAIN=${DOMAIN}
PUBLIC_BASE=${PUBLIC_BASE}
ADMIN_USER=${ADMIN_USER}
SESSION_SECRET=${SESSION_SECRET}
S3_SECRET=${S3_SECRET}
S3_ACCESS=${S3_ACCESS}
S3_BUCKET=${S3_BUCKET}
GIT_BRANCH=${GIT_BRANCH}
WEB_PORT=${WEB_PORT}
API_PORT=${API_PORT}
PB_PORT=${PB_PORT}
YT_PORT=${YT_PORT}
S3_PORT=${S3_PORT}
EOF
chmod 600 "$ENV_FILE"
log "wrote $ENV_FILE"
}
install_packages() {
export DEBIAN_FRONTEND=noninteractive
log "installing only missing packages (no apt upgrade)"
apt-get update -y
apt-get install -y --no-install-recommends \
git curl unzip ca-certificates ffmpeg \
python3 python3-venv python3-pip
NODE_BIN="$(command -v node)"
NPM_BIN="$(command -v npm)"
[[ -n "$NODE_BIN" && -n "$NPM_BIN" ]] || die "node/npm not in PATH"
ffmpeg -version | head -1
}
clone_repo() {
log "clone/update $APP_DIR branch $GIT_BRANCH"
if [[ -d "$APP_DIR/.git" ]]; then
git -C "$APP_DIR" remote set-url origin "$GIT_URL"
git -C "$APP_DIR" fetch --depth=1 origin "$GIT_BRANCH"
git -C "$APP_DIR" checkout -B "$GIT_BRANCH" "origin/$GIT_BRANCH"
else
[[ -e "$APP_DIR" && ! -d "$APP_DIR/.git" ]] && die "$APP_DIR exists and is not a git repo"
git clone --depth=1 --branch "$GIT_BRANCH" "$GIT_URL" "$APP_DIR"
fi
git -C "$APP_DIR" log -1 --oneline
# never import another environment's runtime data
rm -f "$APP_DIR/backend/data/monitor.db" \
"$APP_DIR/backend/data/monitor.db-shm" \
"$APP_DIR/backend/data/monitor.db-wal"
if [[ "$FRESH" == "1" ]]; then
log "FRESH=1 wiping local app data only under $APP_DIR and $SW_DATA"
rm -rf "$APP_DIR/backend/data/covers" "$APP_DIR/backend/data/clips" "$APP_DIR/pb/pb_data"
mkdir -p "$APP_DIR/backend/data/covers" "$APP_DIR/backend/data/clips"
fi
}
install_pocketbase() {
mkdir -p "$APP_DIR/pb"
if [[ ! -x "$APP_DIR/pb/pocketbase" ]]; then
log "download PocketBase $PB_VER"
curl -fsSL -o /tmp/pb.zip \
"https://github.com/pocketbase/pocketbase/releases/download/v${PB_VER}/pocketbase_${PB_VER}_linux_amd64.zip"
unzip -o /tmp/pb.zip pocketbase -d "$APP_DIR/pb"
chmod +x "$APP_DIR/pb/pocketbase"
rm -f /tmp/pb.zip
fi
"$APP_DIR/pb/pocketbase" --version
}
install_seaweed() {
mkdir -p /opt/seaweedfs "$SW_DATA/master" "$SW_DATA/volume" "$SW_DATA/filer" /etc/seaweedfs
if [[ ! -x /opt/seaweedfs/weed ]]; then
log "download SeaweedFS $WEED_VER"
curl -fsSL -o /tmp/weed.tgz \
"https://github.com/seaweedfs/seaweedfs/releases/download/${WEED_VER}/linux_amd64.tar.gz"
tar -xzf /tmp/weed.tgz -C /opt/seaweedfs weed
chmod +x /opt/seaweedfs/weed
rm -f /tmp/weed.tgz
fi
cat >/etc/seaweedfs/douyinweb-s3.json <<EOF
{
"identities": [
{
"name": "douyinweb",
"credentials": [{"accessKey": "${S3_ACCESS}", "secretKey": "${S3_SECRET}"}],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
}
]
}
EOF
}
write_units() {
NODE_BIN="${NODE_BIN:-$(command -v node)}"
NPM_BIN="${NPM_BIN:-$(command -v npm)}"
[[ -n "$NODE_BIN" && -n "$NPM_BIN" ]] || die "node/npm missing"
log "writing systemd units (new names only)"
cat >/etc/systemd/system/douyinweb-pb.service <<EOF
[Unit]
Description=DouyinWEB PocketBase (localhost only)
After=network.target
[Service]
Type=simple
WorkingDirectory=${APP_DIR}/pb
ExecStart=${APP_DIR}/pb/pocketbase serve --http=127.0.0.1:${PB_PORT}
Restart=always
RestartSec=3
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/douyinweb-yt.service <<EOF
[Unit]
Description=DouyinWEB YouTube.js sidecar
After=network.target
[Service]
Type=simple
WorkingDirectory=${APP_DIR}/youtube-svc
Environment=YT_SVC_HOST=127.0.0.1
Environment=YT_SVC_PORT=${YT_PORT}
Environment=NODE_ENV=production
ExecStart=${NODE_BIN} src/server.mjs
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/douyinweb-api.service <<EOF
[Unit]
Description=DouyinWEB FastAPI
After=network.target douyinweb-pb.service douyinweb-s3.service
[Service]
Type=simple
WorkingDirectory=${APP_DIR}/backend
Environment=TZ=Asia/Shanghai
Environment=DY_PB_URL=http://127.0.0.1:${PB_PORT}
Environment=DY_PB_ADMIN_EMAIL=${PB_ADMIN_EMAIL}
Environment=DY_PB_ADMIN_PASSWORD=${ADMIN_PASS}
Environment=DY_S3_ENABLED=true
Environment=DY_S3_ENDPOINT=http://127.0.0.1:${S3_PORT}
Environment=DY_S3_PUBLIC_BASE=${PUBLIC_BASE}
Environment=DY_S3_ACCESS_KEY=${S3_ACCESS}
Environment=DY_S3_SECRET_KEY=${S3_SECRET}
Environment=DY_S3_BUCKET=${S3_BUCKET}
Environment=DY_S3_REGION=us-east-1
Environment=DY_YOUTUBE_SVC_URL=http://127.0.0.1:${YT_PORT}
Environment=DY_PUBLIC_BASE_URL=${PUBLIC_BASE}
Environment=DY_CORS_ORIGINS=${PUBLIC_BASE},http://127.0.0.1:${WEB_PORT}
Environment=DY_AUTH_ENABLED=true
Environment=DY_ADMIN_USERNAME=${ADMIN_USER}
Environment=DY_ADMIN_PASSWORD=${ADMIN_PASS}
Environment=DY_SESSION_SECRET=${SESSION_SECRET}
ExecStart=${APP_DIR}/backend/.venv/bin/python -m uvicorn app.main:app --host 127.0.0.1 --port ${API_PORT}
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/douyinweb-web.service <<EOF
[Unit]
Description=DouyinWEB Next.js
After=network.target douyinweb-api.service
[Service]
Type=simple
WorkingDirectory=${APP_DIR}/frontend
Environment=TZ=Asia/Shanghai
Environment=NODE_ENV=production
Environment=DY_INTERNAL_API_URL=http://127.0.0.1:${API_PORT}
Environment=DY_PUBLIC_BASE_URL=${PUBLIC_BASE}
Environment=PORT=${WEB_PORT}
Environment=HOSTNAME=127.0.0.1
ExecStart=${NPM_BIN} run start -- --hostname 127.0.0.1 --port ${WEB_PORT}
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/douyinweb-sw-master.service <<EOF
[Unit]
Description=DouyinWEB SeaweedFS master
After=network.target
[Service]
ExecStart=/opt/seaweedfs/weed master -ip=127.0.0.1 -port=${SW_MASTER_PORT} -mdir=${SW_DATA}/master
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/douyinweb-sw-volume.service <<EOF
[Unit]
Description=DouyinWEB SeaweedFS volume
After=network.target douyinweb-sw-master.service
Requires=douyinweb-sw-master.service
[Service]
ExecStart=/opt/seaweedfs/weed volume -mserver=127.0.0.1:${SW_MASTER_PORT} -ip=127.0.0.1 -port=${SW_VOLUME_PORT} -dir=${SW_DATA}/volume -max=100
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/douyinweb-sw-filer.service <<EOF
[Unit]
Description=DouyinWEB SeaweedFS filer
After=network.target douyinweb-sw-master.service douyinweb-sw-volume.service
[Service]
ExecStart=/opt/seaweedfs/weed filer -master=127.0.0.1:${SW_MASTER_PORT} -ip=127.0.0.1 -port=${SW_FILER_PORT} -defaultReplicaPlacement=000
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
cat >/etc/systemd/system/douyinweb-s3.service <<EOF
[Unit]
Description=DouyinWEB SeaweedFS S3 API
After=network.target douyinweb-sw-filer.service
Requires=douyinweb-sw-filer.service
[Service]
ExecStart=/opt/seaweedfs/weed s3 -filer=127.0.0.1:${SW_FILER_PORT} -ip.bind=127.0.0.1 -port=${S3_PORT} -config=/etc/seaweedfs/douyinweb-s3.json
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
}
app_python_node() {
log "python venv + pip"
python3 -m venv "$APP_DIR/backend/.venv"
"$APP_DIR/backend/.venv/bin/pip" install -U pip
"$APP_DIR/backend/.venv/bin/pip" install -r "$APP_DIR/backend/requirements.txt"
log "youtube-svc npm"
(cd "$APP_DIR/youtube-svc" && npm install --omit=dev --no-audit --no-fund)
log "frontend npm build"
(cd "$APP_DIR/frontend" && npm install --no-audit --no-fund && npm run build)
}
start_stack() {
log "enable/start douyinweb units only"
systemctl enable --now \
douyinweb-sw-master douyinweb-sw-volume douyinweb-sw-filer douyinweb-s3 \
douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web
sleep 4
systemctl is-active \
douyinweb-sw-master douyinweb-sw-volume douyinweb-sw-filer douyinweb-s3 \
douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web
}
ensure_bucket_and_admin() {
sleep 3
"$APP_DIR/backend/.venv/bin/python" - <<PY
import boto3
from botocore.client import Config
c=boto3.client("s3", endpoint_url="http://127.0.0.1:${S3_PORT}",
aws_access_key_id="${S3_ACCESS}", aws_secret_access_key="${S3_SECRET}",
region_name="us-east-1", config=Config(signature_version="s3v4", s3={"addressing_style":"path"}))
try:
c.create_bucket(Bucket="${S3_BUCKET}")
print("bucket created")
except Exception as e:
print("bucket", e)
print(c.list_buckets())
PY
mkdir -p "$APP_DIR/pb/pb_data"
"$APP_DIR/pb/pocketbase" superuser upsert "$PB_ADMIN_EMAIL" "$ADMIN_PASS" || true
}
write_nginx_vhost() {
detect_nginx
local cert_dir
if [[ "$NGINX_MODE" == "baota" ]]; then
cert_dir="/www/server/panel/vhost/cert/${DOMAIN}"
mkdir -p "$cert_dir" \
"/www/wwwroot/${DOMAIN}" \
"/www/server/panel/vhost/nginx/proxy/${DOMAIN}" \
"/www/server/panel/vhost/nginx/extension/${DOMAIN}" \
"/www/server/panel/vhost/nginx/well-known"
shopt -s nullglob
local chains=(/root/.acme.sh/*.smallzhiyuns.com_ecc/fullchain.cer)
local keys=(/root/.acme.sh/*.smallzhiyuns.com_ecc/*.smallzhiyuns.com.key)
if [[ ${#chains[@]} -ge 1 && ${#keys[@]} -ge 1 ]]; then
cp -f "${chains[0]}" "$cert_dir/fullchain.pem"
cp -f "${keys[0]}" "$cert_dir/privkey.pem"
elif [[ -f "${cert_dir}/fullchain.pem" ]]; then
log "using existing baota cert for $DOMAIN"
else
die "no TLS cert for ${DOMAIN}; place fullchain/privkey or a matching acme.sh wildcard first"
fi
: > "/www/server/panel/vhost/nginx/well-known/${DOMAIN}.conf"
: > "/www/server/panel/vhost/rewrite/${DOMAIN}.conf"
echo "# douyinweb extension placeholder" > "/www/server/panel/vhost/nginx/extension/${DOMAIN}/placeholder.conf"
cat >"/www/server/panel/vhost/nginx/proxy/${DOMAIN}/douyinweb.conf" <<EOF
#PROXY-START/ douyinWEB — do not use BaoTa to overwrite this file casually
location ^~ /api/ {
proxy_pass http://127.0.0.1:${API_PORT};
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection \$connection_upgrade;
proxy_read_timeout 3600s;
client_max_body_size 200m;
}
location ^~ /covers/ {
proxy_pass http://127.0.0.1:${API_PORT};
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-Proto \$scheme;
}
location ^~ /_/ {
proxy_pass http://127.0.0.1:${PB_PORT};
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-Proto \$scheme;
}
location ^~ /${S3_BUCKET}/ {
proxy_pass http://127.0.0.1:${S3_PORT};
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-Proto \$scheme;
client_max_body_size 200m;
}
location / {
proxy_pass http://127.0.0.1:${WEB_PORT};
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection \$connection_upgrade;
proxy_read_timeout 60s;
}
#PROXY-END/
EOF
local vhost="${BAOTA_VHOST_DIR}/${DOMAIN}.conf"
[[ -f "$vhost" ]] && cp -a "$vhost" "${vhost}.bak.$(date +%s)"
cat >"$vhost" <<EOF
server
{
listen 80;
listen 443 ssl http2;
server_name ${DOMAIN};
index index.html;
root /www/wwwroot/${DOMAIN};
client_max_body_size 200m;
ssl_certificate ${cert_dir}/fullchain.pem;
ssl_certificate_key ${cert_dir}/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:!MD5;
ssl_prefer_server_ciphers on;
error_page 497 https://\$host\$request_uri;
include /www/server/panel/vhost/nginx/well-known/${DOMAIN}.conf;
include /www/server/panel/vhost/nginx/proxy/${DOMAIN}/*.conf;
location ~ \.well-known { allow all; }
access_log /www/wwwlogs/${DOMAIN}.log;
error_log /www/wwwlogs/${DOMAIN}.error.log;
}
EOF
else
die "non-BaoTa nginx detected; add a server_name for ${DOMAIN} manually then re-run. Refusing to overwrite /etc/nginx defaults."
fi
log "nginx -t then reload (existing sites keep their vhosts)"
if ! "$NGINX_BIN" -t; then
rm -f "${BAOTA_VHOST_DIR}/${DOMAIN}.conf"
die "nginx test failed; new vhost removed, existing sites untouched"
fi
"$NGINX_BIN" -s reload
}
verify() {
log "verify localhost"
curl -fsS "http://127.0.0.1:${API_PORT}/api/health" | head -c 400; echo
curl -sS -o /dev/null -w "web:%{http_code}\n" "http://127.0.0.1:${WEB_PORT}/login" || true
log "verify public ${PUBLIC_BASE} (may take a few seconds)"
curl -sS -o /dev/null -w "pub_login:%{http_code}\n" --max-time 20 "${PUBLIC_BASE}/login" || true
curl -sS -o /dev/null -w "pub_health:%{http_code}\n" --max-time 20 "${PUBLIC_BASE}/api/health" || true
echo
echo "URL ${PUBLIC_BASE}/"
echo "login ${ADMIN_USER}"
echo "PB ${PUBLIC_BASE}/_/"
echo "PB mail ${PB_ADMIN_EMAIL}"
}
main() {
log "douyinWEB bootstrap DOMAIN=$DOMAIN APP_DIR=$APP_DIR FRESH=$FRESH"
assert_ports_free
persist_secrets
# shellcheck disable=SC1090
source "$ENV_FILE"
install_packages
clone_repo
install_pocketbase
install_seaweed
write_units
app_python_node
start_stack
ensure_bucket_and_admin
write_nginx_vhost
verify
log "DONE — existing services were not stopped"
}
main "$@"