Nginx in Docker with Fail2ban

Posted by

To ease the deployment and for security reasons, I’m running most of my applications in Docker containers. Since theses containers are not directly part of the system, to connect them to classic tools it requires some extra configuration.


Install Fail2ban with your package manager and make Nginx running in Docker.

Mount the files

In my Compose file I’m mounting the log directory.

      - /var/log/nginx:/var/log/nginx

For Kubernetes, you need to use a volume in your pod

          - name: nginx-logs
            mountPath: /var/log/nginx
        - name: nginx-logs
            path: /var/log/nginx

We also need to manage the log file, else it will grownup until filling the disk. Create /etc/logrotate.d/nginx and add inside:

/var/log/nginx/*.log {
        rotate 7
        rotate 52

Enable the jails

Lets create a local configuration file, create /etc/fail2ban/jail.local and add the following content.

enabled = true

enabled = true

enabled = true

Restart Fail2ban

service fail2ban restart

We can check that our jails are enabled

fail2ban-client status
|- Number of jail:	4
`- Jail list:	nginx-botsearch, nginx-http-auth, nginx-limit-req, sshd

The nginx-limit-req module will require extra configuration. You need to enable ngx_http_limit_req_module in Nginx, I let you follow the Documentation.


Combining Nginx running inside of Docker and Fail2ban is simple but requires extra tuning compared to the the native integration. You can use a similar configuration to combine Fail2ban with other containerized software.