Dockerized Nginx 反向代理 - 真实 IP

Dockerized Nginx 反向代理 - 真实 IP

我有以下问题。我有一个docker compose设置,它使用Nuxt3启动前端服务,并基于golang启动后端API。这两个容器通过Nginx反向代理公开,一切正常,但我需要在我的golang服务中检索用户IP地址。Nginx似乎只转发带有172.xxx的docker ip,而不是真实用户的IP地址。

docker-compose.yaml

version: '3'
services:
  nuxt-frontend:
    build:
      context: ./frontend # Path to your Nuxt 3 backend code
      dockerfile: Dockerfile.local
    command: npm run dev
    x-develop:
      watch:
        - action: sync
          path: ./frontend
          target: /app
          ignore:
            - node_modules/
        - action: rebuild
          path: package.json
  mongodb:
    image: mongo:latest
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: admin
    volumes:
      - mongodb_data:/data/db
  go-backend:
    build:
      context: ./backend
      dockerfile: Dockerfile.local
    command: air
    x-develop:
      watch:
        - action: sync
          path: ./backend
          target: /app
        - action: rebuild
          path: go.mod
    depends_on:
      - mongodb 
  nginx:
    image: nginx:latest
    ports:
      - "80:80"   # HTTP port
      - "443:443" # HTTPS port
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./nginx/ssl:/etc/nginx/ssl
    depends_on:
      - nuxt-frontend
      - go-backend
volumes:
  cache:
    driver: local
  mongodb_data:

nginx.conf

server {
    listen 80;
    server_name localhost;
    
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name localhost;

    ssl_certificate /etc/nginx/ssl/cert.pem; 
    ssl_certificate_key /etc/nginx/ssl/key.pem;

    location /api {
        proxy_pass http://go-backend:3001; 
        proxy_set_header    Host                $http_host;
        proxy_set_header    X-Real-IP           $remote_addr;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
    }

    location / {
        proxy_pass http://nuxt-frontend:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

非常感谢您的任何建议。

亲切的问候

相关内容