Skip to content

Instantly share code, notes, and snippets.

@alectrocute
Last active May 6, 2024 07:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alectrocute/8c7e16d3718ccc9373313959fa9d22c2 to your computer and use it in GitHub Desktop.
Save alectrocute/8c7e16d3718ccc9373313959fa9d22c2 to your computer and use it in GitHub Desktop.
Quick n' easy NGINX & Node.js VPS setup!

Quick n' easy NGINX & Node.js VPS setup!

N|SolidN|Solid N|Solid

Here's the quickest and easiest guide to setting up a little test enviorment. This guide likely applies to any VPS provider or VPS, not just Linode... it's just what I prefer to use. Assuming you know the basics of Linode's VPS system and SSH commands, let's get started!

Configure your Linode

  • Install your favorite flavor of Linux. I prefer Ubuntu.
  • Boot up the VPS.
  • Open up Terminal (if you're on MacOS). Alternatively you can use PuTTY.
  • SSH into the VPS.
ssh root@[linode ip]

Install NGINX

Nothing's better than a fresh install of NGINX. Coming from Apache2, there's nothing better to me than the slim, barebones nature of NGINX.

  • Grab a copy via apt-get.
sudo apt-get install nginx
  • Install screen, a handy SSH multitasking tool that'll be required for Node.
sudo apt-get install screen
  • Start up that NGINX server!
service nginx start

You should see the NGINX default index.html when you visit your Linode's IP.

It's time to start editing files. I prefer to use an SFTP client on my VPS so I can edit in the Brackets code editor, but you can alternatively use nano if you don't want to or can't install extra software.

Configure NGINX

So go into /etc/nginx/sites-available/ and edit the file example.com. Yeah, I know your site's not named example.com (if it was, I'd be surprised, since that domain must cost a fortune). You can either change the filename and reflect the change in nginx.conf or just leave it as is. I typically don't change the name.

If you're using nano, as I mentioned before, use this command:

nano /etc/nginx/sites-available/example.com

Remember, with nano, the command CMD + X is used to save your file. And then I believe you hit enter to confirm changes. Otherwise your file won't be saved!

Here's my typical example.com config file to get you started. You can probably just copy-paste it in there and it'll work. Just make sure your root is set to the folder of your web directory (typically /var/www/html or /var/www/.

server {
         listen       80;
         server_name  localhost;
         location / {
                root   /var/www/html;
                index  index.html index.htm index.js index;
        }
         location ~* \.(js)$ {
         proxy_pass http://localhost:3000;
         proxy_set_header Host $host;
        }
}

Alternatively, if you are extremely OCD and hate the sites enabled / sites available folders, and want all your config for NGINX entirely in one single file, you can delete both those folders and paste this in your nginx.conf file:

worker_processes  1;
events {
worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
         listen       80;
         server_name  localhost;
         location / {
            root   /var/www/html;
            index  index.html index.htm index.js index;
        }
    location ~* \.(js)$ {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
    }
    }
}

Yeah, don't tell an NGINX purist that you just did that. But I do it so I can configure everything in one single fell swoop. Moving on...

Install Node.js

Update your package manager with sudo apt-get update since it's probably super outdated. And you don't want to grab some old, moldy packages. It's a great way to waste time if you accidentally install something outdated and incompatible.

Grab a copy of Node.js and its little buddy, npm (Node package manager):

sudo apt-get install nodejs npm

Once that's all complete, it's time to start up your dedicated Node.js server! And it's surprisingly easy...

Create your server.js file

Go into your root html directly, in this guide's example, it's /var/www/html/. Create a file named server.js. In it, paste in the following:

var http = require("http"),                                     //Import Node.js modules
    url = require("url"),
    path = require("path"),
    fs = require('fs')
http.createServer(function(request, response) {                 //Create server
var name = url.parse(request.url).pathname;                     //Parse URL
var filename = path.join(process.cwd(), name);                  //Create filename
fs.readFile(filename, "binary", function(err, file) {           //Read file
    if(err) {                                                   //Tracking Errors
    response.writeHead(500, {"Content-Type": "text/plain"});
    response.write(err + "\n");
    response.end();
    return; }
    response.writeHead(200);                                    //Header request response
    response.write(file, "binary");                             //Sends body response
    response.end();                                             //Signals to server that
});                                                             //header and body sent
}).listen(3000);                                                //Listening port
console.log("Server is listening on port 3000.")                //Terminal output

Then go back to your Terminal, or PuTTY, or whatever SSH client you're using and launch your server.js file with Node.js!

Launch your server.js file

This is where screen comes in handy. Make sure you're in the /var/www/html folder or type cd /var/www/html/ to be sure. Launch the command: screen.

And then node server.js.

If all goes well, you should see the console.log read:

Server is listening on port 3000.

To exit screen, remember, it's CTRL+A and then the D key! It'll become second nature to you soon, just like CTRL+X+Y+ENTER for nano. Yay for high-speed finger macros.

Add a test Javascript file.

In your website's index, /var/www/html, create the file index.js.

Paste in the following test file:

<!DOCTYPE html>
<html>
<body>
<center>
<h2>
If this displays as an HTML page, your Node server is working!
</h2>
</center>
<center>
<button type="button"
onclick="document.getElementById('sample').innerHTML = Date()">
Test server-side script
</button>
<p id="sample"></p>
</center>
</body>
</html>

Save that file and go back to your SSH.

Restart your NGINX server

For all these changes to take place, it's likely a wise idea to restart your NGINX server. Use the command service nginx restart.

Make sure it all works

If you have my luck, then nothing will work and your VPS server far across the country, is likely on fire right now, causing panic to the five I.T. engineers that are on that shift.

But if it all goes right, your web browser should resolve to your domain and display your .js page as HTML using server-side Javascript! Now go on, create. Check out Angular, Ionic, etc. It's never been easier to create an incredible webapp or service; if you're willing to learn TypeScript...

Things to check out

The possibilities are endless with Node.js!

  • Angular - Cross-platform web/mobile framework
  • Ionic - A beautiful UI framework with Angular built in.
  • React - Facebook's framework. I haven't bothered to learn it, with the steep learning curve, but I've seen (and use daily) some great stuff powered by it.
  • Vue.js - Another popular framework.
  • Material Components for Web - Gorgeous UI resource.

Todos

  • Add more boilerplate resources.
  • Spell check.
  • Explain how to use npm.
  • "Hello World" Angular tutorial.
  • Show to to analyze different processes and keep-alive.

License


Copy and paste this on a website where you hide it behind a $5 paywall. See if I care.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment