0% found this document useful (0 votes)
5 views

FSD LAB final

The document outlines the Full Stack Web Development Laboratory course at PET Engineering College, detailing various practical exercises and projects related to web development using technologies like JavaScript, NodeJS, Express, MongoDB, and MySQL. It includes a certificate section for student records, a table of contents listing topics covered, and code snippets for implementing different web applications and servers. The document serves as a record of the work done by students in the Master of Computer Applications program during the academic year 2024-2025.

Uploaded by

redgirlred13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

FSD LAB final

The document outlines the Full Stack Web Development Laboratory course at PET Engineering College, detailing various practical exercises and projects related to web development using technologies like JavaScript, NodeJS, Express, MongoDB, and MySQL. It includes a certificate section for student records, a table of contents listing topics covered, and code snippets for implementing different web applications and servers. The document serves as a record of the work done by students in the Master of Computer Applications program during the academic year 2024-2025.

Uploaded by

redgirlred13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

PET ENGINEERING COLLEGE

VALLIOOR-627 117

DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

FULL STACK WEB DEVELOPMENT LABORATORY


MC4212
PET ENGINEERING COLLEGE
VALLIOOR-627 117

DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

FULL STACK WEB DEVELOPMENT LABORATORY MC4212

Name :

Reg. No :

Year & Sem :


PET ENGINEERING COLLEGE
VALLIOOR-627 117

CERTIFICATE

Certified that this student is the bonafide record of the work done by
Ms./Mr./Mrs. of Second semester of this
College in FULL STACK WEB DEVELOPMENT LABORATORY-MC4212
during the academic year 2024-2025 in partial fulfillment of the requirement
of MCA degree of the Anna University, Chennai.

Staff in-charge Head of the Department

University Reg.No :

University Examination Held On :

Internal Examiner External Examiner


TABLE OF CONTENT

S.NO DATE TOPIC PAGE SIGNATURE

NO

1. Form validation using JavaScript

2. Get data using Fetch API

3. Create a NodeJS server that


serves static HTML and CSS files

4. Create a NodeJS server using Express that stores


data from a form as a JSON file

5. Create a NodeJS server using Express to perform


CRUD operation in MongoDB database

6. Create a NodeJS server to perform CRUD operation


in a MySQL database

7. Create a counter using ReactJS

8. Create a Todo application using ReactJS

9. Create a simple Sign up and Login mechanism and


authenticate the user using cookies

Create and deploy a virtual machine using a virtual


10. box that can be accessed from the host computer
using SSH
Create a docker container that will deploy a NodeJS
11. ping server using the NodeJS image
1. Form validation using JavaScript
CODE:
A) index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>create a Form and Validate the contents</title>
<link rel="stylesheet" href="style.css">
<style>
body{
width: 100%;
height: 100vh;
display: grid;
place-items: center;
}
</style>
</head>
<body>
<div class="box" >
<div align="center" >
<h3 style="padding: 20px;">Seminar Registeration</h3>
</div>
<form action="welcome.html" id="registerForm" >
<label for="name">Student Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<label for="clgName">College Name</label>
<input type="text" name="clgName" id="clgName" />
<label for="mobileNo">Mobile Number</label>
<input type="text" name="mobileNo" id="mobileNo" />
<div class="gender">
<label for="">Gender</label> <br/> <br />
<input type="radio" name="gender" id="male" value="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" value="female" />
<label for="female">Female</label>
<input type="radio" name="gender" id="others" value="others" />
<label for="others">others</label>
</div>
<div align="center" >
<input type="submit" value="Register">
</div>
</form>
</div>
<script src="main.js"></script>
</body>
</html>

B) style.css
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
}

.box{
width: 300px;
border:1px solid #000;
padding: 20px;
}
input{
width: 100%;
height: 25px;
margin-bottom: 15px;
}

