Access host machine in Docker Container on Ubuntu 18.04
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:
- First, create an alias for
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
- Then, put this on you docker-compose.yml file:
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"
- Finally, when you're done with the above steps, restart your containers with
docker-compose down && docker-compose up -d
ordocker-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.