diff --git a/scripts/websites-agent/deploy.sh b/scripts/websites-agent/deploy.sh index 6d71dc9..0108508 100755 --- a/scripts/websites-agent/deploy.sh +++ b/scripts/websites-agent/deploy.sh @@ -213,7 +213,74 @@ NODE fi echo "no standalone output — using next start (legacy)" -pm2 restart "$SLUG" --update-env || pm2 start "$ECOSYSTEM" --only "$SLUG" + +# Reset cwd/script in case a previous deploy used standalone. Do not +# `pm2 restart --update-env`: the deploy agent has PORT=9050 and that +# leaks into the site, so nginx (site port) gets 502. +SLUG="$SLUG" ROOT="$ROOT" ECOSYSTEM="$ECOSYSTEM" node <<'NODE' +const fs = require('fs'); +const path = process.env.ECOSYSTEM; +const slug = process.env.SLUG; +const root = process.env.ROOT; +let cfg = { apps: [] }; +try { + delete require.cache[require.resolve(path)]; + cfg = require(path); + if (!Array.isArray(cfg.apps)) cfg.apps = []; +} catch (_) { + cfg = { apps: [] }; +} + +const app = cfg.apps.find((a) => a.name === slug); +if (!app) { + console.error('ecosystem entry missing for', slug); + process.exit(1); +} + +const fromEnv = Number(app.env && app.env.PORT); +const fromArgs = Number((String(app.args || '').match(/--port\s+(\d+)/) || [])[1]); +const port = + [fromEnv, fromArgs].find((p) => Number.isFinite(p) && p > 0 && p !== 9050) || 3005; + +app.cwd = root; +app.script = 'node_modules/next/dist/bin/next'; +app.args = 'start --hostname 127.0.0.1 --port ' + port; +app.env = { + NODE_ENV: 'production', + PORT: String(port), +}; + +const lines = ['module.exports = {', ' apps: [']; +cfg.apps.forEach((entry, idx) => { + lines.push(' {'); + lines.push(` name: ${JSON.stringify(entry.name)},`); + lines.push(` cwd: ${JSON.stringify(entry.cwd)},`); + lines.push(` script: ${JSON.stringify(entry.script)},`); + if (entry.args) { + lines.push(` args: ${JSON.stringify(entry.args)},`); + } + lines.push(' env: {'); + for (const [key, value] of Object.entries(entry.env || {})) { + lines.push(` ${key}: ${JSON.stringify(String(value))},`); + } + lines.push(' },'); + lines.push(` error_file: ${JSON.stringify(entry.error_file)},`); + lines.push(` out_file: ${JSON.stringify(entry.out_file)},`); + lines.push(' time: true,'); + if (entry.max_memory_restart) { + lines.push(` max_memory_restart: ${JSON.stringify(entry.max_memory_restart)},`); + } + lines.push(idx === cfg.apps.length - 1 ? ' }' : ' },'); +}); +lines.push(' ],'); +lines.push('};'); +lines.push(''); +fs.writeFileSync(path, lines.join('\n')); +console.log('ecosystem updated for next start:', slug, 'port', port); +NODE + +pm2 delete "$SLUG" || true +pm2 start "$ECOSYSTEM" --only "$SLUG" pm2 save || true echo "==== $(date -u +%Y-%m-%dT%H:%M:%SZ) deploy ok: $SLUG ===="