Introduction to VPS

1. What is a VPS server? (Virtual Private Server)

A virtual private server (VPS) is the perfect solution for those who need more control and flexibility than traditional hosting. VPS provides dedicated resources, greater security (correctly configured) and performance. It's a great choice for growing businesses, developers, and high-traffic websites. With VPS, you can easily scale your resources, manage applications and enjoy the independence of a dedicated server at an affordable price.

2. Why choose VPS instead of Shared Hosting?

Choosing VPS over shared hosting provides greater performance, security and flexibility. VPS gives you dedicated resources, which eliminates the risk of performance degradation by other users. It also offers full control over the server configuration and the ability to adapt resources to individual needs. Perfect for websites with higher traffic and companies that need stability and better data protection.

Moreover, when we use Shared Hosting services, we are able to run only one application assigned to a given hosting. We are thus technologically and cost-limited. Currently, the prices of Shared Hosting usually start from PLN 100 per year, while we can get a cheap VPS from as little as PLN 260 per year.

Are you asking where the savings of VPS over Shared Hosting appear? , as I mentioned earlier, on Shared Hosting we are able to run only one website, while VPS allows us to host an unlimited number of websites, limited only by our system resources.

It is also worth mentioning at the very end a very an important aspect which are the technological limitations of Shared Hosting. Over 90% of Shared Hosting providers are mainly focused on supporting Wordpress applications, which may make it impossible to run applications based on technologies such as React, Laravel, Django or .NET on such a service.

3. Where to buy a VPS server?

It is worth considering purchasing a VPS server from reputable providers such as OVH, Hetzner, Hostinger, Google or DigitalOcean. The key criteria are reliability, performance and technical support. Be sure to pay attention to the location of servers, scalability options and the availability of additional services such as backups, external firewall and DDoS protection. Compare the offers and choose the solution that suits your needs.

I personally serve my clients using Hostinger solutions (unsponsored article, unfortunately...).

The company offers offers us VPS at very affordable prices. We can choose from server locations around the world. Additionally, we have access to functionalities such as External Firewall, Weekly Backups (included in the price), Basic server monitoring, and basic antivirus.

Buy a VPS server

Linux login and update

Before you start with VPS

Before we start the safe configuration of our VPS server, you must have one very important issue in mind, namely the fact that Linux as an operating system has many different distributions that differ not only in their applications, but also and architecture. This means that, depending on the selected distribution, it may be necessary to use other commands to perform certain operations.

I personally use Ubuntu and this tutorial was written with Ubuntu users in mind. If you use another Linux distribution, nothing is lost.

You can still use this material, but you will have to find the appropriate commands for your operating system distribution in several places.

In addition, this article assumes that you have already deployed your Linux and are able to log in to it using SSH.

If you do not know how to do this yourself, I invite you to this article in which, together, step by step we install our Linux on the servers of an external VPS Server Distributor

1. How to log in to Linux? (SSH)

SSH (Secure Shell) is a network protocol that ensures secure communication between computers. It enables remote login, server management and file transfer, while protecting your data with encryption. SSH is indispensable for system administrators and developers, guaranteeing the privacy and integrity of information. It is a standard server management tool used in various IT environments.

To log in to your machine for the first time, execute the command (Use a terminal e.g. Powershell or Terminus)

ssh -p 22 root@ip-of-our-vps

When you log in for the first time, you will be asked to confirm the creation of the keys. After acceptance, you will be connected to your server.

Login as Root

You have currently logged in to your VPS server as Root (Super User). This practice is never recommended until you are an advanced user. Nevertheless, it is required when first configuring our server.

Later At this stage, we will implement basic security rules, completely blocking the possibility of logging in remotely to the system as Root.

2. How to update Linux? (Ubuntu)

The first step after logging in to a new machine should be to update it. If you have already learned the basics of Linux, the following commands should be familiar to you.

sudo apt update && sudo apt upgrade -y

Don't know Linux commands yet?

At the beginning of your adventure with Linux Administration, many commands may be unfamiliar and incomprehensible to you.
Don't be afraid, I didn't know many things when I started. Fortunately, we live in times with access to the Internet :)< br />There are many Shell Explain applications available on the Internet!

Go to shell.how →

Linux Firewall Configuration

Before you start, configure the Firewall

A firewall is an essential tool for controlling traffic coming in and out of your server. It is the first element of the entire system that receives all queries directed to your VPS server. A properly configured firewall can almost completely protect our system, but also if it is programmed too aggressively, we can block access to our network applications.

