Author Archives: admin

How To Set Up a Node.js Application for Production on Ubuntu 20.04

Node.js is an open-source JavaScript runtime environment for building server-side and networking applications. The platform runs on Linux, macOS, FreeBSD, and Windows. Though you can run Node.js applications at the command line, this tutorial will focus on running them as a service. This means that they will restart on reboot or failure and are safe for use in a production environment.

In this tutorial, you will set up a production-ready Node.js environment on a single Ubuntu 20.04 server. This server will run a Node.js application managed by PM2, and provide users with secure access to the application through an Nginx reverse proxy. The Nginx server will offer HTTPS using a free certificate provided by Let’s Encrypt.


This guide assumes that you have the following:

An Ubuntu 20.04 server setup, as described in the initial server setup guide for Ubuntu 20.04. You should have a non-root user with sudo privileges and an active firewall.
A domain name pointed at your server’s public IP. This tutorial will use the domain name throughout.
Nginx installed, as covered in How To Install Nginx on Ubuntu 20.04.
Nginx configured with SSL using Let’s Encrypt certificates. How To Secure Nginx with Let’s Encrypt on Ubuntu 20.04 will walk you through the process.
When you’ve completed the prerequisites, you will have a server serving your domain’s default placeholder page at

Step 1 — Installing Node.js

Let’s begin by installing the latest LTS release of Node.js, using the NodeSource package archives.

First, install the NodeSource PPA in order to get access to its contents. Make sure you’re in your home directory, and use curl to retrieve the installation script for the most recent LTS version of Node.js from its archives.

cd ~
curl -sL -o

You can inspect the contents of this script with nano or your preferred text editor:


When you’re done inspecting the script, run it under sudo:

sudo bash

The PPA will be added to your configuration and your local package cache will be updated automatically. After running the setup script from Nodesource, you can install the Node.js package:

sudo apt install nodejs

To check which version of Node.js you have installed after these initial steps, type:

node -v

Note: When installing from the NodeSource PPA, the Node.js executable is called nodejs, rather than node.

The nodejs package contains the nodejs binary as well as npm, a package manager for Node modules, so you don’t need to install npm separately.

npm uses a configuration file in your home directory to keep track of updates. It will be created the first time you run npm. Execute this command to verify that npm is installed and to create the configuration file:

npm -v

In order for some npm packages to work (those that require compiling code from source, for example), you will need to install the build-essential package:

sudo apt install build-essential

You now have the necessary tools to work with npm packages that require compiling code from source.

With the Node.js runtime installed, let’s move on to writing a Node.js application.

Step 2 — Creating a Node.js Application

Let’s write a Hello World application that returns “Hello World” to any HTTP requests. This sample application will help you get Node.js set up. You can replace it with your own application — just make sure that you modify your application to listen on the appropriate IP addresses and ports.

First, let’s create a sample application called hello.js:

cd ~
nano hello.js

Insert the following code into the file:

const http = require('http');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World!\n');

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

Save the file and exit the editor.

This Node.js application listens on the specified address (localhost) and port (3000), and returns “Hello World!” with a 200 HTTP success code. Since we’re listening on localhost, remote clients won’t be able to connect to our application.

To test your application, type:

node hello.js

You will receive the following output:

Server running at http://localhost:3000/

Note: Running a Node.js application in this manner will block additional commands until the application is killed by pressing CTRL+C.

To test the application, open another terminal session on your server, and connect to localhost with curl:

curl http://localhost:3000

If you get the following output, the application is working properly and listening on the correct address and port:

Hello World!

If you do not get the expected output, make sure that your Node.js application is running and configured to listen on the proper address and port.

Once you’re sure it’s working, kill the application (if you haven’t already) by pressing CTRL+C.

Step 3 — Installing PM2

Next let’s install PM2, a process manager for Node.js applications. PM2 makes it possible to daemonize applications so that they will run in the background as a service.

Use npm to install the latest version of PM2 on your server:

sudo npm install pm2@latest -g

The -g option tells npm to install the module globally, so that it’s available system-wide.

Let’s first use the pm2 start command to run your application, hello.js, in the background:

pm2 start hello.js

This also adds your application to PM2’s process list, which is outputted every time you start an application:

[PM2] Spawning PM2 daemon with pm2_home=/home/sammy/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /home/sammy/hello.js in fork_mode (1 instance)
[PM2] Done.
│ id │ name               │ mode     │ ↺    │ status    │ cpu      │ memory   │
│ 0  │ hello              │ fork     │ 0    │ online    │ 0%       │ 25.2mb   │

As indicated above, PM2 automatically assigns an App name (based on the filename, without the .js extension) and a PM2 id. PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

Applications that are running under PM2 will be restarted automatically if the application crashes or is killed, but we can take an additional step to get the application to launch on system startup using the startup subcommand. This subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots:

pm2 startup systemd

The last line of the resulting output will include a command to run with superuser privileges in order to set PM2 to start on boot:

[PM2] Init System found: systemd
[PM2] To setup the Startup Script, copy/paste the following command:
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u sammy --hp /home/sammy

Run the command from the output, with your username in place of sammy:

sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u sammy --hp /home/sammy

As an additional step, we can save the PM2 process list and corresponding environments:

pm2 save

You have now created a systemd unit that runs pm2 for your user on boot. This pm2 instance, in turn, runs hello.js.

Start the service with systemctl:

sudo systemctl start pm2-sammy

If at this point you encounter an error, you may need to reboot, which you can achieve with sudo reboot.

Check the status of the systemd unit:

systemctl status pm2-sammy

For a detailed overview of systemd, please review Systemd Essentials: Working with Services, Units, and the Journal.

In addition to those we have covered, PM2 provides many subcommands that allow you to manage or look up information about your applications.

Stop an application with this command (specify the PM2 App name or id):

pm2 stop app_name_or_id

Restart an application:

pm2 restart app_name_or_id

List the applications currently managed by PM2:

pm2 list

Get information about a specific application using its App name:

pm2 info app_name

The PM2 process monitor can be pulled up with the monit subcommand. This displays the application status, CPU, and memory usage:

pm2 monit

Note that running pm2 without any arguments will also display a help page with example usage.

Now that your Node.js application is running and managed by PM2, let’s set up the reverse proxy.

Step 4 — Setting Up Nginx as a Reverse Proxy Server

Your application is running and listening on localhost, but you need to set up a way for your users to access it. We will set up the Nginx web server as a reverse proxy for this purpose.

In the prerequisite tutorial, you set up your Nginx configuration in the /etc/nginx/sites-available/ file. Open this file for editing:

sudo nano /etc/nginx/sites-available/

Within the server block, you should have an existing location / block. Replace the contents of that block with the following configuration. If your application is set to listen on a different port, update the highlighted portion to the correct port number:

server {
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

This configures the server to respond to requests at its root. Assuming our server is available at, accessing via a web browser would send the request to hello.js, listening on port 3000 at localhost.

You can add additional location blocks to the same server block to provide access to other applications on the same server. For example, if you were also running another Node.js application on port 3001, you could add this location block to allow access to it via

/etc/nginx/sites-available/ — Optional
server {
    location /app2 {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

Once you are done adding the location blocks for your applications, save the file and exit your editor.

Make sure you didn’t introduce any syntax errors by typing:

sudo nginx -t

Restart Nginx:

sudo systemctl restart nginx

Assuming that your Node.js application is running, and your application and Nginx configurations are correct, you should now be able to access your application via the Nginx reverse proxy. Try it out by accessing your server’s URL (its public IP address or domain name).


Congratulations! You now have your Node.js application running behind an Nginx reverse proxy on an Ubuntu 20.04 server. This reverse proxy setup is flexible enough to provide your users access to other applications or static web content that you want to share.

2 steps to import and export Databases in MySQL or MariaDB

Importing and exporting databases is a common task in software development. You can use data dumps to back up and restore your information. You can also use them to migrate data to a new server or development environment.

In this tutorial, you will work with database dumps in MySQL or MariaDB (the commands are interchangeable). Specifically, you will export a database and then import that database from the dump file.

Step 1 — Exporting a MySQL or MariaDB Database

The mysqldump console utility exports databases to SQL text files. This makes it easier to transfer and move databases. You will need your database’s name and credentials for an account whose privileges allow at least full read-only access to the database.

Use mysqldump to export your database:

mysqldump -u username -p database_name > data-dump.sql

username is the username you can log in to the database with
database_name is the name of the database to export
data-dump.sql is the file in the current directory that stores the output.

The command will produce no visual output, but you can inspect the contents of data-dump.sql to check if it’s a legitimate SQL dump file.

Run the following command:

head -n 5 data-dump.sql

The top of the file should look similar to this, showing a MySQL dump for a database named database_name.

SQL dump fragment
-- MySQL dump 10.13 Distrib 5.7.16, for Linux (x86_64)
-- Host: localhost Database: database_name
-- ------------------------------------------------------
-- Server version 5.7.16-0ubuntu0.16.04.1

If any errors occur during the export process, mysqldump will print them to the screen.

Step 2 — Importing a MySQL or MariaDB Database

To import an existing dump file into MySQL or MariaDB, you will have to create a new database. This database will hold the imported data.

First, log in to MySQL as root or another user with sufficient privileges to create new databases:

mysql -u root -p

You’ll see this output confirming the database creation.

Query OK, 1 row affected (0.00 sec)

Then exit the MySQL shell by pressing CTRL+D. From the normal command line, you can import the dump file with the following command:

mysql -u username -p new_database < data-dump.sql

username is the username you can log in to the database with
newdatabase is the name of the freshly created database
data-dump.sql is the data dump file to be imported, located in the current directory

If the command runs successfully, it won’t produce any output. If any errors occur during the process, mysql will print them to the terminal instead. To check if the import was successful, log in to the MySQL shell and inspect the data. Selecting the new database with USE new_database and then use SHOW TABLES; or a similar command to look at some of the data.

View list USB devices on Linux Ubuntu

On Ubuntu, you may (for one reason or another) wish to view information about all USB devices connected to the system. Unfortunately, Ubuntu doesn’t come with an official GUI USB tool that users can use to view this information efficiently.

Ubuntu list USB devices – Lsusb

The number one way an Ubuntu user can view all connected USB devices is with the lsusb command. This command literally means “list USB,” and it does exactly that — it lists all of your USB devices, their IDs, names, etc.

To get started, open up a terminal window on the Ubuntu desktop. To open up a terminal window on Ubuntu, press Ctrl + Alt + T on the keyboard. Or, search for “Terminal” in the app menu and launch it that way.

With the terminal window open and ready to use, execute the lsusb command in the terminal window. Once you enter it, it will print out detailed information about the USB devices connected to the system.


In the lsusb output, you’ll see “Bus,” followed by numbers, “Device,” more numbers, “ID,” some hex code (that’s your device’s ID code), and the name of the device. To locate any USB device, find the name at the end.

If you’d like to save this output to a text file for later reading, research, or easier viewing via your favorite text editor, pipe the output to a file using the > command-line modifier.

lsusb > ~/my-usb-devices.txt

At any time, you can view the “my-usb-devices.txt” file in the terminal with the cat command below.

cat ~/my-usb-devices.txt

Ubuntu list USB devices – Dmesg

Another way to view USB devices on Ubuntu is with the dmesg command. The dmesg tool is used primarily to view kernel logs on your system. As USB devices interact with your Ubuntu system, they’re talking to the Ubuntu Linux kernel, which means their information is in these logs.

To use dmesg, you must first open up a terminal window. To do this, press Ctrl + Alt + T on the Ubuntu desktop. Alternatively, search for “Terminal” in the app menu and launch it that way.

When the terminal window is open and ready to use, enter the dmesg command below with sudo privileges. Sadly, the Ubuntu Linux kernel logs cannot be viewed without root access, as dmesg interacts with system-level stuff.

sudo dmesg | grep usb

You’ll see an output of all USB-related information that has interacted with the Ubuntu kernel by entering this command. From here, use the output to find information on your USB devices.

Want to save the dmesg output to a text file for later reading, or to view it better in your favorite GUI text editor? Using the command below, redirect the output to a text file.

sudo dmesg | grep usb > ~/dmesg-usb-info.txt

With it redirected, you can view the text file using the cat command below. Or by opening up “dmesg-usb-info.txt” in your favorite text editor.

cat ~/dmesg-usb-info.txt

Ubuntu list USB devices – Usb-devices

A third way you can view USB device information on the Ubuntu desktop is with the usb-devices command. It is similar to the lsusb tool. However, it is a bit more intricate and provides a lot more information in a much more organized way.

To start, you must have a terminal window open up on the Ubuntu desktop. To open up a terminal window on the desktop, press Ctrl + Alt + T on the keyboard. Or, search for “Terminal” in the app menu and launch it.

With the terminal window open and ready to go, execute the usb-devices command. The output is long and prints out in detail, every single USB device connected to Ubuntu in a vertical list.

In this list, you’ll see several columns. T, D, P, S, S, S, C, and I. Each of these letters has tons of information about your devices. For example, to find out the vendor info of a connected USB, go to “P” and read the vendor and product info, etc.

To save the output of the usb-devices command to your Ubuntu system for later reading, or to access via your favorite GUI text editor, you can pipe the output using >.

usb-devices > ~/my-usb-devices-output.txt

At any time, if you want to view the “my-usb-devices-output.txt” file on your computer, execute the cat command below. Alternatively, double-click on “my-usb-devices-output.txt” in the Ubuntu file manager to view it in your favorite text editor.

Sửa lỗi khi yum trên CentOS 8 – Failed to download metadata for repo ‘AppStream’

Khi gõ lệnh YUM trên Cenos8 lỗi như sau

[root@vps~]# yum update
CentOS-8 – AppStream 70 B/s | 38 B 00:00
Error: Failed to download metadata for repo ‘AppStream’: Cannot prepare internal mirrorlist: No URLs in mirrorlist

Bước 1: Đi tới thư mục /etc/yum.repos.d/

[root@vps~]# cd /etc/yum.repos.d/

Bước 2: Thực hiện command sau để điều chỉnh file cấu hình

[root@vps~]# sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
[root@vps~]# sed -i 's|#baseurl=|baseurl=|g' /etc/yum.repos.d/CentOS-*

Bước 3: Thực hiện thao tác yum update

[root@vps~]# yum update -y

Code đếm ngược sử dụng jQuery sau đó lấy kết qủa từ AJAX

Cách seo của mấy đồng chí PTU là bắt người tải dữ liệu về phải truy cập vào 1 trang nào đó để lấy mã giải nén.

Dưới đây mình xin show 1 đoạn code hoạt động tương tự như các trang web lấy mã đó

Mã HTML đơn giản như sau, kèm thư viện jQuery

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Countdown and AJAX</title>
  <script src=""></script>

  <a href="#" id="startCountdown">Lấy mã</a>
  <div id="countdown"></div>
  <div id="ajaxResult"></div>

Code Javascript sử dụng jQuery

// thời gian đếm ngược
var seconds = 30;

function updateCountdown() {
    if (seconds &gt; 0) {
    setTimeout(updateCountdown, 1000);
} else {
// Sau 30 giây thì gửi POST AJAX
   type: 'POST',
   url: 'link-xử-lý-ajax',
   data: { key: 'value' }, // Thêm dữ liệu bạn muốn gửi
   dataType: 'json',
   success: function(response) {
      // Xử lý dữ liệu jSon trả về
      console.log('AJAX post successful:', response);
      // Hiển thị kết quả ra #ajaxResult 
      $('#ajaxResult').text('AJAX result: ' + JSON.stringify(response));
    error: function(error) {
      $('#ajaxResult').text('AJAX result: Lỗi');

// Xử lý khi bấm vào link
$('#startCountdown').on('click', function(event) {
    event.preventDefault(); // Prevent the default link behavior
// Bắt đầu đếm ngược khi người dùng bấm vào link

Cách cài đặt PIP trên CentOS 7

I. Introduction

What is PIP?

PIP is a package management system that simplifies the installation and management of software packages written in Python, such as those found in the Python Package Index (PyPI). PIP isn’t installed by default on CentOS 7, but the installation is pretty straightforward.
Khuyến mãi Black Friday

In this tutorial, AZDIGI will walk you through the steps required to install PIP on CentOS 7 using the package manager and cover some basics on installing and managing Python packages using PIP.

When installing python modules, you should prefer installing the python modules provided by the distribution using yum as they are tested to work properly on CentOS 7. In most cases, you should just use using PIP in a virtual environment. Python Virtual Environments allows you to install Python modules in an isolated location for a specific project rather than being installed system-wide. This way, you don’t have to worry about affecting other Python projects.

So, please continue to see part II for details on how to install and use it.

II. Implementation Guide

You can install PIP on CentOS 7 with the following 2 steps.

Step 1: SSH into your VPS

First, you need to SSH into your VPS as root, if you don’t know how to SSH, you can see the instructions below:

How to log in to Linux VPS via SSH protocol

Step 2: Install PIP and use PIP

1. Enable the EPEL repository

By default, PIP is not available in the CentOS 7 repositories. To install PIP, we need to enable the EPEL repository with the command:

yum install epel-release

2. Install PIP

Once the EPEL repository is enabled, we can install PIP and all its packages with the following command:

yum install python-pip

3. Check PIP

After successful installation, you use the following command to check the version of PIP and Python installed:

pip --version

[root@template ~]# pip --version
pip 8.1.2 from /usr/lib/python2.7/site-packages (python 2.7)

So my VPS has installed PIP 8.1.2 and Python 2.7.

4. Install development tools

Development tools are required to build Python Modules, you can install them as follows:

yum install python-devel
yum groupinstall 'development tools'
Cách cài PIP trên Centos 7

Cách cài PIP trên Centos 7

5. Manage Python Packages with PIP

First, to be able to see some instructions on how to use PIP, you can use the command:pip help

How to install PIP on Centos 7

Next, we’ll learn a few useful basic PIP commands. With PIP, we can install packages from PyPI, version control, local projects and distribution files. Normally, you would install packages from PyPI.

Install package

For example, if we want to install a package named twisted, we can do that with the following command:

pip install twisted

twist is an asynchronous networking framework written in Python.

Uninstall package

To uninstall a run package, you can use the following command:

pip uninstall twisted

Upgrade package

To upgrade the package, then you can use the command below:

pip install --upgrade

Search for package

To search for packages from PyPI, you can use the following corresponding command:

pip search "twisted"

List installed packages

To list installed packages, you can use the command:

pip list

List outdated packages

To list outdated packages, you can use the following corresponding command:

pip list --outdated

So you can grasp the basic commands to manage Python with PIP already.

III. Summary

I has shown you how to install PIP on a server using Centos 7 with just a few simple command lines. Installing PIP will help you easily manage Python and improve your VPS operation and use. Hopefully, this article will help you to install Let’s Encrypt SSL successfully!

Tạo javascript đếm ngược 10s, 30s, 90s

Code Html

<meta name="viewport" content="width=device-width, initial-scale=1">
p {
  text-align: center;
  font-size: 60px;
  margin-top: 0px;

<p id="countdown"></p>


Code Javascripts

var timeleft = 100;
var downloadTimer = setInterval(function(){
  if(timeleft <= 0){
    document.getElementById("countdown").innerHTML = "Finished";
  } else {
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
  timeleft -= 1;
}, 1000);

Cài đặt Python 3 trên Centos 7 và set làm mặc định

I. Introduction

What is Python?

Python is a powerful, high-level, object-oriented programming language created by Guido van Rossum. It’s easy to learn and is emerging as one of the best introductory programming languages for newbies. Python is completely dynamically typed and uses automatic memory allocation. Python has powerful high-level data structures and a simple yet effective approach to object-oriented programming. Python’s command syntax is a huge plus, its clarity, ease of understanding, and flexible typing make it an ideal language for scripting and application development in various fields on most platforms.

You can learn more about Python through each version and the structure and operating principles here.

II. Implementation Guide

To install Python 3, you can follow the following 3 installation steps.

Step 1: SSH into your VPS

First, you need to SSH into your VPS as root, if you don’t know how to SSH, you can see the instructions below:

How to log in to Linux VPS via SSH protocol

Step 2: Check your Python version

By default Python installed on Centos 7 will be Python 2.7.x version, you use the following command to check the version:

python --version

So now my VPS is using Python version 2.7.

So to upgrade to Python 3 version, go to step 3.

Step 3: Update the Yum management tool

yum -y update                    (Cập nhật yum)
yum -y install yum-utils         (Cài đặt yum utils)
yum -y groupinstall development  (cài đặt các công cụ phát triển CentOS giúp xây dựng và biên dịch phần mềm từ mã nguồn.)

Step 4: Install Python 3
To check and download the latest Python versions, you can visit the homepage here.

Since the standard yum repos don’t have the latest Python release, we will install the IUM (Inline with Upstream Stable) which will have the latest packages by running the following command:

yum install \ \

Now install Python 3, I will install Python 3.6 with the command:

yum -y install python36u

As shown above, I have successfully installed Python 3

As shown above, I have successfully installed Python 3

As shown above, I have successfully installed Python 3


Next, we will install PIP to manage software packages for Python.

yum -y install python36u-pip

Then we will install the Python development packages.

yum -y install python36u-devel

Finally, check the Python version you just installed.

python3.6 --version

Step 5: Set Python 3 as the default

Although we have successfully installed Python 3, the VPS will still use Python version 2.7.5 as default. To change the default version, do the following:

Check the location where Python 3 has just been installed, I previously installed Python 3.6 version, so I will use the following command:

which python3.6

The path will display as follows:

root@template bin]# which python3.6

Add the Alias in bash_profile.

This section means that we will add an Alias configuration so that when calling the python command, the system will load the specified path (here is Python version 3.6). You open and edit the bash_profile file with the command:

vi ~/.bash_profile

Insert the following navigation into the .bash_profile file.

Remember to replace /usr/bin/python3.6 with the path on your VPS.

alias python='/usr/bin/python3.6'

After editing, type :x to Save the configuration.

Reload .bash_profile

source ~/.bash_profile

Recheck the Python version .

python --version

As shown above, the default version has been changed to 3.6.8.

As shown above, the default version has been changed to 3.6.8.

III. Summary

So in this article, I showed you how to install Python 3 and set this new version of Python as the system default. With this upgrade, you will be able to use many new packages from Python because each new package is developed they have conditions attached to the supported version. Hope this article will help you to install it successfully!

If you find the article helpful, please share it widely.