casparjespersen
casparjespersen

Reputation: 3870

Forward DNS hostname to Docker container

WIthin a Docker container, I would like to connect to a MySQL database that resides on the local network. However, I get errors because it can not find the host name, so my current hot fix is to hardcode the IP (which is bound to change at some time).

Hence; is it possible to forward a hostname from the host machine to the Docker container at docker run?

Upvotes: 0

Views: 3096

Answers (3)

Miq
Miq

Reputation: 4289

Docker containers by default has access to the host network, and they're able to resolve DNS names using DNS servers configured on the host, so it should work out of the box.

I remember having similar problem in my corporate network, I solved it by referencing in the app the remote server with FQDN - our-database.mycompany.com instad just using our-database.

Hope this helps.

Upvotes: 1

nickgryg
nickgryg

Reputation: 28753

Yes, it is possible. Just inject hostname variable when run docker run command:

$ hostname
np-laptop

$ docker run -ti -e HOSTNAME=$(hostname) alpine:3.7
/ # env
HOSTNAME=np-laptop
SHLVL=1
HOME=/root
TERM=xterm
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/

Update:

I think you can do two things with docker run for your particular case:

1. Bind /etc/hosts file from the host to a container.

2. Define any dns server you want inside a container with --dns flag.

So, finally the command is:

docker run -ti -v /etc/hosts:/etc/hosts --dns=<IP_of_DNS> alpine:3.7

Upvotes: 1

eniacz
eniacz

Reputation: 127

People has asked similar questions and got good answers:

How do I pass environment variables to Docker containers?

Alternatively you can configure the DHCP/DNS server that serves the docker machines to resolve the hostnames properly. DDNS is another option that can simplify configuration as well.

Upvotes: 0

Related Questions