input[type="submit"]{
height: 30px;
background-color: darkblue;
border: none;
outline: none;
cursor: pointer;
color: #fff;
font-size: 16px;
transition: .5s;
}
input[type="submit"]:hover{
background-color: blue;
}
input[type="radio"]{
width: 12px;
height: 12px;
}
.gender label{
padding-right: 20px;
}
C) main.js

document.getElementById('registerForm').addEventListener('submit',(e)=>{
let user = document.getElementById('name').value;
let email = document.getElementById('email').value;
let clgName = document.getElementById('clgName').value;
let mbleNo = document.getElementById('mobileNo').value;
let gender = document.getElementsByName('gender');
let genderValue = false
let error = [];
if( user.length <= 2 || !user.match((/^[a-z,A-Z]+$/)) ){
error.push("invalid student name");
}
if(email.length < 5 || email.indexOf('@') == -1 || email.indexOf('.') == -1
){
error.push("Invalid Email Address");
}
if(clgName.length < 5){
error.push("Invalid college name");
}
if(mbleNo.length != 10 || !mbleNo.match((/^[0-9]+$/)) ){
error.push("Invalid Phone Number");
}
for(let i=0;i<gender.length;i++){
if(gender[i].checked){
genderValue = true
}
}

if(genderValue == false){
error.push("Plase select gender option")
}
if(error.length != 0){
e.preventDefault()
alert(error.map((data)=>`\n ${data}`))
}
});

D) welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div align="center" >
<h1> Form submitted successfully </h1>
</div>
</body>
</html>
OUTPUT:
2. Get data using Fetch API
CODE:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetched Data Cards</title>
<style>
.card-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
border: 1px solid #ddd;
border-radius: 8px;
width: 200px;
padding: 15px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
text-align: center;
}
.card img {
width: 100%;
border-radius: 50%;
}
</style>
</head>
<body>
<h1>Fetched Data Cards</h1>
<div class="card-container" id="card-container"></div>

<script>
fetch('https://dummyjson.com/users')
.then(response => response.json())
.then(data => {
const container = document.getElementById('card-container');
data.users.forEach(user => {
const card = document.createElement('div');
card.classList.add('card');
const cardContent = `
<h3>${user.firstName}</h3>
<p>Id: ${user.id}</p>
<p>Age: ${user.age}</p>
<p>Gender: ${user.gender}</p>
`;
card.innerHTML = cardContent;
container.appendChild(card);
});
})
.catch(error => {
console.error('Error fetching data:', error);
});
</script>
</body>
</html>
OUTPUT:
3. Create a NodeJS server that serves static HTML and CSS files

CODE:
A) index.html

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
<link rel=”stylesheet” href=”style.css”>
<title>Full Stack Web Development</title>
</head>
<body>
<h1>Full Stack Web Development</h1>
<p>- Computer Applications</p>
</body>
</html>

B) style.css
body {
background-color: green;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}

C) server.js
const http = require(‘http’);
const fs = require(‘fs’);
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === ‘/’) {
fs.readFile(‘index.html’, (err, data) => {
if (err) {
res.writeHead(500, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Internal Server Error’);
} else {
res.writeHead(200, { ‘Content-Type’: ‘text/html’ });
res.end(data);
}
});
} else if (req.url.match(/\.(html|css)$/)) {
const filePath = req.url.slice(1);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Internal Server Error’);
} else {
res.writeHead(200, { ‘Content-Type’: filePath.endsWith(‘.css’) ? ‘text/css’ : ‘text/html’
});
res.end(data);
}
});
} else {
res.writeHead(404, { ‘Content-Type’: ‘text/plain’ });
res.end(‘404 Not Found’);
}
});

server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

OUTPUT:
4. Create a NodeJS server using Express that stores data from a form as a
JSON file

CODE:
A) New folder/views/index.js
const express = require('express');
const expbs = require('express-handlebars');
const bodyParser = require('body-parser');
const path = require('path'); // Import path module
const app = express();

// Use body-parser middleware with extended option


app.use(bodyParser.urlencoded({ extended: true }));

// Set the views directory


