Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save syafiqfaiz/11ed4bf1ee0acec60c4dfce93906e786 to your computer and use it in GitHub Desktop.
Save syafiqfaiz/11ed4bf1ee0acec60c4dfce93906e786 to your computer and use it in GitHub Desktop.
Shell script to deploy self hosted Nextjs using PM2

Shell script for zero downtime self hosted nextjs application deployment using Pm2

Whats happening in the script?

  1. It start with making a copy of current application into a temporary folder.
  2. Spin up a separate PM2 server using the newly copied application.
  3. Once the server is up and running, we switch the reverse proxy server, in my case we are using nginx.
  4. We turn of the current reverse proxy server and replace it with new reverse proxy that is pointing to new temporary next js application.
  5. Turn off the current production PM2 server.
  6. Now we can start with pulling the latest code to the server and building a new production build.
  7. Once the production build is done, we can start the PM2 server back online.
  8. We swap again the nginx config
  9. Now our server should point to newly updated application
  10. Cleanup and we are done.
#!/bin/bash
set -e
# deploying new production
echo "Starting production deployment"
# copy all files from current production to the temp directory
echo "Copying files to production temp directory"
cp -r /var/www/your-app/* /var/www/your-app.temp | pv -lep -s $(du -sb /var/www/your-app | awk '{print $1}') >/dev/null
# turn on temporary app server
echo "Turning on temporary app server"
pm2 start your-app-temp
# swap nginx config
echo "Swapping nginx config"
sudo rm /etc/nginx/sites-enabled/your-app.conf
sudo ln -s /etc/nginx/sites-available/your-app.temp.conf /etc/nginx/sites-enabled/your-app.temp.conf
sudo service nginx reload
# stop the current app server
echo "Stopping current app server"
pm2 stop your-app
# building the new app
echo "Building the new app"
cd /var/www/your-app/
git fetch origin main
git reset --hard origin/main
yarn install
yarn build
# turn on the main app server
echo "Turning on the main app server"
pm2 start your-app
# swap nginx config
echo "Swapping nginx config"
sudo rm /etc/nginx/sites-enabled/your-app.temp.conf
sudo ln -s /etc/nginx/sites-available/your-app.conf /etc/nginx/sites-enabled/your-app.conf
sudo service nginx reload
# turn off temporary app server
echo "Turning off temporary app server"
pm2 stop your-app-temp
echo "Staging deployment completed"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment