Skip to content

Instantly share code, notes, and snippets.

@Rankarusu
Last active February 10, 2025 09:02
Show Gist options
  • Save Rankarusu/23a04ed587b05c6f2b701f2457a127b0 to your computer and use it in GitHub Desktop.
Save Rankarusu/23a04ed587b05c6f2b701f2457a127b0 to your computer and use it in GitHub Desktop.
Setting up fail2ban with nginx proxy manager running via docker

Setting up fail2ban with nginx proxy manager running via docker

trying to follow this tutorial, i was not able to get fail2ban to work in my setup, so here is a gist in case I forget.

1. install fail2ban

sudo apt install fail2ban

2. make a copy of the jail config to edit

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

edit your preferred defaults in here. e.g. bantime, ignoreip

3. mount your log folder outside of nginx proxy manager

    volumes:
    - /path/to/logs:/data/logs

4. create /etc/fail2ban/filter.d/npm.conf

[INCLUDES]

[Definition]

failregex = ^<HOST>.+" (4\d\d|3\d\d) (\d\d\d|\d) .+$
            ^.+ 4\d\d \d\d\d - .+ \[Client <HOST>\] \[Length .+\] ".+" .+$

5. create /etc/fail2ban/action.d/docker-action.conf

#https://www.the-lazy-dev.com/en/install-fail2ban-with-docker/
[Definition]

actionstart = iptables -N f2b-npm-docker
              iptables -A f2b-npm-docker -j RETURN
              iptables -I FORWARD -p tcp -m multiport --dports 0:65535 -j f2b-npm-docker

actionstop = iptables -D FORWARD -p tcp -m multiport --dports 0:65535 -j f2b-npm-docker
             iptables -F f2b-npm-docker
             iptables -X f2b-npm-docker

actioncheck = iptables -n -L FORWARD | grep -q 'f2b-npm-docker[ \t]'

actionban = iptables -I f2b-npm-docker -s <ip> -j DROP

actionunban = iptables -D f2b-npm-docker -s <ip> -j DROP

6. create /etc/fail2ban/jail.d/npm.local

[npm]
enabled = true
chain=INPUT
maxretry = 3
bantime = 48h
findtime = 60m
logpath = /path/to/logs/default-host_*.log
          /path/to/logs/proxy-host-*.log
action = docker-action
@sgrasley
Copy link

Since docker is already using iptables to manipulate access to the system, you might try using the DOCKER-USER chain.

@cresusjpt
Copy link

Since docker is already using iptables to manipulate access to the system, you might try using the DOCKER-USER chain.

@sgrasley can you explain please ?

@nollm
Copy link

nollm commented Dec 18, 2024

The DOCKER-USER chain in iptables is a special chain created by Docker specifically for users to insert custom firewall rules. Since Docker itself manages iptables to enable communication between containers, it can sometimes override or bypass user-defined rules. The DOCKER-USER chain provides a way to ensure that your custom rules are processed before Docker’s internal rules.
Use chain=DOCKER-USER instead of chain=INPUT and remove the action parameter to use default action.
If an IP is blocked, this applies to all Docker containers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment