Node.js App on AWS EC2 Instance

To get started let’s spin up an Ubuntu 16.4 LTS instance on AWS.  After instance is up and running, we need to add port 80 to the instance’s security group inbound rules.  There should be at least two ports open: 22, and 80.

Now we can ssh into the instance and install Nginx, Node, and Supervisord.  Let’s start with Nginx.

   sudo add-apt-repository -y ppa:nginx/development
   sudo apt-get update
   sudo apt-get install -y nginx

Node.js

   sudo su 
   curl --silent --location https://deb.nodesource.com/setup_8.x | bash -
   apt-get update
   apt-get install nodejs –y
   /usr/bin/npm install -g npm
   exit

Supervisord

   sudo apt-get install -y supervisor
   sudo service supervisor start

Now let’s create a Node.js server application using Express and make it listen on port 3000.

cd /var/www/html
sudo mkdir node-server
sudo chown ubuntu: node-server
sudo chmod 770 node-web-server
sudo chmod g+s node-web-server
cd node-server
npm init -y
npm install express --save
cat > app.js << EOF1
 
var express = require('express');
var app = express();
 
app.get('/', function(req, res){
   res.send('Hello Express!');
});
app.listen(3000, function(){
   console.log('Server is listening on port 3000');
});
EOF1

Let’s make Supervisord “supervise” our app. Create the following file /etc/supervisor/conf.d/node-server.conf

[program:nodeserver]
command=/usr/bin/node /var/www/node-server/html/app.js
directory=/var/www/html/node-server
autostart=true
autorestart=true
startretries=3
user=ubuntu

After that reload configuration file.

supervisorctl reread
supervisorctl update

Let’s configure Nginx to listen on port 80 and proxy all requests to port 3000 by creating the following config file /etc/nginx/sites-available/nodeserver

server {
    listen 80;
    server_name node-server.com;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_http_version 1.1;
        proxy_pass http://127.0.0.1:3000;
    }

    access_log off;
    error_log  /var/log/nginx/node-server-error.log error;
}

Enable the site and reload Nginx.

sudo ln -s /etc/nginx/sites-available/nodeserver /etc/ngix/sites-enabled/nodeserver
sudo nginx -t
sudo service nginx reload

We should have our node application running and accessible via node-server.com In order to check that add to your hosts file line that points node-server.com to ip of the created AWS instance.

Resources used

Share this article

Posted

in

by

Tags: