Get original client ip

How to get the original client IP inside the docker container to put into the database as a log, while I’m still trying with a simple code. I’m using nodejs express with module type configuration style.
this is my code:

import express from 'express'
import http from 'http'

const app = express()
app.set('port', '0.0.0.0' || '1234')
app.get('/', (req, res) => {
    const ipadd = req.socket.remoteAddress
    
    res.send({ status: true, message: `IP: ${ipadd}` })
    return
})

http.createServer(app).listen('1234', '0.0.0.0', () => {
    console.log(`Server running at http://0.0.0.0:1234/`)
})

i’ve try to run with command bellow

  1. docker run -d --restart unless-stopped --name read-ip-container --publish 1234:1234 read-ip:latest NOT WORKING TO GET CLIENT IP
  2. docker run --rm -it --net=host read-ip index.js -lkv 0.0.0.0 1234 NOT WORKING TO GET CLIENT IP

please help me solve this problem without request headers like x-forwarded-for :smiling_face_with_tear:

On Docker Desktop, the only way to retain the client ip is to enable host network in the Docker Desktop settings and starting the container attached to the host network.

see: https://docs.docker.com/engine/network/drivers/host/#docker-desktop

i’ve try this on number 2 but the result i get is 127.0.0.1

i try install docker on linux and i get original client IP. I run with command docker run -d --restart unless-stopped --name read-ip-container --publish 1234:1234 read-ip:latest i don’t know why it’s not working when host OS is windows but working on linux very well

Usually you would use the HTTP headers to get the original IP, especially when load balancers and reverse proxies are used on the way.

X-Forwarded-For: 1.2.3.4
X-Forwarded-Host: whoami.example.com
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Forwarded-Server: 0415b78c68a2
X-Real-Ip: 1.2.3.4
1 Like