How To Deploy A NodeJS Application On AWS EC2 Server
Prerequisite
Instance Type: Amazon Linux 2 AMI 2.0.20200207.1 x8664 HVM (_Free Tier Eligible)
Step 1: Install NodeJS
- Connect to your Linux instance
-
Install node version manager (nvm) by typing the following at the command line.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash -
Activate nvm by typing the following at the command line.
. ~/.nvm/nvm.sh -
Use nvm to install the latest version of Node.js by typing the following at the command line.
nvm install node -
Test that Node.js is installed and running correctly by typing the following at the command line.
node -e "console.log('Running Node.js ' + process.version)"OR
node -vBoth of which will show you node version
Step 2: Setup Demo Server
-
Make a folder
mkdir server -
Create a demo server code
cat >> index.js << EOF var app = require('express')(); console.log("Starting the server!"); var sampleJson = { "status": 200, "message": "Aloha!" } app.get('', function (req, res) { console.log("Processing Request") res.type('application/json'); res.send(sampleJson); }); console.log("Listening on port: 9000") app.listen(9000); EOFFeel free to modify the code
-
Install Express
npm install express
Step 3: Run the Server
Now You have two option for running the code
-
Run in Foreground
node index.js #Output----------------- Starting the server! Listening on port: 9000 #CTRL + C to exitIssue with this can be you won't be able to run any other commands
-
Run in Background
-
Install Latest Version of PM2
npm install pm2@latest -g -
Now start the server with command
pm2 start index.jsHere index.js is the target server file you want to run
-
Just to check the status of your server run below command
pm2 list # Sample Output ┌────┬────────────────────┬──────────┬──────┬───────────┬──────────┬──────────┐ │ id │ name │ mode │ ↺ │ status │ cpu │ memory │ ├────┼────────────────────┼──────────┼──────┼───────────┼──────────┼──────────┤ │ 0 │ index │ fork │ 0 │ online │ 1.4% │ 38.1mb │ └────┴────────────────────┴──────────┴──────┴───────────┴──────────┴──────────┘ -
To test the server, you have 2 ways
-
Locally (On EC2 Machine itself)
curl http://localhost:9000 # Output ------------------------- {"status":200,"message":"Aloha!"} -
Publicly (If available)
You will have to hit this URL http://ec2-public-address:9000/ from POSTMAN or similar tool
-
-
Debug
-
If you run into any issue, you can always check logs bu using following commands
pm2 logsThis will show you only last 15 statements from log
-
To view complete logs, you can use
cat /home/ec2-user/.pm2/logs/index-error.log cat /home/ec2-user/.pm2/logs/index-out.log -
In case you get port issue (Unavailable Port), you can use following command to list all ports in use
netstat -nltu