Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get local host IP address in docker container?

Tags:

bash

shell

docker

I am using docker and run using script. I want to change in one of configuration with host machine IP address in docker.

#!/bin/bash
IP=$(echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed   's/addr://'`)
echo Setting xwiki config IP
CONFIG=/xwiki/webapps/xwiki/WEB-INF/xwiki.cfg
sed -i -e "s/^xwiki.authentication.authhost=localhost*/xwiki.authentication.authhost= $IP/"  $CONFIG

/xwiki/start_xwiki.sh -f

I run my docker with following command.

docker run -t -i $EXPOSE_PORTS $IMAGE "$@"
like image 662
Pawan Kumar Avatar asked Feb 08 '23 19:02

Pawan Kumar


1 Answers

As mentioned in "How to get the ip address of the docker host from inside a docker container", you can directly access it from the container:

/sbin/ip route|awk '/default/ { print $3 }'

But, as commented, when you are using the docker bridge (default) for the containers, this will output the bridges IP like 172.17.42.1 rather than the host's IP such as 192.168.1.x (typical of an home NAT)

You can pass the actual IP as an environment variable with run --env <key>=<value>

-e "DOCKER_HOST=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+')

(From "Is there an easy way to programmatically extract IP address?")

As the OP Pawan Sharma comments:

docker0 gives host docker ip. I used eth0, it gives my host ip.

-e "DOCKER_HOST=$(ip -4 addr show eth0| grep -Po 'inet \K[\d.]+')
like image 64
VonC Avatar answered Feb 13 '23 03:02

VonC