host.docker.internal On LINUX?! YES
I am past my bedtime but I learned something interesting today: Docker on Linux supports the very handy host.docker.internal since Docker 20.10 as a shorthand to reach ports exposed to the host. This is very nice because the always weird and janky Coolify that I use to self-host my stuff is making sure that different resources are isolated into their own Docker networks (good) but the one way most people seem to recommend is to connect to a shared resource like a database is through exposing the DB to the internet and using the public ip to connect (bad).
Personally I think that doing a port mapping and then talking over the host mapped port is better. Nobody except for specific applications on the same host (as I only have one VPS) need to connect to my database directly. Earlier you needed to know the "host gateway IP". No more! Just do something like this in your docker-compose file:
services:
myservice:
# ...
extra_hosts:
- 'host.docker.internal:host-gateway'
And then if for example you have exposed a shared db to your host you just refer to it like so:
services:
myservice:
# ...
environment:
- 'DATABASE_URL=postgres://user:pw@host.docker.internal:5432/myservice-db'
extra_hosts:
- 'host.docker.internal:host-gateway'
And in this way you can have a single instance for all your hosted services (like a db as I said or a KV store like redis) and save a bunch of resources.
- Stack Overflow Answer
- Interestingly this doesn't seem to be documented, yet. From another answer I found these two links:
- https://github.com/docker/for-linux/issues/264#issuecomment-598864064
- https://github.com/moby/moby/pull/40007#issuecomment-578729356
-
← Previous
DailyDogo 1564 🐶