Skip to content

Commit

Permalink
Add container name and container hostname to hosts by default
Browse files Browse the repository at this point in the history
  • Loading branch information
grachevko committed Sep 13, 2021
1 parent 8751f22 commit 21da876
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ Try to ping from host

% ping nginx.local

Default hosts
-----
By default adding records with container name and container hostname.
To disable it you can use environments `CONTAINER_HOSTNAME_DISABLED` and `CONTAINER_NAME_DISABLED`:
```bash
$ docker run -d --restart=always \
--name docker-hosts-updater \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /etc/hosts:/opt/hosts \
-e CONTAINER_HOSTNAME_DISABLED=false \
-e CONTAINER_NAME_DISABLED=false \
grachevko/docker-hosts-updater
```

Multiple Hosts
-----
You can add multiple hosts, just separate them by semicolon:
Expand Down
5 changes: 4 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ version: '3.7'
services:
dhu:
build:
context: .
context: .
image: grachev/dhu
# environment:
# CONTAINER_HOSTNAME_DISABLED: 'false'
# CONTAINER_NAME_DISABLED: 'false'
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./:/usr/local/app
Expand Down
11 changes: 10 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import docker
import re
import os
from netaddr import valid_ipv4

LABEL = 'ru.grachevko.dhu'
MARKER = '#### DOCKER HOSTS UPDATER ####'
HOSTS_PATH = '/opt/hosts'
CONTAINER_HOSTNAME_DISABLED = bool(os.getenv('CONTAINER_HOSTNAME_DISABLED', False))
CONTAINER_NAME_DISABLED = bool(os.getenv('CONTAINER_NAME_DISABLED', False))


def listen():
Expand Down Expand Up @@ -41,11 +44,17 @@ def scan():
if ip == False:
ip = next(iter(lb.attrs.get('NetworkSettings').get('Networks').values())).get('IPAddress')

hosts = string_to_array(string)
if not CONTAINER_HOSTNAME_DISABLED:
hosts.append(container.attrs.get('Config').get('Hostname'))
if not CONTAINER_NAME_DISABLED:
hosts.append(container.name)

if ip:
containers.append({
'ip': ip,
'priority': priority,
'hosts': string_to_array(string),
'hosts': hosts,
'createdAt': container.attrs.get('Created'),
})

Expand Down

0 comments on commit 21da876

Please sign in to comment.