Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access host machine in Docker Container on Ubuntu 18.04

Tags:

docker

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?

like image 288
Erfun Avatar asked Dec 09 '18 08:12

Erfun


2 Answers

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:

  1. 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

  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"

  1. Finally, when you're done with the above steps, restart your containers with 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.

like image 104
Erfun Avatar answered Nov 15 '22 08:11

Erfun


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.

like image 44
aadlani Avatar answered Nov 15 '22 06:11

aadlani