Zero-downtime deploys with releases and a symlink: pm2 and Next.js
A deploy that runs git pull && npm install && npm run build on the server has two problems. During the build the site is in a half-written state — requests arrive while .next is being deleted and rewritten. And if something goes wrong there is no way back: all you have is a broken working directory.
The layout
/opt/app/
releases/
20260731-021243/
20260731-014756/
...
current -> releases/20260731-021243
shared/
dev.db
public-uploads/
Each deploy installs into a fresh directory under releases/. current is a symlink pointing at whichever one is live. The database and user uploads live in shared/, outside any release, so no deploy can touch them.
The detail that matters: point pm2 at the symlink
When you create the pm2 process, give it the symlink itself, not the resolved path:
# right
cd /opt/app/current
pm2 start ./node_modules/next/dist/bin/next -- start -p 4000
# wrong: pm2 resolves this and stores releases/20260731-.../
cd /opt/app/releases/20260731-021243
Set up correctly, a deploy reduces to: repoint the symlink, pm2 restart. No deleting and recreating the process.
Order matters
The symlink is not touched until the new release is completely ready:
- Create the release directory
- rsync the tracked files (
git ls-files, so uncommitted working-tree changes stay home) - Copy
.envfrom the previous release npm ciprisma generateandmigrate deploynpm run build- Flip the symlink and restart pm2 ← the only downtime, and it is seconds
- Health check — on failure, put the symlink back
The build happens in steps 1–6, while the live site keeps serving from the old release.
Automatic rollback
End the script with a health check that reverts the symlink when it fails:
if ! curl -fsS -o /dev/null "$HEALTH_URL"; then
ln -sfn "$PREVIOUS_RELEASE" "$APP_ROOT/current"
pm2 restart "$PROCESS_NAME"
exit 1
fi
Those few lines remove the "I deployed and the site is down" situation entirely.
Cleaning up
Every deploy leaves a full copy including node_modules, so disks fill quickly. Keeping the last eight releases is plenty in practice — you were never going to roll back further than that.
Why not a checkout on the server
Keeping no git repository on the server has a concrete benefit: the set of files shipped is defined explicitly by git ls-files. A file edited by hand on the server is quietly replaced on the next deploy instead of producing a conflict.