app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', expbs.engine({ defaultLayout: false }));
app.set('view engine', 'handlebars');

// Routing
app.get('/', function(request, response, next) {
response.render('index', { layout: false });
});

app.post('/', function(request, response, next) {


response.send(request.body);
});

app.listen(3000, () => {
console.log("Server is running on port 3000");
});

B) New folder/views/index.handlebars

<h1>Student Form</h1>
<form action="/" method="post">
<table style="font-size: 20px;">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name" placeholder="Your name.."></td>
</tr>
<tr>
<td><label for="reg">Register Number:</label></td>
<td><input type="text" id="reg" name="registerNumber" placeholder="Your
number"></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td><input type="text" id="city" name="city" placeholder="Your City"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>

OUTPUT:
5. Create a NodeJS server using Express to perform
CRUD operation in MongoDB database
CODE:
A) index.js
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const path = require("path");

mongoose.connect("mongodb://localhost:27017/student");
const Student = mongoose.model("Student", new mongoose.Schema({
name: String, Reg_number: String, Address: String, City: String
}));

const app = express();


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static("public"));

app.get("/", (r, s) => s.redirect("index.html"));


app.get("/add_student", (r, s) => s.sendFile(path.join(__dirname, "public", "index.html")));
app.get("/api/students", (r, s) => Student.find().then(s.send).catch(() => s.sendStatus(500)));
app.post("/sign_up", (r, s) => new Student({
name: r.body.name, Reg_number: r.body.reg, Address: r.body.add, City: r.body.city
}).save().then(() => s.redirect("/view.html")).catch(() => s.sendStatus(500)));
app.put("/api/student/:id", (r, s) =>
Student.findByIdAndUpdate(r.params.id, {
name: r.body.name, Reg_number: r.body.reg, Address: r.body.add, City: r.body.city
}, { new: true }).then(d => d ? s.send("Updated") : s.sendStatus(404)).catch(() =>
s.sendStatus(500)));
app.delete("/api/student/:id", (r, s) =>
Student.findByIdAndDelete(r.params.id).then(d => d ? s.send("Deleted") :
s.sendStatus(404)).catch(() => s.sendStatus(500)));
app.delete("/api/database", (_, s) =>
mongoose.connection.dropDatabase().then(() => s.send("DB Deleted")).catch(() =>
s.sendStatus(500)));

app.listen(3000, () => console.log("Running on 3000"));

B) public/index.html
<!DOCTYPE html>
<html>
<body>
<h2>Add Student</h2>
<form method="POST" action="/sign_up">
<input name="name" placeholder="Name" required><br>
<input name="reg" placeholder="Reg number" required><br>
<input name="add" placeholder="Address" required><br>
<input name="city" placeholder="City" required><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

D)public/view.html

<!DOCTYPE html>
<html>
<body>
<h2>Student Records</h2>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Reg</th>
<th>Address</th>
<th>City</th>
<th>Edit</th>
<th>Delete</th>
</tr></thead>
<tbody id="records"></tbody>
</table>
<button onclick="location.href='/add_student'">Add</button>
<script>
fetch('/api/students').then(r=>r.json()).then(d=>{
d.forEach(s=>{
records.innerHTML += `<tr><td>${s.name}</td
><td>${s.Reg_number}</td>
<td>${s.Address}</td>
<td>${s.City}</td>
<td>
<button
onclick="edit('${s._id}','${s.name}','${s.Reg_number}','${s.Address}','${s.City}')">Edit
</button>
</td>
<td>
<button onclick="del('${s._id}')">Delete</button></td>
</tr>`;
});
});
function edit(id,n,r,a,c){
const name=prompt("Name",n), reg=prompt("Reg",r), add=prompt("Address",a),
city=prompt("City",c);
if(name && reg && add && city)
fetch('/api/student/'+id,{method:'PUT',headers:{'Content-Type':'application/json'},
body:JSON.stringify({name,reg,add,city})})
.then(r=>r.text()).then(alert).then(()=>location.reload());
}
function del(id){
if(confirm("Delete?")) fetch('/api/student/'+id,{method:'DELETE'})
.then(r=>r.text()).then(alert).then(()=>location.reload());
}
</script>
</body>
</html>

