mrvautin

Deploying your Next.js website without any downtime

In an ideal world, you'd build your Next.js app locally, check it works then deploy the built app to your production server.

Sometimes you just want to deploy your Next.js website on the server and not build locally as stated above. To do this we are going to setup a simple shell script and use PM2 to deploy with no downtime.

An example PM2 ecosystem.config.js file in the root of your project:

module.exports = {
   apps: [
      {
         name: 'my-app',
         script: 'npm run start',
         cwd: '/Users/mrvautin/Documents/Code/my-app/',
         env: {
               NODE_ENV: 'development'
         },
         env_production: {
               NODE_ENV: 'production'
         }
      }
   ],
   deploy: {
      production: {
         user: 'my-user',
         host: 'my-server',
         key: '/Users/mrvautin/.ssh/id_rsa',
         ssh_options: 'ForwardAgent=yes',
         ref: 'origin/main',
         repo: '[email protected]:mrvautin/my-app.git',
         path: '/var/www/html/my-app',
         'post-deploy': 'sh nextjs-pm2-deploy.sh'
      }
   }
};

An example package.json with our deploy script:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "deploy": "pm2 deploy production"
  },
  "dependencies": {},
  "devDependencies": {}
}

Now the contents of the nextjs-pm2-deploy.sh shell script referenced in the post-deploy section of the ecosystem.config.js file above:

echo "Deploy starting..."

npm run install || exit

BUILD_DIR=temp npm run build || exit

if [ ! -d "temp" ]; then
  echo '\033[31m temp Directory not exists!\033[0m'  
  exit 1;
fi

rm -rf .next

mv temp .next

pm2 reload all --update-env
pm2 reset all

echo "Deploy done."

Summary

Basically, this script will install our app, set the build path to /temp, build the app into /temp, check the /temp directory exists then move the contents over and reset our PM2 instance.

All this happens in an instant and should see your app deployed with no noticeable downtime.

Related posts