Before we get to the heart of the matter, it is worth knowing that we distinguish 2 types of firewalls:

  • External firewall (e.g. the one from the VPS provider)
  • Internal Firewall (active directly on our Linux)
External + Internal Firewall Configuration

The firewall acts as a kind of filter through which all queries directed to our server pass. It's up to us what traffic we allow. The firewall configuration is mainly based on access to individual ports in our system.

If you have problems running any application on the production server, first make sure that the port on which the application is transmitting is not blocked by one of the above-mentioned Firewalls

1. How to configure an external firewall?

If your VPS server provider does not offer an External Firewall, you can skip this step without any problems.
It is not necessary due to the fact that the internal Linux implementation of the Firewall' and it should be 100% sufficient.

The external firewall serves as additional security, which facilitates work mainly via the GUI.

Below is an example configuration of my external firewall at Hostinger provider.

  • It blocks access to all available TCP and UDP ports
  • Opens ports 80 and 443 (Web Applications)
  • Opens port 22 for the specified IP address (SSH with IP filter)
Internal Firewall Configuration

2. How to configure a Linux firewall? (UFW)

It's time for what tigers like the most, i.e. a return to the old and proven Command Line.
Below we will implement exactly the same solution as in the External Firewall.

For this purpose, we will use a simplified Linux Firewall management interface called UFW (Uncomplicated Firewall)
We will do the following:

  • We will block all incoming connections
  • We will unblock all outgoing connections
  • We will allow SSH access (Port 22)
  • We will allow access to ports 80 and 443

Installation of Uncomplicated Firewall

sudo apt install ufw

UFW Basic Rules Configuration

sudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw allow sshsudo ufw allow 80/tcpsudo ufw allow 443/tcp

Enable UFW

sudo ufw enablesudo ufw status

This way we managed to configure our internal Firewall in a safe way. We blocked access to all ports and allowed only access to SSH (Port 22) and ports 80, 443 on which our Reverse-Proxy will listen in the future in order to host our web applications.

IP Filtration for Port SSH(22)

If you decide to implement access to port 22 only using selected IPs using UFW, you may lose access to your server

This may happen if your Internet provider rotates IP addresses. Before you decide undergoing such a procedure, it will make 100% sure that your IP address is statically defined.

If it turns out that your IP address is dynamic, you can always implement IP filtering for SSH Port(22) using External Firewall.

New User with sudo permissions + SSH Key

1. How to create a new sudo Linux user?

A user with sudo privileges is also called a Superuser due to the ability to perform actions reserved only for Root. An account that has such permissions can be called an administrative account.

Create new user

sudo adduser username

Grant sudo permissions to the new user

sudo usermod -aG sudo username

2. How to create SSH keys for a new Linux user?

In the next section, we will increase the security of our server by allowing login to it only using SSH keys.
At the beginning of this tutorial, you used your password for a given user to log in to the server via SSH.

This approach is dangerous because in extreme cases, when your password is compromised, an unauthorized person will gain access to your VPS server, thanks to which they will be able to do whatever they want with it.

The solution to this problem is to limit SSH login to only the use of SSH Keys.
In this case, as long as your key file is safely stored with you, no one will be able to log in to your server via SSH.

This tutorial assumes that you do not have any SSH keys on your Local Computer yet

On your local computer, run the following command to generate an SSH key pair (e.g. Windows, Mac)

ssh-keygen -t rsa -b 4096

Using this command will create two files on your local machine at the following path C:\Users\user-name\.ssh

  • id_rsa - Your private SSH key (Place on VPS)
  • id_rsa.pub - Public SSH Key (Use to log in)

Backup SSH Keys

It is very important to save your local id_rsa file on some portable disk, because if it is deleted or malformed, you will not be able to log in to your VPS server!!!

3. How to add SSH keys to a new Linux user on a VPS?

The next step is to properly prepare the Linux user account that you created in the first subsection of this stage.

We have the following steps to perform:

  1. Copying the Public Key from the Local Computer to our VPS Server
  2. Adding the Public Key to our new Linux User's account
  3. Test the configuration (Necessary)

On the VPS server, you must execute the following commands to create an SSH directory for the new User

mkdir /home/new-username/.ssh

Change the new directory's affiliation from Root to New User

sudo chown -R n-n-user:n-n-user /home/n-n-user/.ssh

On your local computer, run the following command to copy the Public Key to the VPS Server

scp C:/Users/username/.ssh/id_rsa.pub new-username@ip-server-vps: ~/.ssh

You will be asked to enter the password for the new user you created.
When everything goes well, you should have an id_rsa.pub file in your new Linux user's .ssh folder.

