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.

Requirements

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.

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

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

        volumeMounts:
          - name: nginx-logs
            mountPath: /var/log/nginx
      volumes:
        - name: nginx-logs
          hostPath:
            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
        missingok
        copytruncate
        rotate 52
        compress
        delaycompress
}

Enable the jails

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

[nginx-botsearch]
enabled = true

[nginx-http-auth]
enabled = true

[nginx-limit-req]
enabled = true

Restart Fail2ban

service fail2ban restart

We can check that our jails are enabled

fail2ban-client status
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.

Conclusion

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.