Deploy a Node.js Application to Amazon Web Services (AWS)
In this blog post I am going to show how you can deploy a simple node js web application to amazon web services so that it can be live over the internet. I will try my best to use the best practices in this tutorial
Prerequisites
- Install Git Bash if you are using windows(Terminal is enough in Mac or Linux)
- Sign Up for AWS
Launch an EC2 instance
- Go to AWS and sign into your console
- Under Services tab up in the navbar choose EC2 to go into the EC2 console
- Go to the instance tab from the sidebar
- Click on Launch instance from the instance menu
- Under OS select Ubuntu 16.04 or which ever OS you like
- Select the instance size
- Leave networking and other stuff to default
- Leave the storage to default too in the next tab
- Configure the security group. Add all the ports from the menu you want (eg PORT 80 for http)
- Click Review and Launch
- From the pop up, choose create a new key pair and download the key pair.
- Click on launch instance
SSH into the server
After in the EC2 console the status of the instance is running, go ahead and click on the instance and copy the public IP from the menu opened and follow the following steps.
- Open git bash if you are in windows or terminal if you are in mac or Linux.
- Navigate to the folder using
cd
where you downloaded the key pair. - SSH into the server by using the command
ssh -i "node.pem" [email protected]
Change the filename and IP address to yours. If it says keyfile permissions too open typechmod 400 node.pem
to fix it. - You should be presented with the welcome message.
Setting up Server
- First update the package manager by
sudo apt-get update
- Then upgrade any outdated packages by
sudo apt-get upgrade
- Now we have to install node.
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - && sudo apt-get install -y nodejs
- Verify the installation by
node -v
- Transfer your node application to the server. I recommend github repository for it. You may use rsync as well.
- Install your npm dependencies by
npm install
- Start you application
node index.js
.Replace index.js with your app’s starting script - In your browser go to
http://YOURSERVERIP:PORT
. You should see your app up and running.
Run our app using forever
If you close your terminal now your app will stop working. We want to run it in the background. We will use the forever
package.
- Install forever by
sudo npm install -g forever
- Start your app using
forever start index.js
Replace index.js with your app’s starting script. - In your browser go to
http://YOURSERVERIP:PORT
. You should see your app up and running. - Verify it in forever to by
forever list
Redirect port 80 to 8080
As by default browser communicate to port 80 of the server in http mode and port 443 in https. So we need to redirect port 8080 to port 80. Use this command for it.
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
Tags: deploymentnode