The final step is to add the SSH Key to the Authorized Keys on the VPS Server

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keysrm ~/.ssh/id_rsa.pub

In this way, you have correctly added your SSH Key to the Authorized Keys on the server.
In the next stages of the guide, you will learn how to activate the ability to log in using SSH Keys

Secure SSH Configuration (Secure Shell)

1. How to change the default SSH port?

SSH (Secure Shell) is a protocol used to remotely manage a server. Default SSH settings can be potentially dangerous, so it is worth configuring them appropriately.

The default SSH port (22) is often the target of attacks. Changing the port to a different one may make it more difficult for potential hackers to access the server.

Hint !

Remember that this is not a necessary step, you can also filter the acceptable IPs to port 22 using Firewall
If you are a more advanced user, you can also consider using the Port Knock method.
Remember that the number of possible solutions are unlimited and the only limitations may be those related to lack of experience.

Make a backup of your sshd_config file (just in case)

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

Open the sshd_config document with your chosen Linux text editor (e.g. nano)

sudo nano /etc/ssh/sshd_config

Locate the line containing the text #Port 22

port 2200 <-- Remove the # sign and enter a new SSH port (e.g. 2200)

Hint !

If you use the nano text editor like me, you can use the following shortcuts:

CTRL + W <-- Search
CTRL + S <-- Save File
CTRL + X <-- Exit Editor

Most useful shortcuts should be visible at the bottom of the screen when you open the editor.

Save changes

Warning!

Before making changes, remember to make appropriate changes to your External and Internal Firewall to allow connections to the new SSH port. Otherwise, you will be without access to the server...

Remember that after making new rules, restart UFW to implement the new configuration!!! (Command in the next step)

2. How to disable root logging in Linux?

Logging in as root directly via SSH is unsafe. A better solution is to use a user account with sudo permissions.

To lock, reopen the sshd_config file and add the following information to the end of the file

PermitRootLogin no <-- Add to end of file or find in file

3. How to enable logging in using SSH keys in Linux?

Why we should use SSH keys was explained in the previous chapter. However, we still don't know how to allow their use.

Reopen the sshd_config file and make sure the specified option is enabled

PubkeyAuthentication yes <-- There cannot be a # sign in front of it

4. How to restart SSH service in Linux?

In order to implement the changes we have made, you will need to restart the SSH service

Run the following command on your Linux VPS

sudo systemctl restart ssh

5. How to use an SSH key to log in to Linux?

Before we continue, make sure your SSH keys have been successfully configured.

Open a new Terminal on your Local Computer and do the following command

ssh -p new-ssh-port n-n-user@ip-vps -i path-to-id_rsa

Where is the id_rsa file?

Your id_rsa file can be found after entering the command “ ~/.ssh” (Local Computer) in the terminal.

Are SSH keys working properly?

If everything was configured correctly when logging in to SSH with a Key, you should not be asked for a password.
If you were asked for a user password anyway, it means that you made a mistake somewhere.

Remember not to confuse the request for the user' s password with the request for the password for the id_rsa key
If you entered phasphrase when creating the keys, you will then be asked for the password for your id_rsa key, which is normal behavior.

When you are 100% sure that your SSH keys are working properly, you can proceed to the next section.

6. How to block SSH login to Linux using a password?

This operation is optional, but its implementation significantly increases the security of your VPS server.

Open the sshd_config file again and check what directory it contains in the first line.
In my case it is /etc/ssh/sshd_config.d

Start of sshd_config file

Go to the above directory and check what files it contains

Go to directory

cd /path/to/your/directory

List directory

ls-la

In my case I got the following results

Directory /etc/ssh/sshd_config.d

The indicated files are additional SSH configuration files usually created by your VPS server provider.
Check what information your files contain.
In my case, the file that needs to be changed looks like this following

Directory /etc/ssh/sshd_config.d

Edit each file that contains the above line of text by changing the option "yes" to "no"

Edit files

sudo nano filename

Replace “yes” with “no”

PasswordAuthentication no

Before you restart your SSH service

Before performing the above operation, make sure that your SSH Keys are working properly.
Otherwise, you will permanently lose access to your VPS and the data contained in it.

If it is a test server nothing is lost, just deploy it again.
Remember not to perform such actions on the production server if you don' t feel up to it yet!!!

Restart SSH service

sudo systemctl restart ssh

At this point we should log out of the root shell and start using our newly created Administrator account.

Fail2Ban Installation and Configuration

1. What is Fail2Ban?

