Manually Deploy Next.js on AWS EC2 with Shell Script

Do you want to know how to manually deploy an application without all advanced tools, just use shell script on Linux? Before we have CI/CD, Github Actions, AWS Codedeploy, etc. developers need to manually execute scripts to deploy, and I will show you brief steps to complete it.

Let me show you with a Next.js application, and I will deploy it on AWS EC2.

Once you connect to your server, execute the following code:

# Optional: clone code if you don't have app code on your destination server, example: git clone https://github.com/vercel/next.js.git
$ git clone <your app's' repo url>
# example: cd /home/ec2-user/next.js
$ cd <filepath of the directory you just cloned>
# install dependencies
$ npm install
# build
$ npm run build
# stop running process, example: ps -ef | grep ec2-user/next.js | grep -v grep |awk '{print $2}'| xargs kill -9
$ ps -ef | grep <app directory> | grep -v grep | awk '{print $2}'| xargs kill -9
# start app as a daemon process
$ (npm run start > /dev/null 2>&1 &)
view raw deploy.sh hosted with ❤ by GitHub

The command (npm run start > /dev/null 2>&1 &) is the key part:

  • npm run start start the app
  • /dev/null: /dev/nullIt’s a special file that’s present in every single Linux system. Whatever you write to /dev/null will be discarded, forgotten into the void. So with >, all output info from npm run start will not show in terminal
  • 2>$1: redirects stderr to stdout
  • &: makes the whole command execute in background
  • (): parentheses denote a subshell in bash, so the process won't stop after you exit the ssh session