Thursday, July 8, 2021

AWS : NodeJS : Hello World on EC2

 Although I have an account in AWS for over a decade, I really did not do much with it other than launching a EC2 instance and then say print Hello World.

A decade has passed and now AWS has caught up with me professionally so need to build come competencies around it.

First is to get the the Hello world back again using Node on a Web Page.

Assumptions:

  1. You have a AWS account. I am using the free tier one.
  2. Have basic understanding of Node
  3. Have basic understanding of AWS specially EC2, VPC and ACLs.

Steps:
  1. Go to EC2. Select "Amazon Linux 2 AMI (HVM), SSD Volume Type" of type "t2.micro" and launch it. 

  2. You will get a public key .pem file. Keep it safely.

  3. On Windows, you will need to set the permissions of the file correctly to mimic chmod 400 of linux:
    1. icacls.exe key.pem /reset
    2. icacls.exe key.pem /grant:r "$($env:username):(r)"
    3. icacls.exe key.pem /inheritance:r

  4. Go to Security Group and Edit Inbound rule to allow:
    1. SSH (port 22) from anywhere
    2. HTTP (port 3000) from anywhere

      This will allow you to connect to the EC2 instance from your local laptop as well as browse the Hello World node site in there.

  5. Coming back to EC2 dashboard, you should see 1 Instance running

  6. You should be able to connect to it using SSH client and see the welcome logo:
           __|  __|_  )
           __|  __|_  )
           _|  (     /   Amazon Linux 2 AMI
          ___|\___|___|
    https://aws.amazon.com/amazon-linux-2/

  7. Now that you have a shell access to your EC2 instance, lets install Node JS.

  8. We will use nvm for it.

  9. curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash

  10. Activate nvm using simply bash or . ~/.nvm/nvm.sh

  11. nvm install node

  12. check node installed:
    node -v
    v16.4.2

  13. Now let just start a simple Express web app
    mkdir myapp
    cd myapp
    npm init (and just enter till the end)
    npm install express --save
    vi app.js
    const express = require('express')
    const app = express()
    const port = 3000

    app.get('/', (req, res) => {
      res.send('Hello World!')
    })

    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`)
     
    })
  14. node app.js
    Example app listening at http://localhost:3000
  15. So our web app is up are running on 3000 but its still within the EC2 instance. To be able to access it from the internet, we need to modify the security group of the EC2 instance to allow the port 3000 be exposed. This has been done in Step 2.

  16. So access the web app using the public IP or hostname of the EC2 instance. Note to use http:// and not https:// and append the port 3000 at the end. It should show up as :

    Hello World!
Thats all for today. Next we will connect the mighty Database :)