IconOf.Com

KOSTAS MAVROPALIAS

LEAD DESIGN ARCHITECT and DEVELOPER at CCKF. CYBERPSYCHOLOGIST.

How to install & setup Node.js on Amazon EC2 – complete guide

in Development @ January 25, 2012

Confused about all these Amazon AWS products? Don’t know where to begin and how to start working with Node.js in the cloud? This step-by-step guide will help you setup a new Amazon AWS EC2 instance and install Node.js with NPM.

Update: you can speed up the Node.js setup process by using my Node.js Amazon CloudFormation template.

Table of contents:

  1. Create an Amazon Web Services (AWS) account
  2. Launch an EC2 instance (web server)
  3. Connect to Amazon EC2 with Putty
  4. Update your EC2 Amazon Linux
  5. Install Node.js and NPM on your Amazon EC2 instance
  6. Next steps

Create an Amazon Web Services (AWS) account

Create an Amazon Web Services (AWS) account (if you already have an Amazon.com account for shopping, you can use that).

Launch an EC2 instance (web server)

In order to install and run Node, we first need to have a web server. Amazon calls its web servers instances, because you can have many of them running in parallel. For now, you only need one instance.

Login with your AWS account and goto the EC2 tab in the AWS Management Console.

Before launching your web-server, Amazon gives you the option to choose a location. The cost varies between locations (although it’s free for the first year). US East (Virginia) and US West (Oregon) were the cheapest ones when this article was published. You can check the current prices for yourselves at Amazon.

After choosing a location, click the big “Launch Instance” button (an EC2 instance is similar to a regular unmanaged web-server).

In the new popup, give a name to your instance, type any name for the key pair file and download it (more on it later). Then choose an AMI (Amazon Machine Image). I suggest Amazon Linux 64 bit, which is loosely based on CentOS and is tuned for security and performance in the cloud. I chose 64bit due to some compatibility issues between the 32bit version and some versions of Node.

There are community Linux AMIs that you can use, which have Node and other software pre-installed, but if you go with a clean installation and setup everything yourself, you’ll learn how to administer and maintain it more easily (we’ll cover the basics in a while).

Finally, in the next screen just hit Launch.

Your instance is now launching and may take a few minutes. Click the View your instances on the Instances page link in the last page in the popup and you will be redirected to the following page:

You can now use your instance’s public dns to connect to your server via ssh. Amazon does not provide a custom username and password for ssh connections. Instead, they use the key pair file you created a couple of steps ago (a more secure practice).

Connect to Amazon EC2 with Putty

If you’re on Windows, you can use an ssh client like Putty:

  • Download Putty and puttygen
  • Use puttygen to convert Amazon’s .pem key pair file to .ppk file.
    • Start puttygen and select Load
    • Select view all files and pick the .pem file you download from Amazon.
      Putty will convert the .PEM format to .PPK format
    • Click OK and select Save Private Key A passphrase is not required but recommended for additional security.
  • Connect with Putty.
    • Launch Putty and enter your instance’s public dns address.
      Using putty to connect using ssh to Amazon EC2
    • Navigate to Connection/SSH/Auth. Click Browse and select the .ppk file you exported from puttygen.
      Choosing Amazon's EC2 ppk file in Putty
    • Finally, click Open. When the connection comes up for the first time, Putty will ask you if you want to save the server’s credentials; click Yes. In the login as prompt, type ec2-user and then your passphrase key for your key pair (if any). You are now logged-in into your instance!
      ssh login to you Amazon EC2 instance with Putty

Update your EC2 Amazon Linux

Security updates are automatically applied on the initial boot of the AMI. Upon login, the Message of the Day (/etc/motd) indicates whether or not any additional updates are available. To install them, just type:
Type y when prompted if this is ok and wait a few minutes for the updates to install.

Install Node.js and NPM on your Amazon EC2 instance

At last, it’s time to install Node.js on your Amazon Linux! We are going to install some required packages to compile Node and get Node from its Github repo. Type the following:

