Application deployment

Install Git on Amazon EC2 2023

Below are instructions for installing Git on an Amazon EC2 virtual machine running Amazon Linux 2023 using basic steps.

  1. Update System Packages

First, update your system packages to make sure you’re using the latest version:

sudo dnf update -y
  1. Use the following command to install Git
sudo yum install git
  1. Install MySQL command-line client
sudo dnf install mariadb105
  1. Check the Git, MySQL version was successfully installed:
git --version && mariadb --version

Create a VPC

  1. Come back to db-instance

    • Scroll down to Connectivity & security section, choose Endpoints
    • Copy Endpoint Create a VPC
  2. Connect to the MySQL command-line client (unencrypted)

    • For the -h parameter, replace it with the DNS name (endpoint) of the DB instance. You can find the DNS name in the detail console of the RDS you created.
    • For the -P parameter, replace it with the port for the DB instance (3306).
    • For the -u parameter, replace it with the master user you set when creating the RDS.
    • After running the command, enter the master user password that you set during the creation of the RDS.
mysql -h [YOUR-RDS-ENDPOINT] -P 3306 -u admin -p

Create a VPC

Show Database

We created the database in the previous configuration step. When connecting to the DB Instance endpoint, the fcaj database has already been initialized. Using this command to display a list of all databases.

SHOW DATABASES;

Create a VPC

Create Database

If fcaj database does not exist yet, use the following command to create a new database named “fcaj”:

CREATE DATABASE IF NOT EXISTS fcaj;

Create a VPC

Using Database

Next, we use the fcaj database using the command. This command indicates that all SQL commands will then be executed in the fcaj database.

USE fcaj;

Create a VPC

Create Table “user”

We have created the database and used it. Now, we will define a “user” table in this database using the following SQL script:

CREATE TABLE `user`
(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `first_name` VARCHAR(45) NOT NULL,
    `last_name` VARCHAR(45) NOT NULL,
    `email` VARCHAR(100) NOT NULL UNIQUE,
    `phone` VARCHAR(15) NOT NULL,
    `comments` TEXT NOT NULL,
    `status` ENUM('active', 'inactive') NOT NULL DEFAULT 'active'
) ENGINE = InnoDB;

This command defines the structure of the “user” table with columns such as “id”, “first_name”, “last_name”, “email”, “phone”, “comments”, and “status”. These columns represent information about the user, and the “id” column is set as the auto-incrementing primary key. Create a VPC

Add Data to Table “user”

Finally, we can add data to the “user” table using the INSERT INTO command. Here is an example that adds some records to a table:

INSERT INTO `user`
(`first_name`, `last_name`, `email`, `phone`, `comments`, `status`)
VALUES
('Amanda', 'Nunes', 'anunes@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Alexander', 'Volkanovski', 'avolkanovski@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Khabib', 'Nurmagomedov', 'knurmagomedov@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Kamaru', 'Usman', 'kusman@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Israel', 'Adesanya', 'iadesanya@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Henry', 'Cejudo', 'hcejudo@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Valentina', 'Shevchenko', 'vshevchenko@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Tyron', 'Woodley', 'twoodley@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Rose', 'Namajunas', 'rnamajunas@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Tony', 'Ferguson', 'tferguson@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Jorge', 'Masvidal', 'jmasvidal@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Nate', 'Diaz', 'ndiaz@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Conor', 'McGregor', 'cmcGregor@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Cris', 'Cyborg', 'ccyborg@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Tecia', 'Torres', 'ttorres@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Ronda', 'Rousey', 'rrousey@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Holly', 'Holm', 'hholm@ufc.com', '012345 678910', 'I love FCAJ', 'active'),
('Joanna', 'Jedrzejczyk', 'jjedrzejczyk@ufc.com', '012345 678910', 'I love FCAJ', 'active');

This command adds user records to the “user” table with information such as name, email, phone number, comments, and a default status of “active”. Create a VPC

Display all information stored in the table.

View all the information currently stored in the user table

SELECT * FROM user;

Create a VPC

Deploy the application

  1. Clone the repository from GitHub use the following command:
git clone https://github.com/thienluhoan/000006-EC2.git

Create a VPC

  1. Navigate to the directory for lab:
cd 000006-EC2
  1. Use nano .env to enter environmental variables, then enter the following code to set up the connection to the database. Remember to rename the DB_HOST field accordingly.
DB_HOST='YOUR-RDS-ENDPOINT'
DB_NAME='fcaj'
DB_USER='admin'
DB_PASS='Aa12345#'

Create a VPC 4. Run nano script.sh to paste the following code. Below is Bash script to install Node.js on Amazon EC2 Linux:

#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# --- Environment Configuration ---
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}Starting Deployment Script...${NC}"

# --- Step 1: NVM & Node.js Environment Setup ---
export NVM_DIR="$HOME/.nvm"

