A Node.JS Application on Amazon Cloud. Part 3: A simple Webserver in Javascript using Node, Express, and MongoDB
In this third part of our exercise, we’re going to use the primary AWS EC2 instance on which we installed Node in Part 1, and the database EC2 Instance we set up in Part 2, as the platform for building a simple web application server. We are going to code that web server in Javascript, using Node together with the Express and Mongoose Node library packages.
Installing the Node libraries we’ll need
Returning to your primary EC2 instance, open an SSH console and install the express and mongoose node packages on the node instance.
$ npm install mongoose $ npm install express
Coding our simple application
Now on your Mac, create a new javascript source code file app.js and follow these simple instructions to build your application.
First we need to load the node libraries we need in this example, namely node’s own http library plus the express and mongoose packages we already installed on our EC2 instance.
var http = require('http'); var mongoose = require('mongoose'); var express = require('express');
We need to define variables to represent our express application and our database.
var app = express(); var db;
Next we need to define the configuration of the other server instance hosting our database. replace the HOST in the following variable definition with your database instance’s public DNS.
var config = { "USER" : "", "PASS" : "", "HOST" : "ec2-xx-xx-xx-xx.ap-southeast-2.compute.amazonaws.com", "PORT" : "27017", "DATABASE" : "my_example" };
Then define the details for the database we will be connecting to on that instance.
var dbPath = "mongodb://"+config.USER + ":"+ config.PASS + "@"+ config.HOST + ":"+ config.PORT + "/"+ config.DATABASE; var standardGreeting = 'Hello World!';
Now lets create something to store in our Db, and that is going to simply be Dennis Ritchie’s old faithful “Hello World!” greeting. Using mongoose we need to create a schema and a model using that schema.
var greetingSchema = mongoose.Schema({ sentence: String }); var Greeting= mongoose.model('Greeting', greetingSchema);
Our first action on startup is to connect to our Mongo database hosted on the other server
db = mongoose.connect(dbPath);
In the connection successful event handler, check if the database already contains a greeting. if not, create one and save it to the database.
mongoose.connection.once('open', function() { var greeting; Greeting.find( function(err, greetings){ if( !greetings ){ greeting = new Greeting({ sentence: standardGreeting }); greeting.save(); } }); });
Now set up the Express routes to handle incoming requests. First, respond to requests to our domain by extracting or greeting from the Db and sending it as the response
app.get('/', function(req, res){ Greeting.findOne(function (err, greeting) { res.send(greeting.sentence); }); });
Set up an Express route to handle any errors
app.use(function(err, req, res, next){ if (req.xhr) { res.send(500, 'Something went wrong!'); } else { next(err); } });
Finally, you need t0 start the Express Webserver:
console.log('starting the Express (NodeJS) Web server'); app.listen(8080); console.log('Webserver is listening on port 8080');
Save your source file, and exit the editor.
Deploy our application to AWS using Git
First, check your git profile is configured properly on your local machine like this
git config --list
If not, you’ll need to install git using macports or whatever package manager you use.
Once git is properly installed, execute
git init
to create a new local git repository in your application folder. This creates the .git directory in your project directory ready for Git to use for staging and indexing your files.
Create an account on github if you haven’t got one already, and link your local git repository to the (still empty) remote repository on your github account
git remote add origin https://github.com/username/path/to/repository
where username is the user name associated with your github account, and path/to/repository is the pathname you want to use for this project repository, e.g. simply “my_webserver”
From now on, on your local machine you can simply push changes to the remote github server using the remote repo’s nickname ‘origin’.
Sync the local and remote repositories:
git add * git commit -m "first commit"
Finally, push all your project files up to the remote repository you’ve named “origin”:
git push origin master
You’re done – The local and remote repositories are now in sync.
Finally, to deploy the code to your AWS production server, SSH into your AWS EC2 instance again, and execute
git clone https://github.com:/username/path/to/repository
then you can use git pull on the server whenever you want to get the latest version from the github repository.
git pull
Now let’s try out our application
On you EC2 instance, start the application
> node app.js starting the Express (NodeJS) Web server Webserver is listening on port 8080
and verify that it started successfully.
Then on your Mac, open a browser and request a page from your webserver application on your EC2 instance by typing in the instance’s IP address and port.
you should see the message “Hello World!” appear in the browser window.
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.
Further reading
You can download the full example code, including error handling and logging to the console for monitoring the connection process, from http://github.com/fatkahawai/node-remote_mongo-example.git
- NodeJS.org The official Node site
- MongoDB The Mongo Database
- Express The useful Express Javascript webserver framework for Node
- Mongoose The Mongoose Javascript library for simple access to a MongoDB
This was a brilliant 3 part series! I was struggling to get a grasp of AWS and needed a step by step guide. This was incredibly useful. Thanks Bob!
Glad you enjoyed it Imran
Thank you for simple and concise instructions. Rare these days …:)
yeah. Mark Twain said it best: I didn’t have time to write you a short letter, so I wrote a long one instead.’
Hey, great tutorial. The mongodb connection URI should probably be in a secure .env file with any other configure variables. Could you give any insight on how to do this? Also, you could use forever to make sure the node process is always running. If you ever feel like making a part 4 then a good topic would be making the deployment production ready including the things above.
Hey there, I think your site might be having browser
compatibility issues. When I look at your blog site in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping.
I just wanted to give you a quick heads up! Other then that, very good blog!
What happens when you log out of your shell session?
run your webserver as a background process and logging out of SSH won’t affect it.
excellent tutorial content and explanation