Now you need to decide which version of Node you want to install. If you are going to use a framework like Express 3.x, you need Node v0.6.x. Just modify the first command line to suit your needs. You can view all available Node tags (versions) by typing git tag -l. The make command will take a while to complete (30+ minutes), so go make a coffee and come back later.
Alright, Node is now installed! Let’s add it to sudo’s path so that we can install more packages. You will need to use the VI editor to edit the /etc/sudoers file. Type the following:

If you’re not familiar with VI, do the following:

The next step is to install NPM(Node package manager). Type the following commands:

Congratulations!

You now have a working Amazon EC2 instance with Node.js and NPM! You can install additional Node packages using NPM:

Next steps

If everything went according to plan, here are a few things that you should/could do:

  1. Save your customised Amazon EC2 instance as an Amazon Machine Image (AMI) and launch future environments with this saved configuration.
  2. Read some tips on securing your EC2 instance.

Conclusion

I hope this guide was useful. If you have any comments, suggestions or additional tips that could be added to the guide, please let me know in the comment section below.

  • http://www.facebook.com/christianstrang Christian Strang

    Really great article and perfect timing! 
    I have almost no idea about servers and installing stuff etc. A few hours ago I didn’t even know how to switch between directories or how to connect to a server. That said, your tutorial was simply amazing, no knowledge-barriers! My EC2 Server is up and running, already created an image.

    Just wanted to let you know, I really appreciated this article!

  • http://www.facebook.com/people/Allan-Lund-Hansen/622661021 Allan Lund Hansen

    Thank you for a great article explained so you can understand it and so it works up to date with everything

  • Fadi Samara

    thanks for this helpful!

  • Ghagg

    Thank you, this was what i needed just in time.. Saved me so much time. very well written. :)

  • Nikkio101

    Hey, you documented my exact setup process for node and AWS.  Thanks for the handy reference!

  • moser

    This is a *very* nice article, well focused, doesn’t assume knowledge or tools — very well written. Thank you!  One minor thing.  I had trouble with the sudo make install for npm.  so I had to use sudo env PATH=$HOME/local/node/bin:$PATH make install

    • http://twitter.com/vijaymadas Vijay

      I had this problem too and realised that I had made a mistake editing the /etc/sudoers file I had accidently typed in 
      :usr/local/bin instead of 
      :/usr/local/bin  notice the missing leading slash.

  • Ronindearborn

    This is a GREAT guide, but I ran into a what looks like permissions error. See https://forums.aws.amazon.com/thread.jspa?threadID=87938

    • http://www.iconof.com Kostas M

      I’m glad you liked it :)

      In your post at Amazon’s forum, you mention “In the above article, you are told to edit the sudoers, which is the last time I can remember sudo working.”. I believe you forgot to type ‘exit’ after editing the sudoers file, to leave ‘su’ mode.

      Maybe it’s not very clear in my guide. It’s the last line in the code block on how to edit the file using VI. If you stay in su mode, then sudo will not work. I hope this solves your problem!

  • Dominic Claxton

    For anyone having a problem connecting to Amazon Web Services (AWS) from a Windows 7 PC.
     I kept getting a ‘No network connection’ and then a time out.I noticed on initial install of my AWS EC2 instance that the SSH security group did not have SSH included. I added this by going to Network Groups (Under NETWORK & SECURITY on the left) and then clicking on my default group and adding a new rule under the Inbound settings on port 22.I realise this is specific to my problem but I went back to Putty and still no luck.I then re-ran the key creation, this time omitting creating a pass-phrase in puttygen. I tried connecting again and it worked.

    • Dominic claxton

      Just wanted to add that the rest of your post was spot on – thanks!

  • http://getitdoneapp.com Mike

    seems like there is an issue with “sudo make install” for npm step I get the error:

    scripts/doc-build.sh doc/api/unpublish.md man/man3/unpublish.3
    make[1]: Entering directory `/home/ec2-user/npm’
    node cli.js install https://github.com/isaacs/ronnjs/tarball/master
    bash: node: command not found
    make[1]: *** [node_modules/.bin/ronn] Error 127
    make[1]: Leaving directory `/home/ec2-user/npm’
    make: *** [man/man3/unpublish.3] Error 2

    • Alex

      you get npm when you install node now so you can skip this step

  • http://getitdoneapp.com Mike

    I think if you change the node .configure to ./configure –prefix=/usr then it works as intended

    • Trevor

      That fixed the issue below for me exactly!

    • http://www.facebook.com/madealive Ben Martin

      I encountered the same issue with node command not found, and this solution fixed it.

  • Timo

    wonderful, working like a charm …

  • zhendalf

    Thank you a lot! This guide was really helpful.
    I have started my node.js app and it works fine until I close Putty. What should I do to keep my app running?

    • http://www.iconof.com Kostas M

      You need to use “screen”. It’s a tool that lets you run tasks in the background, even after you logout. It is like a window manager for the shell. Have a look at this tutorial: 
      http://www.rackaid.com/resources/linux-screen-tutorial-and-how-to/

      • zhendalf

        And thank you again! It’s exactly what I needed.

  • Pingback: Node.JS Up And Running In The Cloud – on Amazon EC2 | Node.JS, Flash, and Flex Consultant – Kit Phelps

  • fany

    wow great article :) thanks for that!

    Nevertheless I have some questions:
    If I would like to add a 2nd instance of the same type
    do I have to repeat the install steps for node.js again?

    How do multiple instances appear to node.js when
    I use the cluster packet of node? Since there
    are multiple CPUs (after adding additional instances)
    does the node.js cluster module recognize the additional
    number of CPUs?

    Thanks :)

    • http://www.iconof.com Kostas M

      Thanks for the comment :)

      You don’t have to repeat the install process when you want to add more instances. After you finish setting-up the first instance and launch it, you can right-click on it and select the “Create image (EBS AMI” option. This will save your instance permanently as an image. Then, you can navigate to Images > AMIs from the left hand side menu, where you will see your image. Now you can right-click on it and choose launch instance. This way, you can launch as many instances (even of different size) as you like.

      Node’s cluster module allows you to utilize multi-core cpus on a _single_ instance. So launching multiple instances will not help you in that regard. What you need is, after you create your EBS AMI image, to launch a ‘large’ or ‘extra large’ instance with that image that will provide you with dual and quad core capabilities, respectively.

      • fany

        thanks for the reply; very much appreciated!

        To wrap things up a bit:
        If I have, lets say 2 extra large instances (one created manually and the
        second generated from your AMI option advice from above) running with node.js and the cluster
        module to utilize all cores of each instance how do I balance the load between
        these two instances?

        Normally I would use e.g. the nginx load balancing feature for that… Is this necessary
        (or even possible?) on the Amazon infrastructure or do they take responsibility to handle
        the load and use the instances in respect to their current load?

        I mean all incoming traffic to a site will be going through the
        same port at first and then must be spread to each instance, true?

        Thanks again :)

        • http://www.iconof.com Kostas M

          Yeah, you got the idea. In order to load-balance two or more instances you need a single point of entry that will manage your traffic. There are various ways to do that. Amazon itself provides elastic load balancers that do this job: http://aws.amazon.com/elasticloadbalancing/ (you set your client app to connect to the load balancer, and then it decides which instance should handle the request). Amazon’s balancer will monitor the cpu load on each of your instances and redirect traffic to the one with the lowest use. Furthermore, you can set it up to automatically launch new instances from the same AMI image, when all of your running instances are at full capacity.

          Another solution is to build one yourself or use nginx (I don’t think that’s the ideal scenario) that can run in a separate instance.

          • fany

            Thanks for your detailed answers – thats an excellent page.

  • Pumpkin Eater

    I love you for posting this

  • Tim

    Awesome, great post, great time saver for us windows people.

  • عقارات الرياض

    really a great article which will help me in using node.js.thanks a lot for sharing.

  • http://www.facebook.com/madealive Ben Martin

    Brilliant article. I began building my web app in *AMP and a DV from Media Temple, but saw the need to change to NodeJS/MongoDB. This made me wonder whether a cloud host would be better suited, which I think it would.

    I do have a question for you. How would you recommend setting up multiple environments (as in staging, production, etc.) with EC2? I’m not sure if I need a new instance for each, or if it would be beneficial. Thanks!

    • http://www.iconof.com Kostas M

      Thanks Ben :)

      To answer your question, in my own Node project I use a micro EC2 instance for staging/testing, because it’s cheap and does the job. That instance runs both the Node server and Mongodb, as performance is not an issue at that point. For production, I host Node & Mongodb in two separate beefier instances with raid, automated backups, etc.

      Of course there are many ways you can arrange your setup, and it really depends on what works best for your project. You could always run everything on one machine, using different ports/ips but then you might run into various issues. Most of them boil down to versioning of your app’s components – from Nodejs and its modules, to the database and your code. E.g. you might run into scenarios where you want to update Node to a newer version but that can break your production code, while your dev code is not ready to be deployed yet. On top of that, you’ll have to duplicate everything, make selective backups, etc.

      I suppose you can make it work, but that can increase the complexity of your deployment and the time you spent managing it. Having separate instances, even micro ones, allows you to isolate your environments, manage them easier and identify potential issues more efficiently (e.g. some new dev code might introduce unusually high cpu usage or disk load, that can be tricky to identify if everything runs on one instance).

      If you want to launch new instances easily consider using CloudFormation, it will automate this process for you. I’ve posted a template for Node instances, here: http://iconof.com/blog/node-js-amazon-cloudformation-template/ .

      • http://www.facebook.com/madealive Ben Martin

        Thanks for the reply Kostas. I ended up passing on CloudFormation, as I thought it would be good to get the experience of setting up an instance myself. It was all quite simple. The most frustrating part was having to wait ~30 mins for NodeJS to make ;)

        I think for now, I’ll use a micro instance for the staging environment, and setup NodeJS and MongoDB each on a small instance (just to get started). I’m using Redis as a session store, and I’ll probably put it on its own micro instance or just stick it with MongoDB.

        Initially, I will just start small and see how I go when the app launches. It will handle file uploads, so I want to be mindful of not consuming all the disk space too quickly and minimizing the effect of the process of upgrading an instance on uploaded files. That being said, I think it will be a while before I need to consider load balancing between multiple instances, but if and when the time comes, I’m sure the transition should be fairly smooth.

        I do have two further questions: 1) Do you have any pointers on setting up automated backups? 2) Regarding system resources, how do you go about the process of monitoring?

        Thank you again. This article has been a very useful resource and has made an overwhelming task somewhat easier :)

  • Jeromy French

    Awesome detail. Thank you for taking the time to document for the rest of us.

  • Pingback: Configure Express + MongoDB + Nginx on AWS EC2 | Brandon's Writes

  • Colin

    Great post! This is exactly what I needed

  • Pratt

    Can you provide me a list of tools that provide images to migrate on amazon cloud(Ex: VM Import/Export)

  • Daniel Villarreal

    Awesome article. Thanks.

    I really do wish to add the Next Step to get up Node.js for being available online.

    I spent some good time figuring out to configure: ‘port’ and ‘host’ on my Node.js “server.js” file.

    you have to use any allowed port # ex. “1339″

    and for the ‘host’ : I had to introduce my EC2 local ip address. with curl http://169.254.169.254/latest/meta-data/local-ipv4

    then start from bash at the folder with my, server.js file: node server.js

    using EC2 public address: curl http://169.254.169.254/latest/meta-data/public-ipv4

    which return my ip. and then I go to http://my-public-EC2-ip:port/

    After that I configuration I was able to actually see my Node.js on the web!

    Now I have to find way to redirect to port 80!

    and start with Express.js

    Thanks!!

  • Richard Sands

    If you’re having trouble installing NPM, you may need to export NODE_PATH while sudoing:
    sudo PATH=/path/to/node/bin/dir:$PATH make install

    Note: I execute the git clone for npm from the node directory – so the npm folder was created in the node directory

    (http://stackoverflow.com/questions/7507720/error-installing-npm-for-node-js)

  • Richard Sands

    P.S. Thanks for a really helpful article – very clearly explained!

  • revillwebdesign

    This is an excellent article and very helpful. Thank you.

  • http://www.jeffbyrnes.net/ Jeff Byrnes

    As a heads-up, NPM will be installed as part of the Node installation (I know it was when I installed Node v0.10.5, the current stable).

    Additionally, /etc/sudoers should always be edited with visudo, like so:

    $ sudo visudo

  • http://twitter.com/Chris_M_Black Chris Black

    Thank you Kostas. Really clean write-up. Appreciated all the additional comments as well.

  • http://InnovationBound.com/Costa Costa Michailidis

    Thanks so much for this write up, it’s a huge help! Hmm… If you install node.js that way, how do you update it later? I’ve gotten used to using n or node version manager on my development machine. Sorry, I’m really new to server admin.

    • http://www.iconof.com Kostas M

      You just checkout a newer version (tag) and configure+make it, like so:

      $ cd to_where_you_did_the_initial_node_git_checkout
      $ git pull (pulls all new versions)
      $ git tag -l (shows you all versions)
      $ git checkout v0.10.5 (checkout the version of your choice)
      $ ./configure
      $ make
      $ sudo make install

      and you’re done :)

      • http://InnovationBound.com/Costa Costa Michailidis

        Got it. That means I’d have to take my app down while the update takes place?

  • Satyam Verma

    I installed npm by sudo env PATH=$HOME/local/node/bin:$PATH make install…after this while installing express when i typed sudo npm install express -g it show me :

    npm http GET https://registry.npmjs.org/express

    and gets stuck like this forever….Please help me out

  • Pingback: Installing NodeJS, MongoDB, and Mozilla Popcorn Maker 0.5.2 on Amazon Web Services | Innovation @ BBG

  • aaron chuidian

    Help, i get stuck on the final “sudo make install”. i get the following …..

    node cli.js install -g -f

    npm WARN using –force I sure hope you know what you are doing.

    npm WARN cannot run in wd npm@1.3.26 node bin/npm-cli.js prune –prefix=. –no-global && rm -rf test/*/*/node_modules && make -j32 doc (wd=.)

    npm ERR! addPlacedTarball Could not remove “/root/.npm/npm/1.3.26/package”

    npm ERR! addLocal Could not install .

    npm ERR! Error: UNKNOWN, unknown error ‘/root/.npm/npm/1.3.26/package’

    npm ERR! If you need help, you may report this *entire* log,

    npm ERR! including the npm and node versions, at:

    npm ERR!

    npm ERR! System Linux 3.4.73-64.112.amzn1.x86_64

    npm ERR! command “node” “/home/ec2-user/npm/cli.js” “install” “-g” “-f”

    npm ERR! cwd /home/ec2-user/npm

    npm ERR! node -v v0.6.8

    npm ERR! npm -v 1.3.26

    npm ERR! path /root/.npm/npm/1.3.26/package

    npm ERR! code UNKNOWN

    npm ERR! errno -1

    npm ERR!

    npm ERR! Additional logging details can be found in:

    npm ERR! /home/ec2-user/npm/npm-debug.log

    npm ERR! not ok code undefined

    npm ERR! not ok code -1

  • Jacob P

    If you are on a unibody Macbook Pro keyboard and can’t press “Insert” natively, just go to the Terminal.app preferences and add a custom key combination (e.g. shift-control-option-downarrow) and bind it to the code “33[2~”. That code is the keypress for Insert.

---