Post

Accessing Host Services from Docker containers

Accessing Host Services from Docker containers

Sometimes services are run on the docker host (e.g.. database servers, etc.) which need to be accessed from within the docker containers.

The usual practice is to bind mount the DB socket inside the container (e.g. /var/run/mysql/mysqld.sock). The problem with this approach is that if the DB server is restarted on the docker host, the socket will be removed and the bind mount will become stale. Applications inside the docker containers will fail until the container is recreated (docker-compose down; docker-compose up -d).

A better option is to alias a second IP address to the docker host’s lo interface and use that IP to access the host services. As the lo interface is internal to the docker host, the same IP can be used on all docker hosts without IP conflicts. Further, using a Link Local Address from the 169.254.0.0/16 segment reduces the chance of IP conflicts with existing subnets.

By using the secondary IP on the host’s lo interface, the container applications will be routed to their local docker host services. This works well in docker swarms also.

Add the lo interface IP address in netplan config file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Sample ubuntu netplan config for aliasing 169.254.254.169/32 as secondary lo IP
network:
  version: 2
  ethernets:
    enp3s0:
      addresses:
        - 192.168.0.10/24
      routes:
        - to: default
          via: 192.168.0.1
          on-link: true
      nameservers:
        addresses: [8.8.8.8, 1.1.1.1]

    lo:
      addresses: [ 169.254.254.169/32 ]

Inside the containers, use the 169.254.254.169 IP to connect to services running on the docker host.

1
2
3
4
5
// Sample wp-config.php fragment

/** Database hostname */

define( 'DB_HOST', '169.254.254.169' );

This exposes all host services to all containers, its bad for security. To restrict this, use iptables firewall rules to prevent access to host ports between 1-1024 on IP 169.254.254.169.

1
$IPTABLES -A INPUT -p tcp -d 169.254.254.169 --dport 1:1024 -j DROP
This post is licensed under CC BY 4.0 by the author.