OUTPUT:
After submit the data,
6. Create a NodeJS server to perform CRUD operation in a
MySQL database

CODE:

A) Create a MySQL database

CREATE DATABASE events_db;


USE events_db;
CREATE TABLE events (
id INT AUTO_INCREMENT PRIMARY KEY,
participantName VARCHAR(255),
eventName VARCHAR(255),
eventDate DATE,
eventPlace VARCHAR(255)
);

B) server.js
const express = require('express');
const mysql = require('mysql');
const app = express(), port = 3000;

const db = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database:


'events_db' });
db.connect(err => err ? console.error(err) : console.log('MySQL connected'));

app.use(express.urlencoded({ extended: false }));

app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));


app.get('/add', (req, res) => res.redirect('/'));

app.post('/addEvent', (req, res) => {


const { participantName, eventName, eventDate, eventPlace } = req.body;
db.query('INSERT INTO events (participantName, eventName, eventDate, eventPlace)
VALUES (?, ?, ?, ?)',
[participantName, eventName, eventDate, eventPlace], err => res.redirect('/events'));
});

app.get('/events', (req, res) => {


db.query('SELECT * FROM events', (err, rows) => {
const list = rows.map(e => `<li>${e.participantName} | ${e.eventName} | ${e.eventDate} |
${e.eventPlace}</li>`).join('');
res.send(`<h1>All Events</h1><button onclick="location.href='/add'">Add</button>
<button onclick="location.href='/edit'">Edit</button><button
onclick="location.href='/delete'">Delete</button><ul>${list}</ul>`);
});
});

app.get('/edit', (req, res) => {


db.query('SELECT * FROM events ORDER BY id DESC LIMIT 1', (err, [e]) => {
if (!e) return res.send('No event to edit');
res.send(`<form action="/updateEvent" method="post">
<input type="hidden" name="id" value="${e.id}">
<input name="participantName" value="${e.participantName}"><br>
<input name="eventName" value="${e.eventName}"><br>
<input type="date" name="eventDate"
value="${e.eventDate.toISOString().split('T')[0]}"><br>
<input name="eventPlace"
value="${e.eventPlace}"><br><button>Update</button></form>`);
});
});

app.post('/updateEvent', (req, res) => {


const { id, participantName, eventName, eventDate, eventPlace } = req.body;
db.query('UPDATE events SET participantName=?, eventName=?, eventDate=?,
eventPlace=? WHERE id=?',
[participantName, eventName, eventDate, eventPlace, id], err => res.redirect('/events'));
});

app.get('/delete', (req, res) => {


db.query('DELETE FROM events ORDER BY id DESC LIMIT 1', err =>
res.redirect('/events'));
});

app.listen(port, () => console.log(`http://localhost:${port}`));

C)index.html
<!DOCTYPE html>
<html>
<body>
<h2>Add Event</h2>
<form action="/addEvent" method="post">
<input name="participantName" placeholder="Participant Name"><br>
<input name="eventName" placeholder="Event Name"><br>
<input type="date" name="eventDate"><br>
<input name="eventPlace" placeholder="Event Place"><br>
<button>Submit</button>
</form>
</body>
</html>
OUTPUT:
Fill in the details and then click 'Submit'

To add new data, click on 'Add'.


To delete existing data, click on 'Delete'
7. Create a counter using ReactJS
CODE:
A) counter.js
import React, { useState } from 'react';
import './Counter.css';
const Counter = () => {
const [count, setCount] = useState(0);

const increment = () => {


setCount(prevCount => prevCount + 1);
};
const decrement = () => {
setCount(prevCount => prevCount - 1);
};
const reset = () => {
setCount(0);
};
return (
<div className="counter">
<h2>COUNTER</h2>
<div className="count">{count}</div>
<div className="buttons">
<button onClick={decrement}>-</button>
<button onClick={reset} className="reset-button">Reset</button>
<button onClick={increment}>+</button>
</div>
</div>
);
};
export default Counter;

