Configuring Fail2Ban on VPS: Automatic Protection Against Brute-Force Attacks
TL;DR
In this guide, we will step-by-step configure Fail2Ban on your VPS for automatic protection against brute-force attacks on various services such as SSH, web servers (Nginx/Apache), mail services, and others. You will learn how to install, configure, and verify Fail2Ban's operation, significantly enhancing your server's security and preventing unauthorized access.
- Automatic blocking of attackers by IP address based on log analysis.
- Protection of key services: SSH, Nginx, Apache, Postfix, Docker containers.
- Detailed configuration of rules (jails), blocking time, and trigger conditions.
- Reduced server load and increased stability by cutting off malicious traffic.
- Step-by-step instructions with current commands and configuration examples for 2026.
- The guide includes sections on server preparation, installation, configuration, maintenance, and troubleshooting.
What we configure and why
In the modern internet, your server is constantly subjected to unauthorized access attempts. One of the most common threats is brute-force attacks, where attackers try to guess passwords for your services (e.g., SSH, FTP, web control panels) by repeatedly trying combinations. These attacks not only pose a security threat but can also significantly strain server resources, slowing down its operation or even making it unavailable.
We will configure Fail2Ban — a powerful tool for automatic protection against such attacks. Fail2Ban scans log files of various services (SSH, Apache, Nginx, Postfix, etc.) for suspicious entries indicating login attempts with incorrect credentials. Upon detecting multiple failed attempts from a single IP address within a specified time, Fail2Ban automatically blocks that IP address for a defined period, using firewall rules (e.g., via iptables or ufw).
As a result of the configuration, you will have a significantly more secure and stable server. Fail2Ban will operate in the background, continuously monitoring activity and automatically thwarting hacking attempts. This will free you from manual log monitoring and constant blocking of suspicious IP addresses, allowing you to focus on core tasks.
Alternatives: Cloud-managed vs Self-hosted
For many tasks, both cloud-managed solutions and the option of self-hosting on a VPS exist. For example, for hosting websites, you can use SaaS platforms or PaaS services, and for databases, managed cloud databases. However, when it comes to complete flexibility, data control, and cost optimization, self-hosted solutions on a VPS are often preferred.
- Full Control: You have complete control over the operating system, installed software, and configurations. This is critical for specific security, performance, or compatibility requirements.
- Cost-effectiveness: For many tasks, a VPS can be significantly cheaper in the long run compared to constantly rising cloud service bills, especially with stable loads.
- Confidentiality: You host your data on your own server, which can be important for projects with high privacy requirements or regulatory compliance.
- Learning and Experience: Setting up your own server is an excellent way to deepen technical knowledge, which is useful for developers and system administrators.
Configuring Fail2Ban is one of the fundamental steps in securing any self-hosted solution on a VPS, complementing standard measures such as using SSH keys and strong passwords.
What VPS configuration is needed for this task
Fail2Ban itself is a fairly lightweight application and does not require significant resources. The main load will depend on the number of services being protected, the volume of logs they generate, and the intensity of attacks. However, for comfortable operation and the ability to host other services on the same VPS, the following minimum configuration is recommended:
- CPU: 1 core. Modern processors with a clock speed of 2.0 GHz or higher will be more than sufficient.
- RAM: 1-2 GB. Fail2Ban consumes from several tens to 100-200 MB of RAM depending on the number of active "jails" and the volume of logs processed. Additional memory will be needed for the operating system and your other services.
- Disk: 20-40 GB NVMe/SSD. NVMe or SSD drives are significantly faster than traditional HDDs, which is important for fast operating system performance and log access. 20 GB is enough for the OS and Fail2Ban, but 40 GB will provide a reserve for logs and other applications.
- Network: 100 Mbit/s or 1 Gbit/s. A stable channel with good bandwidth is important for overall server operation, but for Fail2Ban, stability is more critical than raw speed.
For most scenarios where a VPS is planned to host several websites, a mail server, or light containers, a plan with 2 CPU cores, 4 GB RAM, and 80 GB NVMe/SSD will be optimal. This will provide sufficient performance and stability headroom.
You can consider a VPS with the specified characteristics for hosting your project. The main thing is to ensure that the provider offers reliable infrastructure and support.
When a dedicated server is needed, not a VPS
A dedicated server should be considered if:
- You require maximum performance and stability without any "neighboring" with other users.
- Your project generates very high load (e.g., a large game server, a high-load SaaS with thousands of users, big data processing).
- Specific hardware or configuration is required that is not available on a VPS.
- Maximum isolation and compliance with strict security/regulatory requirements are needed, where virtualization could be a potential risk.
For the task of protecting against brute-force attacks on typical services, a VPS will be more than sufficient. Upgrading to a dedicated server is justified if the project you are protecting has already outgrown the capabilities of a VPS.
Location: What it affects
The choice of VPS location affects several key aspects:
- Latency: The closer the server is to your target audience or to you, the lower the latency. This is critical for interactive applications, game servers, and websites where every millisecond matters.
- Legal aspects: The laws of the country where the server is located determine data processing rules, confidentiality, and other legal matters.
- Availability: Some regions may have better connectivity to certain parts of the world.
For protection against attacks, Fail2Ban's location does not play a direct role, but for the overall performance of your services, choose a location as close as possible to your main users.
Server preparation
Before proceeding with Fail2Ban installation, it is necessary to perform basic setup of a fresh VPS. These steps will enhance security and ease of administration.
1. Connecting via SSH
Connect to your VPS as the root user, using the IP address provided by your hosting provider:
ssh root@YOUR_IP_ADDRESS
Replace ВАШ_IP_АДРЕС with your server's actual IP.
2. System Update
Always start by updating the package manager and installed packages to the latest versions. This ensures you have current security patches and stable library versions. For Debian/Ubuntu-based systems (current for 2026):
sudo apt update && sudo apt upgrade -y
This command updates the list of available packages and then installs all available updates without prompting for confirmation.
3. Creating a new user with sudo privileges
Working as root is insecure. Let's create a new user and grant them sudo privileges:
adduser your_user # Creates a new user
usermod -aG sudo your_user # Adds the user to the sudo group
Replace ваш_пользователь with your desired name. After this, set a strong password for the new user.
4. Configuring SSH keys for the new user
Using SSH keys instead of a password significantly enhances security. First, generate keys on your local machine if you don't have them:
ssh-keygen -t ed25519 -C "[email protected]"
Then copy the public key to the server:
ssh-copy-id your_user@YOUR_IP_ADDRESS
Now you can connect as your_user:
ssh your_user@YOUR_IP_ADDRESS
5. Disabling SSH login for root and password authentication
After successfully logging in with the new user and SSH key, disable root login and password authentication in the SSH server. This will significantly enhance security:
sudo nano /etc/ssh/sshd_config
Find and change the following lines (or add them if missing):
PermitRootLogin no
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
Save the changes (Ctrl+X, Y, Enter) and restart the SSH service:
sudo systemctl restart sshd
IMPORTANT: Before disabling, make sure you can log in with the new user and SSH key! Keep the current root session open until you verify login via the new user.
6. Configuring the firewall (UFW)
A firewall is necessary to restrict access to server ports. UFW (Uncomplicated Firewall) is easy to configure. Install it if it's not already installed:
sudo apt install ufw -y # Install UFW
sudo ufw allow OpenSSH # Allow SSH (port 22 by default)
sudo ufw allow 80/tcp # Allow HTTP
sudo ufw allow 443/tcp # Allow HTTPS
sudo ufw enable # Enable the firewall
sudo ufw status # Check status
Be sure to allow SSH, otherwise you will lose access to the server after enabling UFW. Also add rules for any other services you plan to use (e.g., 25/tcp for SMTP, 53/udp for DNS, etc.).
Software Installation — Step-by-Step
Now that the server is prepared, let's proceed with Fail2Ban installation. We will use the official repositories for Debian/Ubuntu, which ensures stability and ease of updates.
1. Fail2Ban Installation
Fail2Ban is available in the standard repositories of most Linux distributions. For Debian/Ubuntu (current as of 2026, Fail2Ban version 1.0+):
sudo apt update # Update package list
sudo apt install fail2ban -y # Install Fail2Ban
After installation, Fail2Ban will automatically start and be enabled on system boot.
2. Checking Fail2Ban Status
Ensure that the Fail2Ban service is running:
sudo systemctl status fail2ban # Check service status
The output should show active (running). If not, try starting it manually:
sudo systemctl start fail2ban # Start the service
sudo systemctl enable fail2ban # Enable autostart on boot
3. Installing Additional Tools (Optional, but Recommended)
For more convenient log monitoring and working with text files, htop and nano might be useful (if not installed):
sudo apt install htop nano -y
htop is an improved interactive process manager, and nano is a simple text editor.
4. Fail2Ban Structure Overview
Fail2Ban stores its configurations in the /etc/fail2ban/ directory. Key files:
jail.conf: The main configuration file with default settings. It should not be modified directly.jail.d/: Directory for custom configurations. This is where we will create our.conffiles.jail.local: A custom file that overrides settings fromjail.conf. It is recommended to use it or files injail.d/.filter.d/: Contains predefined filters for various services.action.d/: Contains predefined actions (e.g., blocking viaiptables).
We will work with the jail.local file or create new files in jail.d/ to avoid losing changes during Fail2Ban updates.