Deploying a Node App to Digital Ocean

By Chimezie Enyinnaya

There are various platforms that help with deploying NodeJS apps to production. Zeit Now is one such platform.

While those platforms can help, in this tutorial, we’ll be looking at how to deploy a NodeJS app to Digital Ocean. Digital Ocean compared to these other platforms is cheaper and you also can logon to your server and configure it however you like.

You get more control over your deployment and also it’s a great experiment to see exactly how Node apps are deployed to production.

Prerequisites

This tutorial assumes the following:

What We’ll Be Deploying

Let’s quickly build a sample app that we’ll use for the purpose of this tutorial. It going to be pretty simple app.

// create a new directory
mkdir sample-nodejs-app

// change to new directory
cd sample-nodejs-app

// Initialize npm
npm init -y

// install express
npm install express

// create an index.js file
touch index.js

Open index.js and paste the code below into it:

// index.js

const express = require('express')
const app = express()

app.get('/', (req, res) => {
    res.send('Hey, I'm a Node.js app!')
})

app.listen(3000, () => {
    console.log('Server is up on 3000')
})

You can start the app with:

node index.js

And access it on http://localhost:3000. You should get Hey, I’m a Node.js app! outputted. The complete code is available on GitHub.

Now let’s take this our awesome app to production.

Create a Droplet

Login to your Digital Ocean account and create a new droplet (server). We’ll be going to with One-click apps. Select NodeJS as shown below:

Next, we’ll choose the $10 plan. Though the task list app will work perfectly on the $5 plan, but we won’t be able to install the NPM dependencies because the NPM requires at least 1GB RAM for installing dependencies. Though there is a way around this by creating swap memory which is beyond the scope of this tutorial.

Next, select a datacenter region, we’ll go with the default:

Next, add a new SSH key or choose from existing ones that you have added. You can get your SSH key by running the command below on your local computer:

cat ~/.ssh/id_rsa.pub

The command above will print your SSH key on the terminal, which you can then copy and paste in the SSH Key Content field. Also, give your SSH key a name.

Finally, choose a hostname for the droplet and click the Create button.

After some couple of seconds, you’ll have your new server up and running on Ubuntu 16.04 and NodeJS version 6.11.2. Note the IP address of the server as we’ll be using it to access the server.

Create Non-root User

Before we start configuring the server for the task app, let’s quickly create a non-root user which we’ll use henceforth for the rest of the tutorial.

Tip: As a security measure, it is recommended to carry out tasks on your server as a non-root user with administrative privileges.

First, we need to login to the server as root. We can do that using the server’s IP address:

ssh root@SERVER_IP_ADDRESS

Once we are logged in to the server, we can move on to create a new user:

adduser mezie

This will create a new user called mezie, you can name the user whatever you like. You will be asked a few questions, starting with the account password.

Having created the new user, we need to give it administrative privileges. That is, the user will be able to carry out administrative tasks by using sudo command.

usermod -aG sudo mezie

The command above adds the user mezie to sudo group.

Now the user can run commands with superuser privileges.

Setup SSH Key For The New User

You need to copy your public key to your new server. Enter the command below on your local computer:

cat ~/.ssh/id_rsa.pub

This will print your SSH key to the terminal, which you can then copy.

For the new user to login to the server with SSH key, we must add the public key to a special file in the user’s home directory.

Still logged in as root on the server, enter the following command:

su - mezie

This will temporarily switch to the new user. Now you’ll be in your new user’s home directory.

Next, we need to create a new directory called .ssh and restrict its permission:

mkdir ~/.ssh
chmod 700 ~/.ssh

Next, within the .ssh directory, create a new file called authorized_keys:

touch ~/.ssh/authorized_keys

Next, open the file with vim:

vim ~/.ssh/authorized_keys

Next, paste your public key (copied above) into the file. To save the file, hit esc to stop editing, then :wq and press ENTER.

Next, restrict the permissions of the authorized_keys file with this command:

chmod 600 ~/.ssh/authorized_keys

Type the command below to return to the root user:

exit

Now your public key is installed, and you can use SSH keys to log in as your user.

To make sure you can login as the new user with SSH. Enter the command below in a new terminal on your local computer:

ssh mezie@SERVER_IP_ADDRESS

If all went well, you’ll be logged in to the server as the new user with SSH.

The rest of the tutorial assumes you are logged in to the server with the new user created (mezie in my case).

Clone The App on The Server

We are going to clone the app unto the server directly in the user’s home directory (that is, /home/mezie in my case):

git clone https://github.com/ammezie/sample-nodejs-app.git

Next, we install the dependencies:

cd sample-nodejs-app
npm install

Once the dependencies are installed we can test the app to make sure everything is working as expected. We’ll do so with:

node index.js

The app is listening on port 3000 and can be accessed at http://localhost:3000. To test the app is actually working, open a new terminal (still on the server) and enter the command below:

curl http://localhost:3000

You should get an output as below:

Hey, I'm a Node.js app!

Good! The app is up and running fine. But whenever the app crashes we’ll need to manually start the app again which is not a recommended approach. So, we need a process manager to help us with starting the app and restarting it whenever it crashes. We’ll use PM2 for this.

Install PM2

We’ll install it globally through NPM:

sudo npm install -g pm2

With PM2 installed, we can start the app with it:

pm2 start index.js

Once the app is started you will get an output from PM2 indicating the app has started.

To launch PM2 on system startup or reboot, enter the command below:

pm2 startup systemd

You’ll get the following output:

[PM2] Init System found: systemd
[PM2] To setup the Startup Script, copy/paste the following command:
sudo env PATH=$PATH:/usr/local/bin /usr/local/lib/node_modules/pm2/bin/pm2 startup systemd -u mezie --hp /home/mezie

Copy and run the last command from the output above:

sudo env PATH=$PATH:/usr/local/bin /usr/local/lib/node_modules/pm2/bin/pm2 startup systemd -u mezie --hp /home/mezie

Now PM2 will start at boot up.

Install Nginx

Next, we’ll install Nginx as the webserver to be used for reverse proxy which will allow us to access the app directly with an IP address or domain instead of tacking port to the IP address. Eg. 102.123.83.29:5000.

sudo apt-get update
sudo apt-get install nginx

Because we chose One-click apps while creating our droplet, ufw firewall is setup for us and running. Now, we need to open firewall for only HTTP since we are not concerned with SSL in this tutorial:

sudo ufw allow 'Nginx HTTP'

Set Up Nginx as a Reverse Proxy Server

Finally, we set up Nginx as a reverse proxy server. To this, run:

sudo vim /etc/nginx/sites-available/default

Within the server block you should have an existing location / block. Replace the contents of that block with the following configuration:

// /etc/nginx/sites-available/default

...
location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:3000;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
}

