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
- Launch EC2 instance
- SSH to instance
- $ ssh user@192.168.1.1
- $ sudo apt-get update
- $ sudo apt-get install git
- Install Node.js with NVM
- $ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
- $ source ~/.bashrc
- $ nvm install 8
- $ node --version
- Setup node app on server
- rsync -av ~/Development/temp/app1 lightsail1:~/app1
- Install Nginx with apt-get
- $ sudo apt-get install nginx
- $ sudo /etc/init.d/nginx start
- 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
- 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
- copy .pem to ~/.ssh/ mv ~/Development/_resources/aws-cli-bash/ec2/dabblelab-dev.pem ~/.ssh/dabblelab-dev.pem
- chmod 600 ~/.ssh/dabblelab-dev.pem | chmod 400 ~/.ssh/dabblelab-dev.pem
- chmod 700 ~/.ssh/
- touch ~/.ssh/config
- chmod ~/.ssh/config 644
- nano ~/.ssh/config host dev1 Hostname [the IP or dns name] User root IdentityFile ~/.ssh/[your keypair here]
- ssh dev1