# Load NVM if installed, otherwise install it
if [ -s "$NVM_DIR/nvm.sh" ]; then
    echo -e "${YELLOW}Loading existing NVM from $NVM_DIR...${NC}"
    \. "$NVM_DIR/nvm.sh"
else
    echo -e "${YELLOW}Installing NVM (Node Version Manager)...${NC}"
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
    \. "$NVM_DIR/nvm.sh"
fi

# Install Node.js LTS and set it as the default version for future sessions
echo -e "${YELLOW}Installing Node.js LTS...${NC}"
nvm install --lts
nvm use --lts
nvm alias default 'lts/*'

# Verify versions (Cleanly typed to avoid zero-width space errors)
NODE_VERSION=$(node -v)
NPM_VERSION=$(npm -v)
echo -e "${GREEN}Node Version: ${NODE_VERSION}${NC}"
echo -e "${GREEN}NPM Version: ${NPM_VERSION}${NC}"

# --- Step 2: PM2 Global Installation ---
# Check if PM2 is installed; if not, install it globally
if ! command -v pm2 &> /dev/null; then
    echo -e "${YELLOW}Installing PM2 (Production Process Manager) globally...${NC}"
    npm install pm2 -g
else
    echo -e "${GREEN}PM2 is already installed.${NC}"
fi

# --- Step 3: Project Initialization ---
# Create package.json if it doesn't exist in the current directory
if [ ! -f package.json ]; then
    echo -e "${YELLOW}Initializing package.json...${NC}"
    npm init -y
fi

# --- Step 4: Dependency Installation ---
echo -e "${YELLOW}Installing production dependencies...${NC}"
npm install express dotenv express-handlebars body-parser mysql

echo -e "${YELLOW}Installing development dependencies...${NC}"
npm install --save-dev nodemon

# --- Step 5: NPM Script Configuration ---
# Add start and dev scripts to package.json programmatically
echo -e "${YELLOW}Configuring NPM scripts in package.json...${NC}"
npm pkg set scripts.start="pm2 start app.js --name 'app' --watch"
npm pkg set scripts.dev="nodemon app.js"

# --- Step 6: Process Management Setup ---
echo -e "${YELLOW}Setting up PM2 to start on system boot...${NC}"

# Generate and execute PM2 startup script securely mapping the correct Node path
sudo env PATH=$PATH:$(dirname $(which node)) $(which pm2) startup systemd -u $USER --hp $HOME

# --- Completion ---
echo -e "${GREEN}Deployment Script Completed Successfully!${NC}"
echo -e "${YELLOW}---------------------------------------------------------${NC}"
echo -e "${YELLOW}Next Steps:${NC}"
echo -e "${YELLOW}1. Run 'source ~/.bashrc' to refresh your terminal.${NC}"
echo -e "${YELLOW}2. Run 'npm start' to start your application via PM2.${NC}"
echo -e "${YELLOW}3. Run 'pm2 save' to freeze your process list for auto-restart.${NC}"
echo -e "${YELLOW}---------------------------------------------------------${NC}"

Create a VPC

  1. Use the command chmod +x script.sh to grant the file execution permissions. Create a VPC

  2. Run bash script.sh to start installation Create a VPC Create a VPC

  3. Run need to run source ~/.bashrc to refresh your terminal.:

  4. Run npm start to start your application via PM2.

  5. Run pm2 save to freeze your process list for auto-restart. Create a VPC

  6. Run pm2 status to display the current status of all applications being managed by PM2. When you run this command, you’ll receive an overview of each application, including details like their state (running, stopped, etc.), memory usage, CPU usage, and the number of restarts. This helps in monitoring the performance and health of your Node.js applications effectively. Create a VPC

  7. Go back to EC2 console, choose ec2-instance to copy the public IPv4 address. Create a VPC

  8. Open a web browser and enter the IP address or domain name of the EC2 Instance, followed by port 5000 for example: http://<IP address or domain name> :5000. This will make a connection to your application running on port 5000. Create a VPC

(Optional) Some SQL commands to check database information in a database management system (DBMS) such as MySQL or PostgreSQL:

  1. Choose a specific database to work with:
USE database_name;

This command will move you from your current database to a database named “database_name”. After using this command, all subsequent SQL commands will apply to this database.

  1. Shows the structure of a specific table:
DESCRIBE table_name;

This command will tell you the structure of the table named “table_name”, including the column name, data type, and other column properties.

  1. Display information about database size:
SELECT table_schema "fcaj", SUM(data_length + index_length) / 1024 / 1024 "Database Size (MB)"
FROM information_schema.tables
GROUP BY table_schema;

This command will display information about the size of the databases in the system, in Megabytes (MB). Remember to replace “database_name” and “table_name” with the specific names of the database and table you want to test. These commands help you manage and examine information about your database. Create a VPC