Save and exit vim.

Test to make sure there are no syntax errors in the configuration by running:

sudo nginx -t

Then restart Nginx:

sudo systemctl restart nginx

Now you should be able to access the app with your IP_ADDRESS. You should get something similar to the image below:

Conclusion

In this tutorial, we have seen how to deploy a NodeJS app to Digital Ocean. We also saw how to setup a reverse proxy server with Nginx.

Source:: scotch.io

Run Node with Docker in 5 Minutes

By John Papa

Run Node with Docker in 5 Minutes

Heard of the latest and greatest thing? Of course. It’s everywhere. Been avoiding it? Ugh, maybe if we just pretend it doesn’t exist, this fad will disappear before we need to learn it.

Do you ever feel this way? I think it affects a lot of people in our technical community. What if the time investment was just a few minutes, you could learn the basics of the “new thing”, and have something running? Just a little taste of success to at least say we’ve tried it? Sometimes that is all it takes to get started.

Let’s give this a go with Docker and see if it can take us less than 5 minutes to find success.

Here is what we will do:

  1. Create your own basic web server
  2. Install Docker
  3. Build your own image
  4. Run it
  5. Browse to our web page

Create a Web Server

First, let’s create a simple node.js app with express that serves the canonical Hello World. Why? Because the world needs a little more kindness.