Fail2Ban is a tool that protects servers against unauthorized access. Monitors system logs to detect suspicious activity, such as multiple failed login attempts. If such behavior is detected, Fail2Ban blocks the source IP address for a specified period of time, reducing the risk of brute-force attacks. It works with various services, such as SSH, Apache, and Postfix, providing flexible and effective protection.

In the following part of this course, you will learn the basics of configuring and using this tool.

How does Fail2Ban work?

Fail2Ban is a tool that is mainly based on managing your Internal Firewall. File2Ban constantly monitors your system logs to detect unwanted behavior. When a given event from a specific IP address is performed too many times, Fail2Ban will automatically add a new rule to your Firewall blocking a given IP address for a specified amount of time. When the banning period ends, the given rule will be automatically removed from the Internal Firewall.

2. How to install Fail2Ban?

To install, execute the command (as sudoer)

sudo apt install fail2ban

Verify the installation by checking the F2B logs to make sure there are no errors

cat /var/log/fail2ban.log

Check the status of the F2B website

systemctl status fail2bansudo fail2ban-client status

3. How to configure Fail2Ban?

The Fail2Ban service stores its configuration data in the jail.conf file, which can be found in the /etc/fail2ban directory.
Before we move on, let's check what is hidden in the first 20 lines of this file.

Check the beginning of the file /etc/fail2ban/jail.conf

head -20 /etc/fail2ban/jail.conf
Directory /etc/ssh/sshd_config.d

It is easy to notice that at the beginning of the file all fields are marked as comments, as evidenced by the # symbol at the beginning of each line.
This data serves as an introductory manual for the Fail2Ban tool.

The most important information is that you should NOT change the jail.conf file directly, but make any changes using the jail.local file

File comparison - jail.conf vs jail.local

The jail.conf file belongs to the installation package of the Fail2Ban tool and is a file that is automatically overwritten with each update of the tool.
If you decided to perform F2B configuration in the jail.conf file, you would lose your setup with the next update of the tool.

Now that we have the basics covered, it's time to learn how to configure fail2ban.

Go to Fail2Ban folder

cd /etc/fail2ban

Copy jail.conf to jail.local

sudo cp jail.conf jail.local

Open the jail.local file and start reading it

sudo nano -l jail.local

By viewing the jail.local file, we can see that line 41 is the beginning of the basic Fail2Ban configuration.

If we go a little lower, we can find out that:

  • The maximum number of failed login attempts can be 5 (Line 10 8)
  • The time window for detecting failed login attempts is 10m (Line 105)
  • IP banning time is 10m (Line 101)

The above parameters tell us that if the client makes 5 incorrect login attempts within 10 minutes, his IP will be banned for 10 minutes. After this time, his IP address will be unblocked again.

4. How to read Fail2Ban logs?

Fail2Ban also has its own log system which is correlated with other most important system logs.
With its help we can check all the most important events that have been recorded by our system.

How to open the Fail2Ban log?

sudo cat /var/log/fail2ban.log

How to open the SSH log?

sudo cat /var/log/auth.log

Spend 15 minutes on your own to analyze the above logs to thoroughly understand their nature.
Remember that you gain more knowledge through independent learning and dedicated exploration of the topics of your interests.
The most important thing is skillfully asking yourself questions: How?, Why?, What for? When?

Example questions:

  • How can I check the IP address of the person who recently tried to SSH login to my VPS?
  • How did the person authenticate with my VPS Server?
  • Has the IP address been successfully banned by Fail2Ban?

5. How to verify if Fail2Ban is working properly?

So far, we have already managed to acquire a really large and valuable piece of knowledge. However, theoretical knowledge and practical knowledge, especially in IT fields, often differ from the truth. Each time you implement a new solution on your server, you should be able to test whether the solution is working properly. The ability to install a given website is not difficult. The most important thing is the appropriate configuration of a given solution and its constant testing and improvement appropriate to the technologies we use.

In order to perform basic Fail2Ban tests, we will make several attempts to log in to our VPS Server using SSH.
In To do this, open a new terminal so that you can simultaneously access the terminal where you are connected to your VPS and an empty new window.

Hint

If you have disabled the ability to log in with a password in the Secure SSH Configuration subsection, you can:

1. Unlock the ability to log in with a password for the duration of the tests
2. Create a backup of your id_rsa key, and then edit your key so that it is different from the original one.

If you choose the second option, be sure to restore your id_rsa key to the backup version after completing the tests, otherwise you will permanently lose the ability to log in to your server

I would like to remind you once again how important it is to have at least several copies of your SSH keys in different places.

Make a new SSH connection (New Terminal)

