Acessing the host from a docker container
This is one of the things I wish I knew earlier.
When developing locally, sometimes you need a database, in those cases you can simply
run docker
/docker-compose
, expose the port and hit that port from the development server.
When running tests, I like to use testcontainers
to spin up a test db.
So host
-> container
communication is straightforward.
However, there are cases when I need to access the host
from a container:
- Running
prometheus
in a container, and pulling/metrics
from thehost
; - Running some benchmark tool against a local development server;
I knew that when running Docker for Mac
(and I think Docker for Windows
), the host.docker.internal
DNS name
is resolved to the host. But that didn’t work for Linux, which requires passing --add-host=host.docker.internal:host-gateway
for it to work.
The point is that there would be 2 different setups depending on the OS, which doesn’t scale very well in a team with non-homogeneous OSes. Boo!
But recently I found about qoomon/docker-host
, which cleverly makes the setup transparent.
Then it uses iptables rules to forward any traffic received on that container to the same port, in the host.
For illustration, run an HTTP server on port 8000 using python
:
|
|
Then, in a docker-compose.yaml
file, we curl
that server via http://docker-host:8000
:
|
|
Which returns
|
|
Showing that it is able to hit the host!
Quirks
If you are running rootless containers, you need to manually set the
DOCKER_HOST
env var with the host’s machineHOSTNAME
Of course, the
NET_ADMIN
andNET_RAW
capabilities need to be added, since you are messing up with the network.