Docker: get clients IP address in container

Viewed 2689

how can i receive the clients ip address in any docker container?

in my php application i need to check client ip addresses with $_SERVER[REMOTE_ADDR] to control access which is at the moment not possible.

for example i am running a php-apache webserver in container on port 8080.

my ip address is : 192.168.80.177 container network: 172.21.0.0/16 container ip': 172.21.0.3

when i access localhost:8080 the ip of the docker network gateway will be logged (172.21.0.1).

is it possible to pass my client ip address to the docker container?

thank you

2 Answers

You could pass the host ip as a environment variables at the docker run time, and then grab it in php with $_ENV['your_env_name'];

# GET & SET HOST IP
# double check this on the system you're working on.
# should work on most linux env
# Adjust NR=1 or NR=2 NR=3 depending on the ip addresses returned
export HOST_IP=$(echo "$(ifconfig)" | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | awk "NR==7{print;exit}");
# PASS HOST IP AS ENV
docker run -it -d -p 8080:8080 -e HOST_IP=$HOST_IP --name yourname docker:image;
// Your php script
echo $_ENV['HOST_IP'];

use --net=host when running your container

Related