We'll start from the same Ubuntu VM running in EC2. Only a little bit of extra setup is required.
First, make sure you open a port for your web app (say, 8080): in the AWS console, go to the "Security group" section and add a custom rule opening port 8080/TCP. Don't forget to click on "Apply rules changes" ;) No need to restart your VM, the change is effective immediately.
Then, 'ssh' into to your VM and install the packages required by Node.js: the environment itself plus its package manager:
ubuntu@ip-10-48-45-182:~$ sudo apt-get install nodejs npm
Now, let's install the native MongoDB driver used by Node.js:
ubuntu@ip-10-48-45-182:~$ npm install mongodb
This generated errors on Ubuntu 12.04, but the package still got installed. YMMV.
All right, now to the good stuff. Here's our web server in Node.js:
- connect to our MongoDB instance (once again, make sure you use your own URI, username and password). Then, select 'collection1', containing 25 documents ({"_id", "x"})
- create a web server running on port 8080 and wait for incoming requests: they will be served by the onRequest function, which issues a global find() on the collection and prints out all documents. JSON.stringify() is a life-saving browser function, it should hopefully work everywhere. If not, use Chrome ;)
Everything will run asynchronously, which is pretty much the point of Node.js, but this is out of scope for today. I strongly recommend the Node Beginner website if you'd like to know more.
Pretty cool, yeah? Let's start this program on our VM:
ubuntu@ip-10-48-45-182:~$ node www.js
Web server started
Connected to database
Our web server is now running. Yes, really. Now, let's connect to our instance from another machine. I'll use 'curl' but your web browser will work too (feel free to actually try, my VM may be running):
$ curl http://ec2-54-216-192-183.eu-west-1.compute.amazonaws.com:8080/
ubuntu@ip-10-48-45-182:~$ node www.js
Web server started
Connected to database
Our web server is now running. Yes, really. Now, let's connect to our instance from another machine. I'll use 'curl' but your web browser will work too (feel free to actually try, my VM may be running):
$ curl http://ec2-54-216-192-183.eu-west-1.compute.amazonaws.com:8080/
And this, ladies and gentlemen, is a super scalable, state of the hype, cloud-based web application. Anybody wants to buy it for a billion dollars? :D
Until next time, read, learn and write some code!