Stop storefront deploys from inheriting the agent PORT and leftover standalone cwd.

pm2 restart --update-env leaked PORT=9050 onto Next sites and left nginx 502 when a build dropped standalone output.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Alireza Hassani
2026-08-30 09:41:37 +03:30
co-authored by Cursor
parent 0c1c3f7ff9
commit e37cb4a20d
+68 -1
View File
@@ -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 ===="