Skip to content

Connecting to local services from Docker Swarm

Posted on:August 7, 2023

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.

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