B) counter-app/src/App.js

import React from 'react';


import './App.css';
import Counter from './Counter';

function App() {
return (
<div className="App">
<Counter />
</div>
);
}
export default App;
C) counter-app/src/Counter.css
.counter {
text-align: center;
margin-top: 50px;
}
.count {
font-size: 24px;
margin-bottom: 20px;
}
.buttons button {
font-size: 18px;
margin: 0 10px;
padding: 5px 10px;
cursor: pointer;
}

OUTPUT:
8. Create a Todo application using ReactJS

CODE:

A) todo-app/src/App.js

import React, { useState, useEffect } from 'react';


import axios from 'axios';
const API = 'http://localhost:3001/tasks';
function App() {
const [tasks, setTasks] = useState([]);
const [text, setText] = useState('');
useEffect(() => {
axios.get(API).then(res => setTasks(res.data));
}, []);
const addTask = async () => {
if (!text.trim()) return;
const newTask = { id: Date.now(), task: text, completed: false };
await axios.post(API, newTask);
setTasks([...tasks, newTask]);
setText('');
};
const toggleTask = async (id) => {
const updated = tasks.map(t => t.id === id ? { ...t, completed: !t.completed } : t);
setTasks(updated);
await axios.put(`${API}/${id}`, updated.find(t => t.id === id));
};
const clearCompleted = async () => {
const toDelete = tasks.filter(t => t.completed);
setTasks(tasks.filter(t => !t.completed));
await Promise.all(toDelete.map(t => axios.delete(`${API}/${t.id}`)));
};
return (
<div>
<h1>Todo List</h1>
<input value={text} onChange={e => setText(e.target.value)} placeholder="New task" />
<button onClick={addTask}>Add</button>
<button onClick={clearCompleted}>Clear Completed</button>
<ul>
{tasks.map(t => (
<li key={t.id} style={{ textDecoration: t.completed ? 'line-through' : '' }}>
<input type="checkbox" checked={t.completed} onChange={() => toggleTask(t.id)} />
{t.task}
</li>
))}
</ul>
</div>
);
}
export default App;

B) todo-app/public/db.json

{
"tasks": [
{
"id": 1,
"task": "Do Jogging",
"completed": false
},
{
"id": 2,
"task": "Complete Class Notes",
"completed": false
},
{
"id": 3,
"task": "Call Mom",
"completed": false
},
{
"id": 4,
"task": "Prepare Exam to Study",
"completed": false
},
{
"id": 5,
"task": "Feed Cat",
"completed": false
},
{
"id": 6,
"task": "Fill the Water Tank",
"completed": false
},
{
"id": 7,
"task": "Do Laundry",
"completed": false
},
{
"id": 8,
"task": "Wash Clothes",
"completed": false
}
]
}
OUTPUT:
9. Create a simple Sign up and Login mechanism and
authenticate the user using cookies

CODE:
A) Create a MySQL database
CREATE DATABASE IF NOT EXISTS authdb;
USE authdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);