ssh -p port-ssh n-n-user@ip-vps

If you chose the second method, which assumes a malformation of the id_rsa key, you should be asked for a password at this point.
Enter the incorrect password a maximum of 3 times.

Check Logs (Terminal Logged in to VPS)

sudo cat /var/log/fail2ban.logsudo cat /var/log/auth.log

The logs should include information about your IP address and failed login attempts.
Read these logs and make sure you understand what they mean.

Make 2 more login attempts (New Terminal)

ssh -p port-ssh n-n-user@ip-vps

At this point, if everything is working properly, your IP address should be blocked for 10 minutes. Unfortunately, if you do not have a second IP address, you must wait this time before you will be able to log in to your VPS server again. Just remember to restore a copy of your id_rsa file this time.

How to unblock IP in Fail2Ban Linux?

If you don' t feel like waiting for your IP to be unblocked, you can always share your Internet from a phone that will have a different IP
Run the command "sudo fail2ban-client set sshd unbanip

6. Fail2Ban Summary

In this chapter, we learned the minimal and basic configuration and operation of the Fail2Ban website. Due to the fact that this guide is intended to introduce you to the world of independent VPS configuration, I am not able to describe the details of this tool here.

I encourage you to explore it yourself. Remember that thanks to Google and Chat-GPT you will be able to discover all the secrets of this tool on your own. The knowledge you gain in this way will be consolidated in a much better way, because you will have to learn step by step how a given solution works.

Also, don't forget to constantly check my website, more will probably appear here in the future an extensive and comprehensive article on advanced configuration of the Fail2Ban service

ClamAV antivirus

1. What is ClamAV?

ClamAV, or Clam AntiVirus, is one of the most popular and comprehensive tools for detecting viruses in Linux systems. Its open-source nature, regular updates and the ability to integrate with a variety of systems make it an ideal choice for administrators who care about the security of their servers.

ClamAV was originally designed mainly for Linux systems, although it is also available for other platforms such as Windows and macOS. It offers a number of features that help detect and remove malicious software, including viruses, Trojans, malware and other threats. It consists of 3 basic elements:

  • ClamD: Daemon that is responsible for background scanning.
  • ClamScan: Command-line tool that allows you to manually scan files.
  • FreshClam: Service responsible for automatic virus database updates.

How does ClamAV work?

ClamAV works by comparing files with a virus signature database. This database is regularly updated by the community and developers, ensuring protection against the latest threats..

2. How to install ClamAV?

To install, execute the command (as sudoer)

sudo apt install clamav clamav-daemon

Restart your VPS server

sudo reboot

Update virus database

sudo freshclam

3. How to configure ClamAV?

The default ClamAV configuration should be fine for most users.
Still, edit the ClamAV configuration file to customize the settings to suit your needs.

Open the configuration file and read its contents

sudo nano /etc/clamav/clamd.confsudo nano /etc/clamav/freshclam.conf

If you have made any changes to the configuration, do not forget to restart the ClamAV website

sudo systemctl restart clamav-daemonsudo systemctl restart clamav-freshclam

4. How to scan a Linux system with ClamAV?

Directory Scanning

sudo clamscan -r /path/to/directory

Whole System Scan

sudo clamscan -r /

Whole System Scan (Show only infected files)

sudo clamscan -r --infected/

Whole System Scan (Save scan result)

sudo clamscan -r --infected / > ~/clamav_output.txt

Whole System Scan (Automatic Virus Removal)

sudo clamscan -r --infected --remove /

How to cancel a command in the terminal?

If your terminal is blocked by the currently running command, you can cancel it with CTRL + C

Summary

A few final words

At the very beginning, I would like to thank you for your patience and congratulate you on your perseverance. I hope this article was understandable to you. If you have any problems, you can always contact me privately for help.

As you can see, safely configuring your new VPS server is not as difficult as it seems. In fact, this operation is mainly based on certain duplicated patterns, which are updated with safer solutions over time. You can use the server we have prepared today to host your first applications. It is safely configured and should not allow hacking.

This article is the first in the series of the "From Zero to DevOps" course. Remember that this is only the first stage in which we have jointly prepared the ground for building our web application. We focused primarily on the basics, i.e. ensuring that our server infrastructure is safe from the first start.

In the next parts of the course, we will learn the next steps to complete the deployment of a web application using Docker technology. We will learn the basics of safely creating Docker images, learn the details of the Docker Compose command and finally make our application available to the world using the Traefik tool. There's a lot of fun ahead of us. Don't forget to follow my website to stay up to date with the latest courses.