Skip to content

Commit

Permalink
Add DNS for container name
Browse files Browse the repository at this point in the history
If there is no `VIRTUAL_HOST` we add a hostname based on the container
name.

We cannot add more than one name to the same IP, apparently. Otherwise
we could have added both of them.
  • Loading branch information
arnested committed Jan 8, 2021
1 parent 4a0d71e commit 9476f37
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 11 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# Local Docker Development DNS

A systemd service that will monitor your Docker host and provide
DNS names for containers with a `VIRTUAL_HOST` environment variable.
DNS names for containers based of the container name.

If a `VIRTUAL_HOST` environment variable is present the DNS we will
base the DNS of that instead.

The service broadcasts the domain names using multicast DNS
(a.k.a. mDNS, zeroconf, bounjour, avahi).
Expand Down
14 changes: 7 additions & 7 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ func handleContainer(
}

hostname := extractHostname(ctx, container)
if hostname == "" {
return
}

services := extractServices(ctx, container)

hostname = rewriteHostname(ctx, hostname)

addToDNS(eg, hostname, ips, services, container.Name[1:])
if hostname != "" {
hostname = rewriteHostname(hostname)
addToDNS(eg, hostname, ips, services, container.Name[1:])
} else {
containerHostname := rewriteHostname(container.Name[1:] + ".local")
addToDNS(eg, containerHostname, ips, services, container.Name[1:])
}
}

// extractIPnumbers from a container.
Expand Down
7 changes: 4 additions & 3 deletions hostname.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package main

import (
"context"
"strings"

"golang.org/x/net/publicsuffix"
)

// rewriteHostname will make `hostname` suitable for dns-sd.
func rewriteHostname(_ context.Context, hostname string) string {
func rewriteHostname(hostname string) string {
suffix, _ := publicsuffix.PublicSuffix(hostname)
basename := hostname[:len(hostname)-len(suffix)-1]
sanitizedHostname := strings.ReplaceAll(basename, ".", "-") + ".local"
basename = strings.ReplaceAll(basename, ".", "-")
basename = strings.ReplaceAll(basename, "_", "-")
sanitizedHostname := basename + ".local"

if hostname != sanitizedHostname {
logf(PriInfo, "Rewrote hostname from %q to %q\n", hostname, sanitizedHostname)
Expand Down

0 comments on commit 9476f37

Please sign in to comment.