J
J
John Doe2018-10-14 04:41:31
PHP
John Doe, 2018-10-14 04:41:31

How to get real user IP in Docker + Nginx + PHP-Fpm?

How do I pass the user's real IP to the container? Now I'm getting this:

"SERVER_PORT": "80",
"SERVER_ADDR": "172.20.0.3",
"REMOTE_PORT": "44034",
"REMOTE_ADDR": "172.20.0.1",

docker-compose.yml:
version: "3.7"
services:
  nginx:
    image: nginx:alpine
    volumes:
      - .:/application
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
    ports:
      - mode: host
        protocol: tcp
        published: 3000
        target: 80
    networks:
      - backend
    links:
      - php-fpm

  php-fpm:
    build: docker/php-fpm
    volumes:
      - .:/application
    networks:
      - backend

networks:
    backend:
      driver: bridge

default.conf:
server {
    listen 80 default;

    client_max_body_size 108M;

    access_log /application/logs/nginx-access.log;
    error_log /application/logs/nginx-error.log;

    root /application/www;
    index index.php;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_pass php-fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        include fastcgi_params;
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
chupasaurus, 2018-10-14
@chupasaurus

proxy_set_header X-Real-IP $remote_addr;

L
LionG, 2020-12-14
@LionG

http {
  ...
  # FIX REAL IP
  real_ip_header X-Forwarded-For;
  set_real_ip_from 0.0.0.0/0;
  ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question