Creating a NodeJS Web Application from Scratch, AppVersion1 and AppVersion2

Short And Simple Building and Deploying Two Versions of a NodeJS Website and Integration with Jenkins, Deploying In NGINX

Rahul Kundra
13 min readMar 24, 2023

What We Are Going Going To

  1. Creating a NodeJS website from scratch, AppVersion1 and AppVersion2
  2. Uploading The code to GitHub and integrating it with Jenkins
  3. Building App and Deploying NGINX, Testing, Monitoring, and Get feedback. and start Again
  1. Login In Your AWS Account If you Don’t Then Then Please Create Here

2. Now Create a Instance (Note: If you are familiar with AWS cloud, You can skip This Step If you Know how to Open ports in security groups for our website . If Not, I Recommend That Choose The same configuration as I do)

Go to EC2 Instance and click on Launch Instance and Give it a name, such as “Node 1” and Select OS Ubuntu 20.04 and Select Instance Type t2.micro (Free tier eligible, Family: t2, 1 vCPU, 1 GiB Memory) and Use the Same key pair as the Master Instance and In Network Settings, Select the same Security Group we created for the Master Instance that allows all traffic and Configures Storage with 10GB storage (default storage)

3. Now Login in Your Instance if you Don’t Know How To Login Then You Here Link

4. Now Update System and Install Basic Packages

sudo apt update -y 
sudo apt install wget curl
sudo apt-get install --yes build-essential

Now Install NodeJs and NPM Package 18.15.0 and 8.1.0

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - &&sudo apt-get install -y nodejs

sudo npm install -g npm@8.1.0

node -v && npm -v

Note: Run As Sudo User Not Root User if You want Run as Root Then Check Below In Question Section We Have Disscus In Deep

5. Now We Need To Create a Directory for Our Web Application Where We Are Going to Store Our Data And Go Inside and Check Path Of Directoy

mkdir Freak-Dragon-Deploy && cd Freak-Dragon-Deploy/ && pwd 

6. Now Start running NPM in Your project folder By Running

npm init

Note : After you run npm init command For Setting up your package, you will be asked to Enter variables. Each line will begin by telling you which variable it is asking for, such as the package name. To the right of the variable name, there may be a default value in parentheses or it may be blank. You can either accept the default by pressing Enter or Enter your own value. Most beginners stick with the defaults.

For this setup, the Entry Point variable will be the main server file. In Simpler projects, only one server file is needed, but in larger ones, there may be multiple server files. The most common names for the main server file are index.js, app.js, and server.js. Keep in mind that the name of the main server file is arbitrary and some Node services may expect it to have a specific name or be in a particular location. This is not crucial for a simple server, but something to Remember when reviewing examples

What I Have Done After npm init I leave Package Name default and Enter and leave Version default As This Our Version 1 and add description and add entry point and leave default test command and git repository and add author name and leave license default

package name: (freak-dragon-deploy)
version: (1.0.0)
description: Creating Our First Web Application For DevOps Learning And This Is AppVerion1 Also
entry point: (index.js) (index.js)
test command:
git repository:
keywords:
author: Rahul Kundra
license: (ISC)

7. Now We Have a file called package.json in our project folder that looks like this:

8. Now To use NPM with our project, we’ll install an NPM package called Express.js. This package is commonly used in Node server projects, and includes objects and methods that simplify tasks like routing, database integration, error handling, and front-end template use.

Our project’s root folder contains a file called package.json, which holds basic information about our app, as well as a record of all the packages we download and save. This is important because other environments need to know which NPM packages our project uses, so they can download and save them in order to run our code. While package.json files can do many things, for now we only need to know that they hold our project’s basic information and packages.

To connect a package to our app, we need to follow two steps:

  1. Download and install the package from NPM.
  2. Save the package name and version number under “Dependencies” in package.json.

To install the Express package, run the following Command from your terminal, while in your Project’s folder:

npm install -s express

This Command installs the Express.js package from the npm registry and Saves it as a dependency in the package.json file for the current project Because We use -s Option

The package will be added to a folder called node_modules in your root project folder. Note that this folder won’t appear until you’ve installed your first package with NPM. If you forget to use -s or — save, you can manually add the package name and version number to package.json. Just be sure to include them!

Here We Have Three Files Now and our package dependency in the package.json

9. Now You Have Two Option Create a index.html file and Put our web Application content Inside And Create a Node.js Nadd Entry

  1. In First Option We Create Both index.html and node.js
nano index.html 

Why did I choose to add HTML code? Because it’s the language we all learned in school — Even though it Sometimes feels like We’ve been coding 🤏😳 In it Since The Stone Age Now And add HTML code

