Commit bb243689 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add automated prod deploy pipeline (nginx reverse proxy + atomic release swap)

Push to main now builds, ships the dist/ over SSH, and installs/configures
nginx as a same-origin reverse proxy to the backend (matching the dev vite
proxy's own /api contract - no CORS, no exposed backend port), with an
atomic release symlink swap and a health check before declaring success.
TLS via certbot is wired in but opt-in (PROD_DOMAIN unset = plain HTTP for
now). Server access comes entirely from GitLab CI/CD variables
(PROD_SERVER_IP, PROD_SSH_PRIVATE_KEY, PROD_SSH_PORT), reusing the same
variable names the backend repo's own (still-disabled) deploy_prod job
already established.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 3f615474
stages:
- test
- deploy
variables:
npm_config_cache: "$CI_PROJECT_DIR/.cache/npm"
......@@ -12,7 +13,9 @@ cache:
# Runs on every push. Typechecks, runs the Vitest suite, and confirms the production build
# actually succeeds - all three catch different classes of bugs (tsc catches type errors
# vitest doesn't run into if a test happens not to exercise a given path; vite build catches
# real bundling/import issues tsc alone won't, e.g. a bad asset path or circular import).
# real bundling/import issues tsc alone won't, e.g. a bad asset path or circular import). The
# dist/ this produces is also what deploy_prod ships - built once here, not rebuilt on the
# server.
test:
stage: test
image: node:20-slim
......@@ -21,5 +24,56 @@ test:
- npx tsc -b --noEmit
- npm test
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 hour
only:
- main
# Only ever runs on main, and fires automatically once the test job above passes (needs:
# artifacts: true pulls test's dist/ output rather than rebuilding it). Ships that dist/ onto
# prod over SSH and runs deploy.sh there - deploy.sh handles everything else: nginx
# install/config (as a same-origin reverse proxy to the backend, plus optional TLS via certbot),
# an atomic release swap, and a reload.
#
# Server access comes entirely from GitLab CI/CD variables (Settings > CI/CD > Variables) -
# PROD_SERVER_IP, PROD_SSH_PRIVATE_KEY, and optionally PROD_SSH_PORT - deliberately kept out of
# this repo and this file entirely.
deploy_prod:
stage: deploy
image: python:3.10-slim
variables:
STAX_WEBAPP_DEPLOY_DIR: "/var/www/stax_webapp"
needs:
- job: test
artifacts: true
before_script:
- apt-get update -qq && apt-get install -y -qq --no-install-recommends openssh-client rsync
# This runner's job containers have a read-only root filesystem - /tmp is the one path
# that's reliably writable regardless, so everything SSH-related lives there instead.
# PROD_SSH_PRIVATE_KEY is a "Variable"-type CI/CD var (raw key text), not "File"-type
# (which would give us a path) - write it out ourselves so this doesn't depend on that
# GitLab dropdown being set exactly right.
- echo "$PROD_SSH_PRIVATE_KEY" > /tmp/prod_deploy_key
- chmod 600 /tmp/prod_deploy_key
- ssh-keyscan -p "${PROD_SSH_PORT:-22}" "$PROD_SERVER_IP" > /tmp/known_hosts 2>/dev/null || true
script:
- echo "Deploying $CI_COMMIT_SHORT_SHA to production..."
- >
scp -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/tmp/known_hosts -i /tmp/prod_deploy_key -P "${PROD_SSH_PORT:-22}"
deploy/scripts/deploy.sh root@"$PROD_SERVER_IP":/root/stax_webapp_deploy_bootstrap.sh
- >
rsync -az -e "ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/tmp/known_hosts -i /tmp/prod_deploy_key -p ${PROD_SSH_PORT:-22}"
dist/ root@"$PROD_SERVER_IP":/root/stax_webapp_release_${CI_COMMIT_SHORT_SHA}/
- >
ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/tmp/known_hosts -i /tmp/prod_deploy_key -p "${PROD_SSH_PORT:-22}"
root@"$PROD_SERVER_IP"
"STAX_WEBAPP_DEPLOY_DIR='${STAX_WEBAPP_DEPLOY_DIR}'
STAX_RELEASE_SHA='${CI_COMMIT_SHORT_SHA}'
STAX_RELEASE_SRC='/root/stax_webapp_release_${CI_COMMIT_SHORT_SHA}'
PROD_DOMAIN='${PROD_DOMAIN:-}'
PROD_DOMAIN_EMAIL='${PROD_DOMAIN_EMAIL:-}'
bash /root/stax_webapp_deploy_bootstrap.sh"
only:
- main
#!/usr/bin/env bash
# Installs a CI-built dist/ release on this machine. Invoked over SSH by the GitLab CI
# `deploy_prod` job on every push to main - see .gitlab-ci.yml. Can also be run by hand on the
# prod server for a manual redeploy/rollback.
#
# Unlike stax_backend_api's deploy.sh, the actual build (npm ci, vite build) happens in CI, not
# here - once a static SPA build exists it needs no runtime on the server at all, so there's no
# reason to install Node/npm on this box just to reproduce a build CI already produced and
# shipped over via rsync.
#
# Self-bootstrapping: safe to run against a completely bare machine (no nginx installed yet) as
# well as an already-deployed one - every step checks what's already there and only does the
# part that's missing.
#
# Releases are kept side-by-side under $STAX_WEBAPP_DEPLOY_DIR/releases/<sha>, with a `current`
# symlink that nginx's root points at and that gets swapped atomically - a request arriving
# mid-deploy sees either the fully old or fully new build, never a half-copied mix of both.
set -euo pipefail
DEPLOY_DIR="${STAX_WEBAPP_DEPLOY_DIR:-/var/www/stax_webapp}"
RELEASE_SHA="${STAX_RELEASE_SHA:?STAX_RELEASE_SHA must be set to the commit this release was built from}"
RELEASE_SRC="${STAX_RELEASE_SRC:?STAX_RELEASE_SRC must be set to the path the built dist/ was rsynced to}"
RELEASE_DIR="$DEPLOY_DIR/releases/$RELEASE_SHA"
KEEP_RELEASES=5
HEALTH_TIMEOUT_SECONDS="${STAX_HEALTH_TIMEOUT_SECONDS:-30}"
log() { echo "[deploy] $*"; }
# --- 1. System packages - idempotent, apt skips anything already satisfied -----------------
log "Ensuring nginx is present"
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq --no-install-recommends nginx curl
# --- 2. Move the CI-built release into place, then swap the symlink immediately - the release
# fully exists on disk before anything points at it, and nginx's root target is never briefly
# missing/half-written -------------------------------------------------------------------
log "Installing release $RELEASE_SHA"
mkdir -p "$DEPLOY_DIR/releases"
rm -rf "$RELEASE_DIR"
mv "$RELEASE_SRC" "$RELEASE_DIR"
ln -sfn "$RELEASE_DIR" "$DEPLOY_DIR/current"
# --- 3. nginx site config - regenerated from scratch every deploy (rather than hand-edited
# once and left alone), so a config change ships the same way any other code change does, just
# by being in this script when it next runs. Safe to regenerate even after certbot has edited
# this same file (step 4 below): certbot reapplies its edits idempotently every run without
# requesting a new certificate, as long as one it can reuse already exists on disk. -----------
SITE_CONF="/etc/nginx/sites-available/stax_webapp"
log "Writing nginx site config"
cat > "$SITE_CONF" <<EOF
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root $DEPLOY_DIR/current;
index index.html;
# Audio upload (Upload page, Telegram chat scanning) needs real headroom - nginx's 1m
# default would reject most real audio files outright.
client_max_body_size 200m;
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
location / {
try_files \$uri \$uri/ /index.html;
}
# index.html references hashed asset filenames, so it must always be revalidated - caching
# it would pin a client to a stale build indefinitely, unlike the assets below.
location = /index.html {
add_header Cache-Control "no-cache";
}
location ~* \.(?:js|css|svg|png|jpg|jpeg|gif|ico|woff2?)\$ {
try_files \$uri =404;
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
}
# Same-origin API proxy, mirroring the dev server's own vite proxy (see vite.config.ts):
# the backend runs on this same box, loopback-only, and is never exposed directly - the
# browser only ever talks to this one origin, so client.ts's default API_BASE_URL of '/api'
# works with no build-time override. /api is stripped before forwarding (proxy_pass's
# trailing-slash target does this), and proxy_buffering is off so large audio stream
# responses reach the client as they arrive rather than being buffered whole in nginx first
# - the exact bug class already fixed once at the app layer (see stream endpoints).
location /api/ {
proxy_pass http://127.0.0.1:8000/;
proxy_http_version 1.1;
proxy_buffering off;
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 "upgrade";
}
}
EOF
ln -sf "$SITE_CONF" /etc/nginx/sites-enabled/stax_webapp
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable nginx >/dev/null 2>&1 || true
systemctl reload nginx || systemctl restart nginx
# --- 4. Optional TLS via certbot, only if a domain is actually configured -------------------
# Skipped entirely (plain HTTP on the bare IP) until PROD_DOMAIN is set - acquiring a real
# certificate needs a domain with DNS already pointed at this box, which is outside anything
# this script or CI can arrange on its own. This isn't just a hardening nicety: the browser
# Geolocation API (used by Soundmarks/LiveLocation) refuses to run at all on a plain http://
# origin that isn't localhost - those features stay non-functional until this step has run.
if [ -n "${PROD_DOMAIN:-}" ]; then
log "PROD_DOMAIN set to $PROD_DOMAIN - ensuring certbot + a valid cert"
apt-get install -y -qq --no-install-recommends certbot python3-certbot-nginx
certbot --nginx -d "$PROD_DOMAIN" --non-interactive --agree-tos \
-m "${PROD_DOMAIN_EMAIL:-admin@$PROD_DOMAIN}" --redirect
nginx -t
systemctl reload nginx
else
log "PROD_DOMAIN not set - serving plain HTTP on the bare IP. Geolocation-dependent features (Soundmarks, LiveLocation) will not work until a domain is pointed at this box and PROD_DOMAIN is set."
fi
# --- 5. Prune old releases, keeping enough for a quick rollback without letting them pile up
# up on a disk that's already a real constraint on this box --------------------------------
log "Pruning old releases (keeping last $KEEP_RELEASES)"
cd "$DEPLOY_DIR/releases"
# shellcheck disable=SC2012
ls -1t | tail -n +$((KEEP_RELEASES + 1)) | xargs -r rm -rf
# --- 6. Health check -------------------------------------------------------------------
log "Waiting up to ${HEALTH_TIMEOUT_SECONDS}s for http://127.0.0.1/ to respond"
deadline=$((SECONDS + HEALTH_TIMEOUT_SECONDS))
until curl -fsS -o /dev/null http://127.0.0.1/; do
if [ "$SECONDS" -ge "$deadline" ]; then
log "FAILED: frontend did not respond after deploy"
log "nginx error log:"
tail -n 50 /var/log/nginx/error.log 2>/dev/null || true
log "Previous release is still on disk under $DEPLOY_DIR/releases/ - to roll back:"
log " ln -sfn $DEPLOY_DIR/releases/<previous-sha> $DEPLOY_DIR/current && systemctl reload nginx"
exit 1
fi
sleep 2
done
log "Deploy successful - $RELEASE_SHA is live"
......@@ -71,7 +71,10 @@ export default defineConfig(({ mode }) => {
// ever sees https://<ip>:5173/api/..., and the actual http:// hop happens server-side in
// Node, which isn't subject to the browser's mixed-content policy.
// VITE_API_BASE_URL is set to "/api" for dev via .env.development.local to route through
// this; production builds still point it at a real absolute URL directly.
// this. Production builds leave it unset too (client.ts's own default is already "/api")
// - prod's nginx (see deploy/scripts/deploy.sh) proxies /api the same way, stripping the
// prefix before forwarding to the backend on the same box. Same reasoning as here: one
// origin, no CORS, no exposed backend port.
proxy: {
'/api': {
target: backendProxyTarget,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment