> First and foremost, open SSH in Visual Studio or Git Bash Code (Window) to access VPS (Example: VEESP).
ssh [email protected]
> Install Git on VPS (Veesp)
sudo apt install git-all
> Install Nodejs version 14.x - using script to create apt sources list file for the NodeSource Node.js 14.x repository.
curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
> Check the repository is added then you can begin to start installation of Node.js 14.x on Ubuntu.
cat /etc/apt/sources.list.d/nodesource.list
deb [signed-by=/usr/share/keyrings/nodesource.gpg] https://deb.nodesource.com/node_14.x focal main
deb-src [signed-by=/usr/share/keyrings/nodesource.gpg] https://deb.nodesource.com/node_14.x focal main
> Use the command as below to run Node.js installation.
sudo apt -y install nodejs
> There are two way to get project in our VPS. First, let try to use git clone to download project in folder www.
cd var/www
Note: To have folder www, you can run the following commands:
sudo apt install tasksel && sudo tasksel install lamp-server
> Beside, default folder named html, we will create a new folder named chatbox for running chatbox project.
mkdir chatbox && ls -a
. .. chatbox html
> Open chatbox can run git clone to download project from git.
git clone https://github.com/flagtick/chatbox-server-nodejs.git
> Check server.js in folder chatbox by cat server.js as below.
root@chatbox://var/www/chatbox# ls -a
. .. config controllers .git models node_modules package.json package-lock.json README.md routes server.js
root@chatbox://var/www/chatbox# cat server.js
const express = require("./config/express.js"),
mongoose = require("mongoose");
const app = express.init();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
server.listen(3000, () => {
console.log('Server started on port 3000');
});
/** Socket.io */
io.of("/api/socket").on("connection", (socket) => {
console.log("socket.io: Connection established successfully: ", socket.id);
socket.on("disconnect", () => {
console.log("socket.io: Connection lose!: ", socket.id);
});
// socket.on('technical-issue', (msg) => {
// console.log('message: ' + msg);
// });
});
/** Connect MongoDB from Node.js application */
mongoose.set('strictQuery', false);
mongoose.connect('mongodb+srv://flagtick:[email protected]/chatbox?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
const messageCollectionStream = connection.collection("messages").watch();
messageCollectionStream.on("change", (change) => {
switch (change.operationType) {
case "insert":
console.log(change.operationType);
io.of("/api/socket").emit("technical-issue", 'Your problem will be solving. Please wait for a moment!');
break;
case "delete":
break;
}
});
});
root@chatbox://var/www/chatbox#
> Install all dependencies in folder chatbox based on package.json file.
npm install
> We need an advanced process manager for production Node.js applications. Load balancer, logs facility, startup script, micro service management, at a glance. Hence, let install pm2 as below.
sudo npm install pm2 -g
> Run pm2 to start node server named Nodemy-server as below. So, all manipulations are happening Nodemy-server under control by PM2.
pm2 start npm --name "Nodemy-server" -- start
> Run pm2 save to save Node.js application and pm2 list to load all processes and show process details.
pm2 save
pm2 list
> To pm2 run Node.js application automatically, we will run pm2 startup as below.
pm2 startup
> Open port 3000 in VPS (VEESP)
sudo ufw enable
sudo ufw allow 3000
sudo ufw allow 22/tcp
sudo ufw reset
Note: You get error SSH server connect to host xxx port 22: Connection timed out on Linux-Ubuntu. It happens because of firewall connection. You should reset your firewall connection from your hosting website.
sudo ufw allow 22/tcp
sudo ufw reset
Note: In while, if you encounter problems with VPS, you can re-install. If it was your manipulation - just delete known host key in file /c/Users/admin/.ssh/known_hosts at your local PC from which you are trying to access your server.
> http://185.242.107.227:3000/
> You can test on Postman with method /message/getMessages.
> To make an adjustment on Node.js application, we will open chatbox where we store source code.
cd //
cd var/www/chatbox
sudo nano server.js
pm2 reload all
> To load all processes when use pm2 and upon duplicated, you can kill them.
pm2 list
ps aux | grep pm2
> Here is server.js
const express = require("./config/express.js"),
mongoose = require("mongoose");
const app = express.init();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
server.listen(3000, () => {
console.log('Server started on port 3000');
});
app.get("/", (req, res) => {
res.send("<h1>Your server has start from deployment!!</h1>");
});
/** Socket.io */
io.of("/api/socket").on("connection", (socket) => {
console.log("socket.io: Connection established successfully: ", socket.id);
socket.on("disconnect", () => {
console.log("socket.io: Connection lose!: ", socket.id);
});
});
/** Connect MongoDB from Node.js application */
mongoose.set('strictQuery', false);
mongoose.connect('mongodb+srv://flagtick:[email protected]/chatbox?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
const messageCollectionStream = connection.collection("messages").watch();
messageCollectionStream.on("change", (change) => {
switch (change.operationType) {
case "insert":
io.of("/api/socket").emit("technical-issue", 'Your problem will be solving. Please wait for a moment!');
break;
case "delete":
break;
}
});
});
> As so, the first way deployment regards to git, here is simplest way:
git clone <Your URL>
npm install
pm2 reload all
> You can also use scp command to copy your updated file into server by SSH directly.
scp -r server.js [email protected]:/var/www/chatbox
pm2 reload all
> How to add log to your Node.js application on server/production. First and foremost, let create Logger.js from your source project.
const { createLogger, format, transports } = require('winston');
module.exports = createLogger({
transports:
new transports.File({
filename: 'logs/server.log',
format:format.combine(
format.timestamp({format: 'MMM-DD-YYYY HH:mm:ss'}),
format.align(),
format.printf(info => `${info.level}: ${[info.timestamp]}: ${info.message}`),
)}),
});
Note: You need to run npm i winston to install winston dependency.
> Our project has structure like this
/root/utils/logger.js
/root/server.js
Note: After restart Node.js application, it creates logs/server.log.
> The server.js has updated as below:
const express = require("./config/express.js"), mongoose = require("mongoose"); const Logger = require('./utils/logger'); const app = express.init(); const server = require("http").createServer(app); const io = require("socket.io")(server); server.listen(3000, () => { console.log('Server started on port 3000'); }); app.get("/", (req, res) => { res.send("<h1>Your server has start from deployment!!</h1>"); }); /** Socket.io */ io.of("/api/socket").on("connection", (socket) => { Logger.info("socket.io: Connection established successfully: ", socket.id); socket.on("disconnect", () => { Logger.info("socket.io: Connection lose!: ", socket.id); }); }); /** Connect MongoDB from Node.js application */ mongoose.set('strictQuery', false); mongoose.connect('mongodb+srv://flagtick:[email protected]/chatbox?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true }); const connection = mongoose.connection; connection.once("open", () => { const messageCollectionStream = connection.collection("messages").watch(); messageCollectionStream.on("change", (change) => { switch (change.operationType) { case "insert": Logger.info("Successful insert data!"); io.of("/api/socket").emit("technical-issue", 'Your problem will be solving. Please wait for a moment!'); break; case "delete": break; } }); });