Stop Brute-Force Attacks: Fail2ban Setup Guide for Linux

Terminal showing Fail2ban banning IPs on a Linux server

Even after locking down SSH with key-based authentication and a custom port, bots will still hammer whatever’s listening — they just won’t get anywhere. Fail2ban is the piece that turns those repeated failed attempts into automatic bans, so your server actively fights back instead of quietly logging attack after attack.

This guide walks you through installing Fail2ban, configuring it properly, and confirming it’s actually catching attempts — in about 10 minutes.

Important note: This guide uses commands for Debian-based distributions (Debian, Ubuntu, and derivatives). If you’re running a RHEL-based distro (CentOS, Fedora, Rocky, AlmaLinux) or Arch, the core concepts still apply, but package manager commands and some paths will differ.

What Fail2ban actually does

Fail2ban watches your log files for patterns that look like abuse — most commonly, repeated failed login attempts on SSH. Once an IP crosses a threshold you define, Fail2ban tells your firewall to block that IP for a set amount of time.

Each service it protects (SSH, Nginx, Postfix, etc.) is configured as a separate jail. A jail defines what log to watch, what pattern counts as a failure, how many failures trigger a ban, and how long the ban lasts.

Install Fail2ban

sudo apt update && sudo apt install fail2ban

Once installed, Fail2ban starts protecting SSH immediately using its default settings. The defaults are a reasonable starting point, but not ideal for every setup — the next section shows you how to customize them.

Let’s confirm that Fail2ban is running properly:

sudo fail2ban-client status

If fail2ban-client status comes back with a connection error, the service may not have started — run the following command and try again:

sudo systemctl enable --now fail2ban

Never edit jail.conf — use jail.local

Fail2ban’s default configuration lives in /etc/fail2ban/jail.conf. Don’t edit this file directly — it gets overwritten whenever Fail2ban is updated, silently wiping out your changes.

Instead, create jail.local, which Fail2ban always reads after jail.conf and uses to override any setting you redefine:

sudo touch /etc/fail2ban/jail.local

All of your custom configuration from this point on goes in jail.local.

Configure the SSH jail

Open jail.local and add the [sshd] section:

[sshd]
enabled = true
# replace port with your actual SSH port if you changed it
port = 2222
maxretry = 5
findtime = 10m
bantime = 1h

A quick breakdown of what each setting controls:

This is a reasonable starting point for most personal or small production servers. If you want repeat offenders banned for progressively longer periods, Fail2ban supports a bantime.increment setting — worth exploring once the basics are working. The official jail.conf reference documents this and every other jail option in full.

If you changed the SSH port from the default value 22 to something else like 2222, you must restart fail2ban, it is required:

sudo systemctl restart fail2ban

Whitelist your own IP

This step gets skipped more often than it should, and skipping it means you can lock yourself out with your own failed login attempts. Add your IP (and localhost) to the ignoreip setting near the top after the default section of jail.local:

