Skip to main content

Setup EC2 for Node.js Apps

In this tutorial, we will set up an EC2 instance for node.js.

Prerequisites

Launch an EC2 instance

You can launch an EC2 instance using the AWS CLI. To launch an EC2 instance, run the following command:

aws ec2 run-instances --image-id ami-0b9e5e9e --count 1 --instance-type t2.micro --key-name my-key-pair --security-group-ids sg-0b9e5e9e --subnet-id subnet-0b9e5e9e

Steps

  1. Launch EC2 instance
  2. SSH to instance
  3. Install Node.js with NVM
  4. Setup node app on server
  • rsync -av ~/Development/temp/app1 lightsail1:~/app1
  1. Install Nginx with apt-get
    • $ sudo apt-get install nginx
    • $ sudo /etc/init.d/nginx start
  2. Route nginx ports
  • sudo nano /etc/nginx/sites-available/default

    server {
    listen 80;

    server_name example.com;

    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;
    }
    }
  • sudo service nginx restart

  1. Setup Node to use pm2 (or forever)
  • sudo npm install pm2 -g

  • pm2 start app.js

  • pm2 startup ubuntu

    #copy all of the files in this directory to the /home/will/newapp directory
    rsync -av ~/Development/temp/app1 lightsail1:~/app1

sudo apt-get install libcap2-bin sudo setcap cap_net_bind_service=+ep /usr/bin/node

SSH Tips

  • ssh user@ip-or-dns-name
  • apt-get is a package manager for Linux (Ubuantu)
  • exit
  • rsync -av . user@ip-or-dns-name:~/newdir

Passwordless SSH

On local Mac

  1. copy .pem to ~/.ssh/ mv ~/Development/_resources/aws-cli-bash/ec2/dabblelab-dev.pem ~/.ssh/dabblelab-dev.pem
  2. chmod 600 ~/.ssh/dabblelab-dev.pem | chmod 400 ~/.ssh/dabblelab-dev.pem
  3. chmod 700 ~/.ssh/
  4. touch ~/.ssh/config
  5. chmod ~/.ssh/config 644
  6. nano ~/.ssh/config host dev1 Hostname [the IP or dns name] User root IdentityFile ~/.ssh/[your keypair here]
  7. ssh dev1

Resources