B) server.js
const express = require('express');
const mysql = require('mysql2');
const cookieParser = require('cookie-parser');
const bcrypt = require('bcrypt');
const path = require('path');
const app = express();
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '', // change if needed
database: 'authdb'
});
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static('public'));
app.get('/', (req, res) => {
if (req.cookies.user) {
res.send(`<h2>Welcome, ${req.cookies.user}</h2><a href="/logout">Logout</a>`);
} else {
res.send(`<h2>Please login</h2><a href="/login">Login</a>`);
}
});
app.get('/register', (req, res) => {
res.sendFile(path.join(__dirname, 'views/register.html'));
});
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashed = await bcrypt.hash(password, 10);
db.query('INSERT INTO users (username, password) VALUES (?, ?)', [username, hashed],
(err) => {
if (err) return res.send('Username already exists. <a href="/register">Try again</a>');
res.send('Registered! <a href="/login">Login</a>');
});
});
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'views/login.html'));
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
db.query('SELECT * FROM users WHERE username = ?', [username], async (err, results)
=> {
if (err || results.length === 0) return res.send('Invalid credentials. <a href="/login">Try
again</a>');
const match = await bcrypt.compare(password, results[0].password);
if (match) {
res.cookie('user', username, { httpOnly: true });
res.redirect('/');
} else {
res.send('Invalid credentials. <a href="/login">Try again</a>');
}
});
});
app.get('/logout', (req, res) => {
res.clearCookie('user');
res.send('Logged out. <a href="/login">Login again</a>');
});
app.listen(3000, () => console.log('Server at http://localhost:3000'));

C) views/register.html
<!DOCTYPE html>
<html>
<head><title>Register</title><link rel="stylesheet" href="/style.css"></head>
<body>
<div class="box">
<h2>Register</h2>
<form method="POST">
<input name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<button>Sign Up</button>
</form>
<p>Already have an account? <a href="/login">Login</a></p>
</div>
</body>
</html>
D) views/login.html
<!DOCTYPE html>
<html>
<head><title>Login</title><link rel="stylesheet" href="/style.css"></head>
<body>
<div class="box">
<h2>Login</h2>
<form method="POST">
<input name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<button>Login</button>
</form>
<p>New here? <a href="/register">Register</a></p>
</div>
</body>
</html>

E) public/style.css
body {
font-family: Arial;
background: #f0f0f0;
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
}
.box {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 0 10px #aaa;
}
input, button {
display: block;
width: 100%;
margin-bottom: 15px;
padding: 10px;
}
button {
background: #007bff;
color: white;
border: none;
}

OUTPUT:
10. Create and deploy a virtual machine using a virtual box that can be
accessed from the host computer using SSH
CODE:
STEP 1: Prepare Your Computer

• Enable Virtualization (VT-x / AMD-V) in BIOS.


• Free up at least 10GB disk space.
• Avoid syncing VM folders via services like OneDrive/Dropbox.
• Admin access is required for installation.

STEP 2: Install VirtualBox

• Download and install from virtualbox.org.


• Follow the install wizard.
STEP 3: Import a VM (.ova file)

• Download .ova from your course.


• In VirtualBox: File > Import Appliance → select .ova → Import.
STEP 4: Start the VM

• Select the VM in the list → click Start.


• Follow on-screen OS setup.
STEP 5: Use the VM

• File Sharing: Use Shared Folders (Settings > Shared Folders).


• Install software with sudo apt update, sudo apt install vim
STEP 6: Shut Down the VM

• Use the Shutdown button inside the VM or In VirtualBox menu → Machine > ACPI
Shutdown
OUTPUT:
11. Create a docker container that will deploy a NodeJS ping server using
the NodeJS image

CODE:
A) nodejs-ping-server/server.js

const express = require('express');


const app = express();
const port = 3000;

app.get('/ping', (req, res) => {


res.send('Hello from Node Js');
});

app.listen(port, () => {
console.log(`Ping server listening at http://localhost:${port}`);
});

B) nodejs-ping-server/Dockerfile

# Use the official Node.js image from the Docker Hub


FROM node:14

# Create and change to the app directory


WORKDIR /usr/src/app

# Copy package.json and package-lock.json


COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application code


COPY . .

# Expose the port the app runs on


EXPOSE 3000

# Command to run the app


CMD ["node", "server.js"]
OUTPUT:
A) Open the command prompt and navigate to the project directory. Then, run “npm
install express” to install the required dependencies for the project

B) Open Command Prompt in the project directory and run command to build
your Docker image

C) After the image is built, run it as a container,


D) Open a “web browser” or use “curl” to test the ping server
i) Web Browser “http://localhost:3000/ping”

You might also like