Introduction
Node.js is a open source, cross-platform runtime environment built on Google’s open source V8 JavaScript Engine for server-side and networking applications. Node.js is lightweight and efficient by using a event-driven, non-blocking I/O model. Applications written with Node.js can be run at the command line or with built-in libraries allow it to act as a web server without software such as Apache or IIS as well. It runs on Linux, OS X, FreeBSD and Windows.
This tutorial will cover setting up a production-ready simple web application in Node.js using Express framework and Nginx web server as a reverse proxy that also can handle caching. With „pm2“ we will keep the application alive.
We do that all on a Ubuntu 14.04 Dev Box using „CodeAnywhere.com“ as our working environment.
You can use this same tutorial on any other hoster with Ubuntu as well. For other Linux distributions, the setup may vary when it comes down to how to install prebundeled software packages.
Our main software bundles
- Express – An flexible and minimalistic web framework for Node.js that deals with routing and templating to provide a robust set of features for web and mobile applications
- pm2 – A production process manager for Node.js applications that ensures your application stays alive forever with a built-in load balancer
- nginx – A HTTP and reverse proxy server for serving static files, load balancing, and caching. It puts its focus on high concurrency, performance and low memory usage.
How it works
Client requests to a page of our application will be passed by Nginx to Express. Express returns this page to Nginx, which then is sent back to the client.
pm2 is used to monitor our Express application to ensure that it is running, and restarts it if stopped.
Node.js
The Express framework is built on Node.js, therefore we must first install Node.
Ubuntu 14.04 comes with a node.js 0.10 (due to name conflicts it is called „nodejs“ on the package management). You can either install this version using the package manager with „apt-get install nodejs“ or follow the steps to install the newer version of nodeversion 0.12.
This instructions are according to „nodesource.com„.
$ sudo apt-get update
$ sudo apt-get install -y build-essential openssl libssl-dev pkg-config
#Note the new setup script name for Node.js v0.12
$ curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash -
# Then install with:
$ sudo apt-get install -y nodejs
Create „Hello World“ Node.js Application
To test the Node.js is properly working, we will create a Hello World application that simply returns „Hello World“ to any HTTP requests.
We will use vi
to edit our sample application called hello.js
:
$ vi hello.js
Insert the following code block into the file:
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(8080, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8080/');
Save the file and exit.
This sample Node.js application will only listen on the specified IP address and port (127.0.0.1:8080). When requested, it returns „Hello World“ with a proper 200 HTTP status code. This means that our application is only able to be accessed from the same server locally – from localhost only.
Test your application
node hello.js
Running a Node.js application this way will block additional commands until you kill it by pressing CTRL+C.
To test the application, open another terminal session and request it with:
$ curl http://127.0.0.1:8080
If you can see the output „Hello World“, the application (and Node.js) is working properly.
Be sure to kill the application (in your other terminal session) by pressing CTRL+C if you haven’t already.
Install pm2
We install pm2, which is a process manager for Node.js applications. With pm2 we can easily run our applications as a service.
To install execute following:
$ sudo npm install pm2 -g
To start our application hello.js
in the background, we use the command pm2 start
:
$ pm2 start hello.js
This will add our application to the pm2 process list and outputs a short overview of the process‘ details.
The application is now running and you can test it again with curl:
$ curl http://127.0.0.1:8080
Reboots
As long pm2 runs, our applications will run as well. To have pm2 start automatically after a server reboot pm2 offers a subcommand which generates and configures a startup script to launch pm2 on server boots. We specify which platform we are running on, in this case Ubuntu:
$ sudo pm2 startup ubuntu
pm2 has a couple other commands to start
, stop
, restart
, monit
, … helpful to manage our applications as background services.
Install and setup Nginx as a reverse proxy server
Our application hello.js
is now running and listening on our private IP address. To make it available for users to access it from the browser, we will set up an nginx web server as a reverse proxy.
Install nginx using apt-get:
$ sudo apt-get update
$ sudo apt-get install -y nginx
Then we open the default server configuration file for editing:
$ sudo vi /etc/nginx/sites-available/default
Delete everything in that file and insert the following configuration. Dont forget to fill in your domain name where it says „example.com“
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Save the file and exit.
This will configure the webserver to respond to requests on port 80 at its URL root „/“. Accessing „http://example.com/
“ (substitute your own domain name) in a web browser would send the request to nginx which will proxy the request to our Node.js application locally on port 8080 and respond back to the user.
Restart nginx now:
$ sudo service nginx restart
You can now try to access your web servers URL in a web browser to test your application. Assuming that your Node.js is running and your nginx configurations are correct.
So far, so good. We now have a running Node.js application served with nginx as our reverse proxy server.
In the next steps, we will install Express – a Node.js application framework.
Installing Express – our application framework
Express provides us with a application generator tool, to quickly create an application skeleton.
You can install it with the command:
$ sudo npm install express-generator -g
Now we have installed it, and can use the command express [appname]
to generate a application skeleton.
$ express myapp
This will create an Express app in our current working directory.
$ express myapp create : myapp create : myapp/package.json create : myapp/app.js create : myapp/public create : myapp/public/javascripts create : myapp/public/images create : myapp/routes create : myapp/routes/index.js create : myapp/routes/users.js create : myapp/public/stylesheets create : myapp/public/stylesheets/style.css create : myapp/views create : myapp/views/index.jade create : myapp/views/layout.jade create : myapp/views/error.jade create : myapp/bin create : myapp/bin/www
Then install the dependencies and run your application:
$ cd myapp
$ sudo npm install
$ DEBUG=myapp:* ./bin/www
Testing your new Express application with curl and you should see a sample page with the text „Express / Welcome to Express“ on it. (You need a second terminal session again). Note: By default, the Express application uses a port 3000 – you can change that later if you like.
$ curl http://127.0.0.1:3000
Run it with pm2
To have this new application running as a service, like we did before, stop it now and start it again just this time we use pm2.
If you haven’t already, kill the application by pressing CTRL+C. Then use pm2 to start it in the background.
$ pm2 start ./bin/www
Setup Express with nginx
Like with the simply plain Node.js application hello.js, which we create earlier in this tutorial, also our new Express application isnt yet accessible by users in the web browser. We have to configure our new application in nginx to finish this last part.
We will replace our nginx server configuration file to server only for the new Express app. (just for simplicity)
Open the default server configuration file for editing again:
$ sudo vi /etc/nginx/sites-available/default
Delete everything in that file and insert the following configuration. Dont forget to fill in again your domain name where it says „example.com“
server {
listen 80 default_server;
server_name example.com;
# serving static files
location ~ ^/(assets/|images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) {
root /home/cabox/workspace/myapp/public/;
access_log off;
expires 24h;
}
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:3000/;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
}
Then restart nginx:
$ sudo service nginx restart
Now you should be able to access your Express application with your web browser via http://example.com/
. You should see the text „Express / Welcome to Express“ slightly styled with basic CSS.
Credits
Is used a few other tutorials to learn it myself and to combine them here.
Thanks to:
Nodesource.com, https://nodesource.com/blog/nodejs-v012…
Daniel Li, http://blog.danyll.com/setting-up-express…
Mitchell Anicas, https://www.digitalocean.com/community/tutor…