Incorrect client IP with Django, Gunicorn, nginx

67 Views Asked by At

I've been trying to fix that issue for 5 hours using some possible solutions to the known problem, but it didnt occured.

I want to log (django logging extension) requests from client with saving client's IP. Unfortunately, instead of client IP I get internal IP of the Docker's gateway.

nginx.conf

server {
  server_tokens off;
  listen 80;
  server_name 127.0.0.1;

  location / {
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header REMOTE_ADDR $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://microservice_backend:8000;
  }

  location ~/(media|static)/ {
    root /var/html;
  }
}

Also I'm using django-xff's middleware and function to extract IP

def get_client_ip(request) -> str:
    x_forwarded_for = request.META.get('HTTP_REMOTE_ADDR')

    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')

    return ip

At the beginning "client's IP" was 172.22.0.1. After using django-xff it's 192.168.0.1. It seems to me that somehow $remote_addr; at nginx contains an incorrect IP.

request.META does not contains client IP at all (it was $remote_addr with value 172.22.0.1)

I'm very upset because of that. Hope someone could help me!

0

There are 0 best solutions below