Setting up Node on Amazon EC2

There’s a lot of articles out there about setting up Node on Amazon EC2 – the one I found most useful was probably this one: http://iconof.com/blog/how-to-install-setup-node-js-on-amazon-aws-ec2-complete-guide/
Having gone through this process twice, here’s my quick steps on how to setup the git structure, setup port forwarding, and setup a post-update hook for git.

Git Structure on EC2

The following actions will create a bare git repository and then clone that repository in a different directory.

mkdir example.git
cd example.git
git init --bare
cd ~
git clone example.git
cd ~
mkdir logs
cd logs
mkdir example

Once this is completed you’ll have two directories in your root:

  • ~/example.git – which contains the bare git repository
  • ~/example – which contains all of the files

Port Forwarding

The first step is getting rid of any settings that existed previously for port forwarding:

iptables --table nat --flush
iptables --flush

The second step is creating the port forward. The following assumes your node server is listening on port 3000 and will allow users to hit the server using HTTP port 80:

iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to 3000

Git Post-Update Hook

I setup the following under ~/example.git/hooks/post-update to:

  1. git pull the latest code into the clone
  2. Run npm install to make sure all of the project dependencies are installed
  3. Stop forever for that app, and then restart it
#!/bin/bash
echo POST_RECEIVE HOOK
cd ~/example
git pull
npm install
~/example/node_modules/forever/bin/forever stop ~/example/server.js
~/example/node_modules/forever/bin/forever \
     start \
     --append \
     -l ~/logs/example/forever.log \
     -o ~/logs/example/out.log \
     -e ~/logs/example/err.log \
     ~/example/server.js
Posted in Code Snippets Tagged with: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*