Deploying a Koa.js Application to an AWS EC2 Ubuntu Instance

January 07, 2017

I am developing an application using Koa.js, a new web framework created by the team behind Express. In this step-by-step tutorial, I'll guide you through deploying a Koa.js application on an Amazon Web Services (AWS) Ubuntu server.

2017 01 07

Launching the Ubuntu Instance on AWS

First, launch an Ubuntu instance on AWS. You'll need to modify the security group settings.

Security Group Settings

If you don't make these changes, attempting to access the public domain in a browser will result in a "Connecting" state until it times out, rendering the site unreachable.

Site Unreachable

By default, the launch wizard only enables SSH.

SSH Only

Click the "Edit" button to add inbound rules for HTTP port 80 and HTTPS port 443.

Edit Inbound Rules

Installing Node.js

SSH into your instance and install Node.js according to the official documentation:

$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
$ sudo apt-get install -y nodejs

Setting Up Nginx as a Reverse Proxy Server

Next, install Nginx:

$ sudo apt-get update
$ sudo apt-get install nginx

Open the configuration file and make the following edits. Don't forget the semicolons:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/yourApp;

    location / {
        proxy_pass http://localhost: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;
    }
}

Save the file and restart the Nginx service:

$ sudo systemctl restart nginx

Deploying Your Application

Clone your Git repository into the /var/www/yourApp directory. You'll likely encounter a "Permission Denied" error, so change the ownership of the folder:

$ sudo chown -R ubuntu /var/www

Create a simple app.js to run your server:

var koa = require('koa');
var app = koa();

// logger
app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

// response
app.use(function *(){
  this.body = 'Hello World';
});

app.listen(3000);

Start the server:

$ node app.js

Open your browser and navigate to your public domain. You should see your Koa.js application running.

App Running

Done! Feel free to leave a comment below if you have any questions. :)


Profile picture

Victor Leung, who blog about business, technology and personal development. Happy to connect on LinkedIn