When building applications within Docker Swarm, it’s common to find scenarios where you need to connect to services running outside of Swarm, yet on the same machine. An example scenario includes a multi-container application running in Docker Swarm, while cache and database services like Redis and Postgres run locally.
Before diving into the solution, let’s briefly understand the Docker networking landscape.
- Standalone Containers: By default, these containers, when not attached to any user-defined network, reside within the
172.16.x.x
to172.31.x.x
IP range. In a typical single-network setup, the host machine is usually reachable at172.17.0.1
. - Docker Swarm: For Swarm services, each network is mapped to a new IP range within
10.x.x.x
. Here, accessing the host machine becomes a bit trickier, as it’s abstracted by the overlay network.
While you might be tempted to reference the local machine directly using the IP (like 172.17.0.1
for standalone containers), there’s a more elegant solution provided by Docker for consistent host referencing.
In the service definition within your Docker Swarm stack file, add the extra_hosts
param:
environment: ...
networks: ...
volumes: ...
extra_hosts:
- "host.docker.internal:host-gateway"
With this configuration, Docker maps host.docker.internal
to the actual gateway IP address of the host machine.
After implementing the above change, connecting to a local Postgres instance would look like this:
postgresql://user:[email protected]:5432/database