How to preserve original client IP addresses when using Cloudflare with Docker containers and reverse proxy?

I’m having trouble with IP address forwarding in my Docker setup. My configuration includes Cloudflare for DNS, a reverse proxy container, and multiple services running in Docker containers.

The problem is that my applications are not seeing the real client IP addresses. Instead, they see either the reverse proxy container IP or my server’s local IP depending on the network configuration I use.

This creates a serious security issue because my services have built-in protection that blocks IPs after failed login attempts. When the wrong IP gets blocked, it prevents all users from accessing the service instead of just blocking the actual attacker.

I’ve tried different Docker networking modes like bridge and host but neither gives me the correct client IP in my application logs. I know this involves configuring headers to pass through the real IP from Cloudflare but I can’t get it working properly.

Has anyone successfully set up IP forwarding through this type of chain? What configuration changes are needed to make sure the original visitor IP reaches the final application?

Your reverse proxy isn’t handling the header chain properly. Cloudflare sends the real IP through specific headers, but your proxy needs to read them and pass them to your Docker containers. For Nginx, use real_ip_module with set_real_ip_from pointing to Cloudflare’s IP ranges, and real_ip_header CF-Connecting-IP. Then add proxy_set_header X-Real-IP $remote_addr to send it downstream. Skip bridge mode - it adds extra NAT layers that mess things up. Host networking works but isn’t secure. Better to use custom bridge networks and configure your apps to trust the reverse proxy container’s IP range for forwarded headers. Test with curl commands to verify each step works before going live. Saves a lot of headaches.

check ur app config - most ppl skip this. ur docker apps need to read CF-Connecting-IP or X-Real-IP headers, even if the proxy forwards them correctly. otherwise you’ll just get proxy ips in your logs instead of real client ips. and whitelist cloudflare ips or the headers get ignored.

I experienced a similar issue with preserving the client IP in my own Docker and Cloudflare setup. To fix this, it’s crucial to note that Cloudflare uses the CF-Connecting-IP header to convey the original client IP, rather than the typical X-Forwarded-For. Therefore, your reverse proxy must be configured to recognize and prioritize this header. I recommend adjusting your proxy settings to first look for CF-Connecting-IP, and only then check X-Real-IP as a fallback. Additionally, ensure that your Docker containers are set to trust the proxy’s IP for forwarded headers, as they will ignore requests from unrecognized sources. Balancing header precedence can be intricate, especially since Cloudflare may insert multiple IP headers in some scenarios.