<!DOCTYPE html>
<html>
<head>
<title>Hello All DevOpFreak, Welcome To This Project!</title>
<style>
h1 { color: #4c4cff; text-align: center; }
h2 { color: #ffa500; text-align: center; }
form { text-align: center; }
input[type='email'] { padding: 10px; border: none; border-radius: 5px; margin-right: 10px; }
button[type='submit'] { padding: 10px; border: none; border-radius: 5px; background-color: #4c4cff; color: white; cursor: pointer; }
p { color: #808080; text-align: center; }
</style>
</head>
<body>
<h1>Hello All DevOpFreak, Welcome To This Project! 😊</h1>
<h2>Subscribe to our newsletter:</h2>
<form><input type="email" placeholder="Enter your email"><button type="submit">Subscribe</button></form>
<p>AppVersion1</p>
</body>
</html>

Note: I Use nano Editior You Can Use Any Like vim or you can use cat to add text But for Nano to Exit Press Ctrl + x and type yes and then enter

2. Now Create index.js file

nano index.j

And Add This Code Even I Explain Explain By Using // Okey

const express = require('express'); //Import the express dependency
const app = express(); //Instantiate an express app, the main work horse of this server
const port = 5000; //Save the port number where your server will be listening

//Idiomatic expression in express to route and respond to a client request
app.get('/', (req, res) => { //get requests to the root ("/") will route here
res.sendFile('index.html', {root: __dirname}); //server responds by sending the index.html file to the client's browser
//the .sendFile method needs the absolute path to the file, see: https://expressjs.com/en/4x/api.html#res.sendFile
});

app.listen(port, () => { //server starts listening for any attempts from a client to connect at port: {port}
console.log(`Now listening on port ${port}`);
});

Now We Have All Files Ready

3. Now We Start Our Website using index.js file As This our First Method

node index.js 

4. “Now, Go to AWS, copy the Instance public IP address, and type : port Number Like 52.66.237.185:5000

How do you feel now that you’ve created your first website? 😀

Note: If you’re unable to access it, check if your AWS Security Group has allowed the project number. Also, if your system has a firewall installed and the port isn’t allowed, check why. Remember, just do what I do! 😉 If you’re able to access it, great! And If you need Help Mention In Comment

2. Now, let’s Move on to the Next step, Method 2

  1. Now Only Create a index.js file and content inside

Note: But Now You May See you No Terminal Where you Can Type command and Create file Because your code running In Background

For Now Press Ctrl + c and you get your terminal back but if you again check your website then you make see This site can’t be reached Because you stop the code

But We Have Solution To run the Node.js application in the background, you can use a process manager like PM2

Note: Install This Package In Your Project file Same Location Where you Create index files

2. Now Install Package and Start Code and Stop and list all Process

sudo npm install -g pm2
pm2 start index.js
pm2 stop index.js
pm2 delete index.js
pm2 list

Note: You Also Run Start your Node.js application as a background process with the name “my-app”.

pm2 start index.js --name my-app

Note: You also Configure PM2 to start your Node.js application automatically when the system boots up, use the following command:

pm2 startup

Follow the instructions provided by the command to set up the startup script

3. Now We Create index.js and Apply Second Method But We Have move old index.js and index.html file Somewhere from our Project

Tumne Suna He hoga ki ek jungle mein do sher ek saath nahi reh sakte

Now We Move Index file to ubuntu home directory

mv index.js index.html /home/ubuntu

4. Now We Create index.js

nano index.js 

Now add this code inside

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

const PORT = process.env.PORT || 5000;

app.get('/', (req, res) => {
const heading = "<h1 style='color:#4c4cff; text-align:center;'>Hello All DevOpFreak, Welcome To This Project! 😊</h1>";
const subheading = "<h2 style='color:#ffa500; text-align:center;'>Subscribe to our newsletter:</h2>";
const form = "<form style='text-align:center;'><input type='email' placeholder='Enter your email'><button type='submit'>Subscribe</button></form>";
const version = "<p style='color:#808080; text-align:center;'>AppVersion1</p>";

res.send(heading + subheading + form + version);
});

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Now This We Run This In as we Siscussed Earlier

pm2 start index.js 

Now You See Some Think Like This

5. Now Again We Access Our Web Application Using Instance Public IP and Same Port No We Define nodejs.index File

Now, Here’s My Question: Do you find any difference between the looks of both websites? Mention it in the Comments and let’s See ಠ_ಠ How Much you Notice🧐

Now Let Upload This Code In GitHub and Integrate With Jenkins

  1. First Login In Your GitHub Account if you Don’t have Then Create Here Link

2. Now You Need Create A Token As GitHub has changed its policy to encourage the use of personal access tokens instead of passwords for authentication when accessing and modifying repositories. This is part of GitHub’s ongoing efforts to improve security and protect user accounts. By using personal access tokens, users can more securely authenticate their access to GitHub and perform actions such as push and pull requests without the need to enter their GitHub account password

  1. Go to your GitHub account and click on your profile picture in the top right corner. Then click on “Settings” from the dropdown menu.
  2. In the Settings page, click on “Developer settings” in the left sidebar.
  3. In the Developer settings page, click on “Personal access tokens.”
  4. Now You Have Two Option For Now click on Token classic and Genrate new token You May Also See Two Option Here classic and Beta Version for now Select classic

5. Choose the scopes or permissions for your token based on what you need to do on GitHub. For example, if you need to push code to a repository, you’ll need the “repo” permission. But For Now select In all Option We Have Do Many Particles

6. Click the “Generate token” button at the bottom of the page.

7. Your New token will be displayed on the screen. Be sure to copy and save the token somewhere secure, as you won’t be able to access it again

3. Now Create a new repository by clicking on the + icon and copy the given SSH link. Don’t create any license or readme.md file, otherwise git will force you to pull/download the changes first

Now after You Click In new Repository You See Something Like This Now you Need a Repository Name You Can Give Any thing you Like But Same As We Give Our Project Directory and Add Description and leave every thing default and and Click on Create

Now You See Something Like This Now You Need to run These Command

Note: you have three option but for Our blog choose 2 and We all do so modification as we Need

4. Now, let’s head back to Your terminal. You’ll need to install Git and add a about yourself. Note: I’m assuming you are a beginner. If you already know these steps, feel free to skip ahead

sudo apt install -y git 
git config --global user.name "rahulkundra"
git config --global user.email "rahulkundra8107@gmail.com"
git config --list

Note: Change With Your Email and User Name and Verify

5. Now We Run above Command We get when we create our Repository

echo "# -Freak-Dragon-Deploy" >> README.md
git init
git config --global init.defaultBranch master

But You May See This Type Of Error (you ignore if you want But i recommend Not because when you Create you job in jenkins and add git Url you See Branch set is Master Not Main Because of This if You want Know In Deep Then Questions

6. Now Guys we Need Need To Add .gitignore file

Note: If .gitignore not already created just add a new file .gitignore with below content in your project directory. If the file already created you can add below content in existing file.

nano .gitignore 
# Dependency directories
node_modules/

# Optional npm cache directory
.npm

# dotenv environment variables file
.env

7. Now We Can Back to 5 Step Now We add all file to satge area and do our first commit

git add .
git commit -m "my first commit for my appversion1 "
git remote add origin https://github.com/DevOpsFreako/-Freak-Dragon-Deploy.git

8.Now We add our git repository and push master brnach master not main as I change and now type your username and Use your new token in place of your GitHub password when prompted to authenticate your access to GitHub

“Guys, I’ve Made changes to many commands, so try to use the same approach. Just replace the app name. If you encounter any problems, don’t hesitate to leave a comment stating the error you faced”

9. Now, your code is pushed to GitHub repository. Check your GitHub account and simply refresh the page. You will see your code there

Now I Think That enough for this Blog In our Next blog, We’re going to delve into the exciting world of integration with Jenkins, deploying on NGINX, testing, monitoring, and Get feedback.and start aagin It’s going to be a wild ride, so Buckle up and Get ready to learn

Some questions that you might want to ask Me

1. You Might Want Know In How Many Way I Can Install NodejS and NPM Then here your Answer In Two Ways Now Check This

Note: I Have Install NodeSource installer That (recommended)

  1. Using a Node version manager to install Node.js and npm

2. Using a Node installer to install Node.js and npm

2. If you are not sure about the command or which packages are going to be installed, use the ‘--dry-run’ option at the end of the command. Please see the example below

sudo apt install nodejs --dry-run
sudo npm install npm --dry-run
sudo apt install npm --dry-run

3. To recreate a new package.json file after you have made changes to your app and want to start fresh, you can follow these steps:

  1. Delete the existing package.json file from your project directory.

2. Open your terminal or command prompt and navigate to your project directory.

3. Run the npm init command again to create a new package.json file:

4. Follow the prompts to configure your new package.json file. You can either use the default values or customize the fields as needed.

5. Once you have completed the prompts, a new package.json file will be generated in your project directory with the updated configuration.

Note: If you have installed any packages using the previous package.json file, you will need to reinstall them after creating the new package.json file. You can do this by running the npm install command in your project directory.

f You Enjoyed Reading This, Do Like, 😊 Follow, and Subscribe to email notifications so that you never miss an update. And as always, stay tuned for more amazing content in the future!

--

--