Balasubramani M

@balasubramanim

Deploy your Node.js app in production and use BitBucket to automate your deployment.

In this tutorial, we will be creating a sample Node.js server, pushing it to BitBucket and using PM2, we will automate our deployment in production.

BitBucket

Why BitBucket? Why not Git?

Bitbucket is a web-based version control repository hosting service owned by Atlassian, for source code and development projects that use either Mercurial or Git revision control systems. Bitbucket offers both commercial plans and free accounts. — Wiki.

The unique difference that comes to my mind when compared with Git is that we can have any numbers of private repositories but not in Git whereas we can only have one in the later. If you don’t want to share your code and make it confidential, you can go for BitBucket. If you don’t have an account yet, you can get one @ https://bitbucket.org/

Create a sample Node.js server

Express Generator

Let us use express-generator to install a sample Node.js server in seconds. To install express-generator as a global module. Open your terminal and issue the following command.

$ sudo npm install -g express-generator

Navigate to your required directory and execute the following command. This will install a sample app called my-app.

$ express — view=hbs my-app

Navigate to your application my-app.

$ cd my-app

Let’s install the modules required to run the application.

$ sudo npm install

Start the application using the following command.

$ sudo npm start

This will run the application by default in Port 3000. You can check your application at http://localhost:3000/ You will see the below screen here.

Express application welcome screen.

Upload your code in BitBucket

There are several steps to be followed during your initial setup. So, let’s start with creating an SSH key to authenticate to your BitBucket account from your local machine.

Totally, there are two types of authentication called SSH and HTTPS.

This is the one time process and we don’t want to use HTTPS option to authenticate because we need to provide our credentials everytime whenever we pull, push or commit from your machine.

SSH Authentication mechanism goes below.

  1. Generating a new SSH key.
  2. Add your SSH key to the ssh-agent
  3. Add the SSH key to your GitHub account

Step 1: Generating a new SSH key.

Open Terminal.

$ cd ~/.ssh/ #To navigate to your default SSH key location.

Paste the text below, substituting in your BitBucket email address.

$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

This creates a new ssh key, using the provided email as a label.

When you’re prompted to “Enter a file in which to save the key,” press Enter. This accepts the default file location.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]

At the prompt, press enter twice without entering any password as of now. That’s it, you have created your SSH key successfully called id_rsa.

Step 2: Add your SSH key to the ssh-agent

Start the ssh-agent in the background.

$ eval "$(ssh-agent -s)"

Add your SSH private key to the ssh-agent.

$ ssh-add -K ~/.ssh/id_rsa

Step 3: Adding a new SSH key to your GitHub account

Copy the SSH key to your clipboard.

$ pbcopy < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard

If you don’t have pbcopy, you can use any of your editors to open this file and copy its whole content. I use sublime and if you want to open the above file in a sublime editor, issue the following command.

$ subl ~/.ssh/id_rsa.pub 
# Either issue this or above command. Don't execute both.

Let’s go to our BitBucket account and paste the key. Navigate to your BitBucket account settings and click the SSH Keys. (Refer the image).

BitBucket Account Settings Page.

Click Add Key and give the label name as per your wish. Let me name it as MY SSH KEY. And in the key box, paste your copied key and click Add key.

That’s it. Now, you are authenticated to perform actions in your BitBucket account from your terminal. Let’s push our code and later deploy it in EC2.

Deploy your code in BitBucket.

First, let’s create a repository in BitBucket, where we going to push our code.

Go to create repository in your BitBucket account or click this URL to navigate to the repo creation page. It looks like below.

Enter your app name called my-app and click Create repository.

Note: Do not include README as of now. In an image, I have included README file.

You will be navigated to your repo source page. Click the clone button which is available at the top right corner. Refer image for info.

And copy the highlighted text alone as given in the image. Since we are going to refer this repo to our local app, git clone is not needed.

Create a file called .gitignore in your root directory to ignore unnecessary files to get uploaded in our BitBucket repo. Paste the below content and save the file. Refer the completed repository source code for more information about structure.

# See http://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
node_modules
# testing
coverage
# production
build
# misc
.DS_Store
.env
npm-debug.log

Now navigate to your app directory (cd /my-app) and execute the below commands one by one to link your local repo to your BitBucket repo and push your changes.

git init
git add --all
git commit -m "Initial Commit"
git remote add origin
git@bitbucket.org:Balasubramani/my-app.git
git pull origin master
git push -u origin master

Done! Your repository is now available in Bitbucket Server.

If you face any error like, Merge issues while issuing git pull origin master just type :q! and press enter to exit and discard the commit message. It is unnecessary at this stage.

Deploy your app in EC2

Amazon EC2

If you are aware of Amazon EC2 instance and know how to configure and work on it, you don’t need to do anything.

However, if you aren’t aware of it, you can go through the below link and set up your remote instance ready which is required to host your Node.js server.

Note: You need a server(EC2 instance) to deploy your production ready Node.js server.

PM2 Setup

Advanced process manager for production Node.js applications.

Let us configure PM2 in our local repository which will actually do our deployment works.

Issue the following command to install PM2 in your root directory.

$ sudo npm i pm2 --save-dev

In your root directory, create a file called ecosystem.config.js and add the below content to it.

module.exports = {
apps: [
{
name: "my-app",
script: "./bin/www",
env: {
PORT: 3000,
NODE_ENV: "production"
}
}
],
deploy: {
production: {
user: "ubuntu",
host: "ec2-xx-xxx-xxx-xx.us-east-2.compute.amazonaws.com",
key: "~/.ssh/AWS-EC2-INSTANCE-LIVE.pem",
ref: "origin/master",
repo: "git@bitbucket.org:Balasubramani/my-app.git",
path: "/home/ubuntu/my-app",
"post-deploy":
"npm install && pm2 startOrRestart ecosystem.config.js"
}
}
};

Remember to replace your host with your Amazon instance host, the PEM key location and update your repo link (Which you have copied earlier — the highlighted text. Hope you remember).

Everything is ready to get deployed. So shall we start?

Of course. Run the below command in your terminal from your root directory to set up the application on your remote server.

$ sudo pm2 deploy ecosystem.config.js production setup

This will configure our application in the EC2 instance.

Finally, issue the below command to host and run your application using PM2 on your remote server.

$ sudo pm2 deploy ecosystem.config.js production

Hurray!!! Your Node.js server is now in your production server and ready to use.

Log in to your remote server and type

$ sudo pm2 status

to check your application status.

Now your application is running on your remote server. To check, add 3000 as a port along with your remote IP address to check the application running…

Eg: http://<your_remote_ip_address>:3000

Note: You need to allow port 3000 in security groups in your EC2 instance. Refer the above link on how to allow port in security group on your remote server.

You can download the final GitHub application here.

Let us map our custom domain, configure Nginx and add SSL layer to our Node.js server in the next tutorial.

Thank you.

More by Balasubramani M

Topics of interest

More Related Stories