How to Install Fail2ban on Ubuntu Server (Block Brute-Force Attacks Automatically)

Fail2ban: ban the bots automatically — Five wrong passwords, one hour in the sin bin.

Look at the login log of any server on the internet and you'll find thousands of failed attempts from addresses you've never heard of. SSH keys stop them getting in, but they still waste bandwidth and fill your logs. Fail2ban watches the log and, after a few failures from one address, bans it at the firewall for a while. It's set-and-forget.

Quick reference

TaskCommand
Installsudo apt install fail2ban -y
Settings file/etc/fail2ban/jail.local
Status of SSH protectionsudo fail2ban-client status sshd
Unban an addresssudo fail2ban-client set sshd unbanip 1.2.3.4
Restart after changessudo systemctl restart fail2ban

1. Install it

sudo apt install fail2ban -y
sudo systemctl enable --now fail2ban

On Ubuntu it starts protecting SSH straight away with sensible defaults.

2. Make a settings file

Never edit jail.conf — updates overwrite it. Create jail.local instead:

sudo nano /etc/fail2ban/jail.local

Paste:

[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5
ignoreip = 127.0.0.1/8 192.168.1.0/24

[sshd]
enabled = true

Save (Ctrl + O, Enter, Ctrl + X) and restart:

sudo systemctl restart fail2ban

3. Check it's working

sudo fail2ban-client status sshd

You'll see how many attempts it's seen and a list of banned addresses. On a server reachable from the internet, give it a day and come back — the list is rarely empty.

Bans that get longer

Add these to [DEFAULT] and repeat offenders are banned for longer each time:

bantime.increment = true
bantime.maxtime = 1w

Protecting other services

Fail2ban has ready-made rules ("jails") for Nginx, Postfix, WordPress and more. Add a section such as:

[nginx-http-auth]
enabled = true

ls /etc/fail2ban/filter.d shows every filter available.

Troubleshooting

You banned yourself. From another address (your phone's hotspot, say), or at the server's keyboard:

sudo fail2ban-client set sshd unbanip 203.0.113.5

Then add your address to ignoreip.

"Failed to access socket" or the service won't start. Usually a typo in jail.local. Run sudo fail2ban-client -d to see the error.

Status says 0 attempts on a server that gets scanned. Ubuntu 24.04 and later log to journald instead of /var/log/auth.log. Add backend = systemd under [DEFAULT].

Wrapping up

Install, write a short jail.local with your own network in ignoreip, restart. From then on anyone who gets a password wrong five times is shut out for an hour, and your logs stop filling up with junk.

Call us