I am looking for a way to connect to my host machine in a Docker Container (in my case, access to a specific port for using a proxy in the application container).
I tried network_mode: "host"
(or docker run --network="host"
), it worked in case of accessing to local machine but caused some other problems which were related to changing network driver to host
:
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known.
Also I can not use ifconfig
to define network alias since I'm using Ubuntu 18.04.
What should I do?
UPDATE: Since the docker-host
(https://github.com/qoomon/docker-host) image is published in the last few months, you can use that without any manual configuration. Easy peasy!
After struggling for a day, finally found the solution. It can be done by --add-host flag in docker run
command or extra_hosts in a docker-compose.yml
file with making an alias for Local (lo | 127.0.0.1
) network interface.
So here are the instructions:
lo
interface. As you may know, ifconfig
command does not exist on Ubuntu 18.04 so this is how we do it:sudo ip addr add 192.168.0.20/24 dev lo label lo:1
extra_hosts:
- "otherhost:192.168.0.20"
If you are not using Docker Compose you can add a host to a container by --add-host
flag. Something like
docker run container-name --add-host="otherhost:192.168.0.20"
docker-compose down && docker-compose up -d
or docker-compose restart
Now you can log-in to your container (docker-compose exec container-name bash
) and test it.
NOTE: Make sure your working port is open using telnet [interface-ip] [port]
command.
You can use the extra_hosts
in you docker-compose, which is what you discovered by yourself. I just wanted to add another way when you are working on your local environment.
In docker-for-mac and docker-for-windows, within a container the DNS name host.docker.internal
resolves to an IP address allowing network access to the host.
Here's the related description, extracted from the documentation:
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker for Windows.
There's an open issue on github concerning the implementation of this feature for docker-for-linux.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With