Skip to content

Instantly share code, notes, and snippets.

@rockon1985
Last active June 29, 2023 06:50
Show Gist options
  • Select an option

  • Save rockon1985/015691b5cad005f49d0be1a62a74e393 to your computer and use it in GitHub Desktop.

Select an option

Save rockon1985/015691b5cad005f49d0be1a62a74e393 to your computer and use it in GitHub Desktop.
Walkthrough guide to deploy nodejs and postgres app using EC2, nginx and RDS

Deploying nodejs on AWS

1. Create AWS EC2 instance

We would prefer to go with Ubuntu Server 16.04 LTS (HVM) [ami-0d03add87774b12c5] for backward compatibility for older applications. But one can choose any version as per thier preference

2. Install nvm and Nodejs using nvm

install required native tools

sudo apt-get update
sudo apt-get install build-essential libssl-dev

download and run nvm installer bash script

curl -sL https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh -o install_nvm.sh
cat install_nvm.sh
bash install_nvm.sh

source profile file

source ~/.profile

Use LTS version of nodejs

nvm install v10.18.0
nvm use v10.18.0
node -v

3. Clone your project code

Use git clone to clone your git repository (Try to use HTTP clone as it is more secure)

4. Run your app

To run nodejs app, you can fire npm start after npm install. Or some other command if you have it custom configured

5. Keep your app running

The above step will only run your application till your login session is valid in the console. If you want to run your app permanently you need to use a process manager.

A. using PM2

npm install pm2 -g
pm2 start --name backend -- start

For automatically running PM2 when the server restarts, issue the following command:

pm2 startup

This will output a script in the terminal which you need to run, copy the script that it outputs and run it in the terminal window. Then fire command

pm2 save

B. Using forever

npm install forever -g
forever start -c "npm start" ./

6. Move the app to default HTTP port

Why nginx? and not PORT=80 ?

Due to following reasons:

  • We cannot expose our exress server directly to world
  • We may want to Filter out unwanted requests
  • We may want to have Rate limiting on incoming requests

We would need to configure a proxy that will redirect all the incoming traffic on port 80(default HTTP port) to the port running our app. For this we would need to install nginx

Installation

sudo apt-get install nginx

Setting up reverse proxy

After installation, add a reverse proxy by adding a server block in file /etc/nginx/sites-enabled/default

use the built in vi editor to open the file:

sudo vi /etc/nginx/sites-enabled/default

and paste this server block in the file.

server {
   listen         80 default_server;
   listen         [::]:80 default_server;
   server_name    localhost;
   root           /usr/share/nginx/html;
   location / {
       proxy_pass http://127.0.0.1:3000;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection 'upgrade';
       proxy_set_header Host $host;
       proxy_cache_bypass $http_upgrade;
   }
}

check if the configuration went well by command:

sudo nginx -t

and then restart the nginx service

sudo service nginx restart

7. Dealing with Databases

In most of the cases, our back end app deals with Databases. So now we would be covering the steps to wire a postgres database server in our application.

  1. First step is to create a RDS instance in the AWS console.

Go to Services > RDS > Launch new RDS instance and select desired configurations for your DB server.

  1. Next, you need to setup rules of its Security group to only allow request from your EC2 instance's security group. In the inbound rule section add a new rule with following options:
Type: Custom TCP
Port Range: 5432 # or any other port in which your DB is running
Source: Custom (Security group name of your EC2 instance)

8. Install Sequelize and initialize DB

npm install -g sequelize-cli

Copy the .env file securely having the database credentials

scp .env ubuntu@EC2_URL:~/node-postgres-api-starter

Note:

  • the environment variables are loaded from .env file using the npm package dotenv.
  • You can also manually set these env variables in the shell by using export command.
  • In production environment, instead of mounting secure fles from our PC, we use AWS Secrets Manager and IAM roles in order to fetch thte secrets safely directly on EC2 instance.

Database URL format:

postgresql://postgres:postgres@localhost:port/dev

Run the migrations on the database

sequelize db:migrate

Extra Notes: A bit about sequelize

  • Serves as the ORM layer in your node app
  • Lets you create models around existing tables and manage associations
  • maintains a list of migrations to be run on the database
  • Comes with a powerful command line tool sequelize-cli
  • Creating a model with its migration is as siple as typing command:
sequelize model:create --name User --attributes name:string,phone:string

9. Auto Scale your EC2 instances

  • In EC2 listing, select your EC2 instance
  • Choose Actions > Instance Settings > Attach to Auto Scaling Group > a new Auto Scaling group
  • Add a new scaling policy by selecting a metric and threshold value

More about Gammastack:

https://www.gammastack.com/

References:

Further steps:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment