Accessing Host from Docker Container

Sometime we need to access the services that are running in the host machine to be accessible from the docker container.  e.g. In on of my project, we needed to connect to the oracle db (port 1521) from inside the container within code.

The default behaviour of containers are, they cant access the host network directly unless the firewall of the host machine allows the network interface of docker to ACCEPT the packets.

So the docker container will communicate with the host machine using the gateway ip. First find the gateway ip inside the container.

Run below command inside the container to get the gateway ip and observer I am not able to connect to port 1521.

# nc -vz dockerhost 1521

dockerhost [] 1521 (?) : Connection timed out

# ip route | awk '/^default via /{print $3}'

Next  task is to get the interface name of the docker network which is binded with the container.  Most of the cases its docker0.

But it can also be customized, so check ifconfig output which matches the inet addr of the container gateway.

# ifconfig

br-4e83b57c54cf Link encap:Ethernet  HWaddr 02:42:AF:CD:B5:DA

inet addr:<strong></strong>  Bcast:  Mask:

# ip addr show br-4e83b57c54cf

10: br-4e83b57c54cf: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP

link/ether 02:42:af:cd:b5:da brd ff:ff:ff:ff:ff:ff

inet <strong></strong> scope global br-4e83b57c54cf

valid_lft forever preferred_lft forever

Here the interface name is : br-4e83b57c54cf

Now add a iptables rule in Linux host:

iptables -A INPUT -i br-4e83b57c54cf -j ACCEPT

Now try to access the host port from container.

# nc -vz dockerhost 1521

dockerhost [] 1521 (?) open

There are other ways also available on internet , but I found none of them working.













About Divyashree - The GNULINUX Guy

I am a Linux and Opensource enthusiast. I started working on Linux early in 2007 while I was doing my Masters in Computer Science and passed out in 2010. Currently working as a DevOps Developer in in Public/Private cloud domain. my @github : my @nagiosexchange : my @linkedin :☁-a9415615
This entry was posted in ARTICLES, Concepts, Container, FOSS, HOWTO, OperatingSystem, TIPS & T RICS and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s