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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 &) |
The command (npm run start > /dev/null 2>&1 &)
is the key part:
npm run start
start the app/dev/null
:/dev/null
It’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 fromnpm run start
will not show in terminal2>$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