If I have a Postgres database running on the host machine (os: Linux), and some service running in a container of docker-compose. How would I access the database from service in a container? How .yaml file of the service in docker-compose should look like?
2
Answers
On Linux, the host can be reached at 172.17.0.1.
You usually don’t change anything in your docker-compose file. You change the settings in your program where you tell it the address of the database server.
Using recent (20.10 or later) versions of Docker on Linux, you can configure a host alias using the
host-gateway
target, like this:Or in your
docker-compose.yaml
:With this configuration, you can refer to your hostas
host.docker.internal
(support for this was added in https://github.com/moby/moby/pull/40007). Support for thehost.docker.internal
alias has been available under MacOS and Windows for a while (where the network configuration made it more of a necessity).For example:
You’re not required to use the name
host.docker.internal
; you could just as easily run:But the name
host.docker.internal
shows up various bits of documentation so it makes a good choice.Prior to Docker 20.10, I would have said:
On Linux, the host can be reached at any of it’s non-
localhost
addresses. A convenient target is the address of the Docker bridge to which your container is connected (docker0
when using the default network, or the one created dynamically for other Docker networks).So if your system has an interface configuration like this:
You could use either 192.168.123.106, 172.23.0.1, or 172.17.0.1 as the
address of your host.
From inside a container, you can get the address of the associated bridge by looking up the default gateway:
Otherwise, just pick a host address and use it. Note that if you’re running with a restrictive firewall configuration you may need to open the necessary ports to permit the access.
NB:
You cannot assume the address of the
docker0
bridge willbe
172.17.0.1
: depending on your local network configuration, Dockermay choose a different network range for that bridge (so, just check
first).
If you are running with a restrictive firewall configuration, you
may need to open up the necessary ports in order for containers to
access services on your host.