diff --git a/Dockerfile b/Dockerfile index 6eaee58..1cbe172 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,16 @@ -FROM docker.io/library/python:3-alpine +# syntax=docker/dockerfile:1 + +ARG BASE_IMAGE=docker.io/library/python:3-alpine +ARG APP_DIR=/hoster + +FROM ${BASE_IMAGE} RUN pip3 install docker -RUN mkdir /hoster -WORKDIR /hoster -ADD hoster.py /hoster/ + +ARG APP_DIR=/hoster +WORKDIR ${APP_DIR} + +ADD hoster.py ./ CMD ["python3", "-u", "hoster.py"] - - - +# CMD "whoami" diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..f4fe945 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,12 @@ +# This file replaces `docker build -t docker-hoster .` +# Run this with `docker-compose build` +version: '3.8' + +services: + host-hostnames: + container_name: 'host-hostnames' + build: + context: '.' + volumes: + - '/var/run/docker.sock:/tmp/docker.sock:ro' + - '/etc/hosts:/tmp/hosts' diff --git a/hoster.py b/hoster.py index d87448a..dc776a4 100644 --- a/hoster.py +++ b/hoster.py @@ -39,9 +39,9 @@ def main(): #listen for events to keep the hosts file updated for e in events: - if e["Type"]!="container": + if e["Type"]!="container": continue - + status = e["status"] if status =="start": container_id = e["id"] @@ -64,16 +64,16 @@ def get_container_data(dockerClient, container_id): container_ip = info["NetworkSettings"]["IPAddress"] if info["Config"]["Domainname"]: container_hostname = container_hostname + "." + info["Config"]["Domainname"] - + result = [] for values in info["NetworkSettings"]["Networks"].values(): - - if not values["Aliases"]: + + if not values["Aliases"]: continue result.append({ - "ip": values["IPAddress"] , + "ip": values["IPAddress"] , "name": container_name, "domains": set(values["Aliases"] + [container_name, container_hostname]) }) @@ -112,11 +112,11 @@ def update_hosts_file(): #append all the domain lines if len(hosts)>0: lines.append("\n\n"+enclosing_pattern) - + for id, addresses in hosts.items(): for addr in addresses: lines.append("%s %s\n"%(addr["ip"]," ".join(addr["domains"]))) - + lines.append("#-----Do-not-add-hosts-after-this-line-----\n\n") #write it on the auxiliar file @@ -125,7 +125,7 @@ def update_hosts_file(): aux_hosts.writelines(lines) #replace etc/hosts with aux file, making it atomic - shutil.move(aux_file_path, hosts_path) + shutil.copyfile(aux_file_path, hosts_path) def parse_args():