mkdir success  
cd success  
npm init -y  
npm i express --save  

Now we’ll open this success folder with the best editor ever created, VS Code. We’ll create a new file named index.js and paste in this code:

const express = require('express');  
const app = express();  
app.get('/', (req, res) => {  
  const msg = 'hello world';
  console.log(msg);
  res.send(msg);
});
app.listen(8626, () => console.log('Our server is running'));  

Now we can test our simple node.js app by running node index.js from a terminal. Be sure to say “Hello” back to the app!

Then we’ll cancel the web server with good ol’ CTRL-C.

Let’s Get Some Docker

Docker … what docker? There’s no docker here yet. We started with an app, and now we’ll go get us some docker.

Go to this link and choose your platform for docker. I’m using macOS, but you pick yours of course. Once it downloads, install docker and follow the prompts.

Build it and They Will Come

OK, that’s kind of a creepy statement from Field of Dreams. But still, an excellent movie. In this case, we’re going to build a docker image from our Dockerfile. Hold on a second … what Dockerfile?

The Dockerfile tells docker what to do, kinda like how google maps tells me how to get somewhere. Let’s create one of these Dockerfile thingies now. Create a new file named Dockerfile. Yep, that’s right, it starts with a capital D and has no file extension. What can I tell ya?

Paste the following commands into the Dockerfile and save it.

FROM node:6.11-alpine  
RUN mkdir -p /app  
WORKDIR /app  
COPY package.json .  
RUN npm install  
COPY index.js .  
EXPOSE 8626  
CMD [ "node", "index.js" ]  

Wanna know what we’re telling docker to do? Well, I’ll tell you anyway. We’re asking it to get an existing docker image off the web that has node 6.11 installed. Then we create a folder named app in that image, copy our package.json to it, install our express package, copy the node server index.js to the image, expose our port, and start the server.

Now we build our image by running the following command from the terminal. This executes the commands in the Dockerfile, builds the image, and tags it with the name johnpapa/success. Feel free to change your tag name, but hey, who doesn’t want a tag called “success”!

docker build -t johnpapa/success .  

Run Docker, Run!

The movie references just keep coming! OK, now we can crank up our server using the following command.

docker run -d -p 8626:8626 johnpapa/success  

We can browse to http://localhost:8626 and the browser is saying hello again. How nice of it!

The Point

The point of this post is not to explain all-things docker. We’re not learning why, which is a big deal frankly. Why is super important. For now, this is just a quick path to some success with docker on your local machine.

If interested, I’ll follow up with more posts or videos on how docker can be helpful and solve real problems we face in Web development. For now, enjoy your success!

Source:: johnpapa

Node.js Weekly Update - Oct. 6

By Tamas Kadlecsik

Node.js Weekly Update - Oct. 6

Below you can find RisingStack‘s collection of the most important Node.js updates, projects & tutorials from this week:

Node v6.11.4 (LTS)

Check out the latest LTS version of Node.js. Changelog:

Support passing undefined to listen() to match behavior in v4.x and v8.x

Node.js State of the Union 2017

Mark R. Hinkle, the executive director of the Node.js Foundation reflected on the current State of Node.js in his latest post. By any reasonable measure the state of Node.js is very strong, and it definitely has a good basis to facilitate further improvements:

Node.js Weekly Update - Oct. 6

Every week there are more than 3 billion downloads of npm packages. The number of Node.js contributors has grown from 1,100 contributors last year to more than 1,500 contributors today.

Trace becomes Keymetrics by October 31.

RisingStack partnered up with Keymetrics, the amazing team behind PM2, the de-facto process manager of the Node ecosystem and the incredible performance monitoring & management tool on top of it.

Node.js Weekly Update - Oct. 6