[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 YOUR_IP_HERE

Replace YOUR_IP_HERE with your actual public IP address. If your IP changes frequently, consider whitelisting a VPN IP instead, or revisit this setting periodically.

Reload and verify the status of the jail

sudo fail2ban-client reload

Confirm the reload is OK and check the status of your SSH jail specifically:

sudo fail2ban-client status sshd

The sshd status output shows the number of currently failed and banned IPs, along with the list itself — right now it should be empty on a freshly configured server.

Test it (safely)

Before trusting Fail2ban to protect you, confirm it actually works. From a second machine (or a second terminal, using a different session), intentionally fail an SSH login a few times in a row — enough to cross your maxretry threshold.

Then check the jail status again:

sudo fail2ban-client status sshd

You should see the test IP listed as banned. You can also confirm Fail2ban is picking up the attempts in its own log:

sudo tail -f /var/log/fail2ban.log

Safety note: don’t run this test from the same IP you rely on to manage the server, unless you’ve already confirmed your whitelist in the previous step is working. If you’re testing from your own connection, keep a separate, already-authenticated session open in case you accidentally ban yourself.

Unban an IP

Mistakes happen — if you ban an IP you didn’t mean to (including your own), reverse it with:

sudo fail2ban-client set sshd unbanip <ip>

This is fully recoverable, so don’t hesitate to test bans aggressively while you’re getting Fail2ban configured — nothing here is permanent.

Extend Fail2ban beyond SSH

SSH is the most common target, but Fail2ban ships with jail definitions for plenty of other services — Nginx and Apache authentication, Postfix, WordPress login pages, and more. If any of those run on your server, they’re worth enabling using the same jail.local pattern covered above.

Extending Fail2ban to Nginx: catching path scanners

So far we’ve been using Fail2ban to protect SSH. But SSH isn’t the only service getting probed on your server — if you’re running Nginx, your access log is almost certainly full of bots looking for things that aren’t there: /wp-login.php, /.env, /phpmyadmin, /.git/config. None of that traffic touches SSH, so your SSH jail never sees it.

Fail2ban isn’t limited to SSH — it can watch any log file and ban based on any pattern you define. Let’s put that to use with a custom filter that watches Nginx for repeated 404s and bans the source.

Prerequisites

If you don’t already have Nginx running:

sudo apt install nginx
sudo systemctl enable --now nginx

Skip this if Nginx is already installed on your server.

Step 1: Write the filter

Fail2ban filters are just regex patterns that tell it what a “bad” log line looks like. Create a new filter file:

sudo nano /etc/fail2ban/filter.d/nginx-404.conf
[Definition]
failregex = ^<HOST> -.*"(GET|POST|HEAD).*HTTP.*" 404
ignoreregex =

<HOST> is a special Fail2ban placeholder — it tells the engine where to extract the offending IP address from the log line. The rest of the pattern matches Nginx’s standard combined log format, looking specifically for requests that returned a 404. If you’ve customized log_format, it may not match.

Step 2: Create the jail

Now tell Fail2ban to actually use that filter. Open your jail config:

sudo nano /etc/fail2ban/jail.local

Add:

[nginx-404]
enabled = true
port = http,https
filter = nginx-404
logpath = /var/log/nginx/access.log
maxretry = 15
findtime = 120
bantime = 86400

This says: if an IP triggers 15 or more 404s within a 2-minute window, ban it for 24 hours.

Important: The 15 404s in 2 minutes threshold should be understood as a behavioral heuristic, not proof of malicious activity. Legitimate clients can occasionally generate large numbers of 404 responses due to broken links, outdated URLs, or application misconfiguration. The rule deliberately uses suspicious request patterns as a proxy for automated scanning, so false positives are possible. Monitor your logs after enabling the jail and adjust maxretry and findtime according to your server’s normal traffic patterns.

Step 3: Whitelist yourself first

You already whitelisted your IP earlier — if you skipped that step, do it now before continuing.

Before you test anything, make sure you can’t accidentally ban your own IP — you’re about to generate a burst of 404s on purpose. In jail.local, under [DEFAULT]:

[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 YOUR_IP_HERE

Skip this step and you’ll lock yourself out mid-demo. Ask me how I know.

Step 4: Validate the regex before trusting it

Never enable a jail on a filter you haven’t tested — a bad regex either matches nothing (silent failure) or matches everything (mass ban). Fail2ban ships a tool for exactly this:

sudo fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-404.conf

You should see a match count greater than zero if your server has any existing 404 traffic in its logs. If it comes back at zero, double-check your log format matches what the regex expects.

Step 5: Reload Fail2ban and trigger a ban

sudo fail2ban-client reload

Now let’s actually earn a ban. From a machine that is not on your whitelist (or temporarily remove yourself from it to test):

for i in {1..20}; do curl -s -o /dev/null http://YOUR_SERVER/nonexistent-$i; done

Then check the jail status:

sudo fail2ban-client status nginx-404

You should see the triggering IP listed under “Banned IP list.”

That’s Fail2ban actively defending a service it was never protecting an hour ago — with about ten lines of config.

Why this matters

SSH gets all the attention in Fail2ban tutorials because it’s the obvious target. But your web server is just as exposed, and it’s usually taking far more hostile traffic than SSH ever sees — it’s just quieter, because a 404 doesn’t feel like an attack the way a failed SSH login does. It can be reconnaissance: repeated requests for paths such as /wp-login.php, /.env, or /.git/config are often signs of automated scanning, even though each request simply produces a 404.

Monitoring Fail2ban long-term

Pair Fail2ban with the basic logging habits from the server-hardening guide — keeping an eye on journalctl -u ssh.service -f alongside /var/log/fail2ban.log gives you visibility into both the attempts and the automatic response to them.

If you want to be notified in real time rather than checking logs manually, Fail2ban supports email notifications on ban events via the action setting in jail.local — a good next step once the core setup is stable.

Fail2ban takes about 10 minutes to set up properly and turns your server from passively logging brute-force attempts into actively shutting them down. Combined with the hardening steps from the previous guide, this covers the majority of opportunistic attacks your server will face.

Next, a look at the three firewall tools you will meet on a Linux server: UFW vs iptables vs nftables: Which Linux Firewall Should You Use?


Discover more from vigilnix

Subscribe to get the latest posts sent to your email.

Ismaël Qouiqa Avatar

Written by

2 responses to “Stop Brute-Force Attacks: Fail2ban Setup Guide for Linux”

  1. […] Fail2ban — which we set up in the previous post to stop brute-force attacks — reacts to abuse: it watches your logs, notices repeated failures, and bans the source. A firewall works differently: it doesn’t wait for bad behavior, it enforces policy from the start. If a port isn’t explicitly allowed, connections to it are blocked before any service gets a chance to respond — there’s no login attempt to fail, no request to log, because the traffic never reaches anything in the first place. […]

  2. […] For a more detailed setup, see Stop Brute-Force Attacks: Fail2ban Setup Guide for Linux. […]

Leave a Reply