As of October 31, we’ll stop providing Trace as a SaaS service, as we’ll start to merge Trace with Keymetrics. You’ll still be able to continue on monitoring your Node.js apps with their excellent service.

Deploy a REST API using Serverless, Express and Node.js

The benefits of using Serverless to deploy web applications are huge.
Moving to Serverless has a relatively long learning curve, though.

In this post you’ll see how to how to use the popular Node web framework Express.js to deploy a Serverless REST API. This means you can use your existing code + the vast Express.js ecosystem while still getting all the benefits of Serverless!

Nest.js Brings TypeScript to Node.js and Express

As we saw in this article, creating applications with Nest.js is easy, flexible, and intuitive.

Nest.js is a framework for building Node.js web applications. What is special about it? It introduces building blocks that help developers to better organize Node.js applications.

A crash course on Serverless with Node.js

What makes Serverless so awesome? And what are the pain points? You’ll find it all out in this article. You’ll also see the main keywords and topics that are crucial in getting started with the technology.

Go ahead and jump right into some code and write your own Serverless functions, emulate the envirnoment locally and monitor performance! Brilliant!

Protect your npm account with two-factor authentication and read-only tokens

npm announced two new ways to protect your npm account. Read on to learn how you can use these security features to keep your code safe and increase everyone’s trust in the more than 550,000 packages of code in the npm Registry.

Create a RESTful API with Node.js, Hapi, and Couchbase NoSQL

Developing Node.js applications with Express is one of the most well-known option, however, it’s not by far the only one.

Check out how to how to create a very simple RESTful API with Hapi and Couchbase Server. The author Nic Raboy finds Hapi much better designed for creating web services. Why? Check it out in the article.

API Authentication With Node.js

Building APIs is important; the only think that is even more important is to create a a SECURED API.

How to build one? It’s all in this article.

Microsoft and Nearform announce alliance for node.js developer migration and support services on Azure

nearForm and Microsoft announced a new alliance at Node.js Interactive 2017, with the aim to help customers migrate Node.js apps to Azure, and provide enterprise-grade support for them.

Node.js Weekly Update - Oct. 6

An increasing number of Node.js developers chose to build and deploy on top of Azure daily, and Microsoft continues making investments to provide developers a great range of options to host their apps.

Previously in the Node.js Weekly Update

In the previous Node.js Weekly Update we collected the latest security issues in Node.js, the new Stackdriver Debugger for Node.js, how to write clean code for cascaded promises and reliable browser tests using Selenium and Node.js; learnt about debugging and the Node8’s util.promisify.

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

Survey: Want to learn Vue? We've got questions!

By Chris Sevilleja

Vue is a great JavaScript framework that we’ll be showcasing more in the coming months. We’re in the process of preparing that material and would love to hear feedback from you!

We’re going to be doing the following in the next month:

  • Many more Vue tutorials
  • Getting Started with Vue video course
  • A free Vue webinar

In putting together this info, we’d like to get some data on who is interested in Vue development. We’ve got some great content in the pipeline; this survey will help us adjust our delivery and who this is geared towards.

The Questions

Some questions that came to mind (feel free to sound off in the comments with your experiences):

What’s your previous JavaScript experience?

  • Are you a vanilla JS developer looking to use Vue?
  • Are you a jQuery developer?
  • Have you already used AngularJS v1 and want to try Vue?
  • Have you tried Angular v2+?
  • Are you a React developer?
  • Would you consider yourself a beginner/intermediate/advanced JS developer?

Why do you want to learn Vue?

  • Where’d you hear about Vue?
  • What are the main features you like most about Vue?
  • Are you going to use it for personal or work projects?

Conclusion

All of these questions will help guide how we create this content. Since Vue has such a low barrier to entry, it will attract more users coming from the vanilla JS and jQuery camps and this will definitely adjust our teaching strategy.

Let me know your experiences, what you’d like to learn, what you’d like to build, and what you’d like to see from Scotch!

Source:: scotch.io