Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@ nfpms:
formats:
- deb
dependencies:
- avahi-daemon
- docker.io | docker-ce
- libsystemd0
recommends:
- libnss-mdns | systemd-resolved
bindir: /usr/libexec
changelog: ./changelog.yml
contents:
Expand Down
43 changes: 32 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
A systemd service that will monitor your Docker host and provide
DNS names for the containers.

The service broadcasts the domain names using multicast DNS
(a.k.a. mDNS, zeroconf, Bonjour, Avahi).
The service answers for the domain names with its own multicast DNS
responder (a.k.a. mDNS, zeroconf, Bonjour). It answers only on the
Docker networks of the containers, so the names do not reach your LAN.

A limitation of this is that domains name can only be on the `.local`
TLD and only have one level below the TLD. A benefit is that you don't
have to change your DNS server or configure stuff in `/etc/resolv` or
similar.
A limitation of this is that domain names can only be on the `.local`
TLD. A benefit is that you don't have to change your DNS server or
configure stuff in `/etc/resolv` or similar.

If the containers also have exposed ports (and the ports can be looked
up in `/etc/services`) the service will also broadcast the
Expand All @@ -21,9 +21,19 @@ Per default domain names will be generated from the `VIRTUAL_HOST`
environment variable is present (several hostnames can be separated by
space or comma) and from the container name.

If the hostnames do not fulfill the rule of being on the `.local` TLD
and have only one level below the service will rewrite it.
I.e. `my.example.com` will be rewritten to `my-example.local`.
If a hostname is not on the `.local` TLD, the service replaces the
public suffix with `.local`. The service keeps the dots, and it also
publishes a flat name with only one level below `.local`. For
example, `my.example.com` gives both `my.example.local` and
`my-example.local`.

The default configuration of nss-mdns (`mdns4_minimal` in
`/etc/nsswitch.conf`) resolves only names with one level below
`.local`. The flat names work everywhere, so the DNS-SD services
point to the flat name. To resolve names like
`my.example.local` too, use systemd-resolved with `MulticastDNS=yes`.
Or change `mdns4_minimal` to `mdns4` in `/etc/nsswitch.conf`, and
create `/etc/mdns.allow` with the two lines `.local.` and `.local`.

## Configuration

Expand Down Expand Up @@ -66,6 +76,17 @@ Environment=LDDDNS_HOSTNAME_LOOKUP=env:VIRTUAL_HOST,containerName
Environment=LDDDNS_IGNORE_DOCKER_COMPOSE_ONEOFF=true
```

## Requirements

The host needs an mDNS resolver, because `ldddns` only answers for
the names. Use one of these:

* Avahi with nss-mdns (`avahi-daemon` and `libnss-mdns`). Most
desktop distributions install these by default.
* systemd-resolved with `MulticastDNS=yes`.

`ldddns` shares UDP port 5353 with the resolver.

## Install

For Pop!_OS, Ubuntu, Debian and the like, download the `.deb` package
Expand Down Expand Up @@ -117,8 +138,8 @@ jan 07 12:46:11 pop-os systemd[1]: Starting Local Docker Development DNS...
jan 07 12:46:11 pop-os ldddns[5414]: Starting ldddns v1.0.13...
jan 07 12:46:11 pop-os systemd[1]: Started Local Docker Development DNS.
jan 07 12:46:11 pop-os ldddns[5414]: Rewrote hostname from "my.example.com" to "my-example.local"
jan 07 12:46:11 pop-os ldddns[5414]: added address for "my-example.local" pointing to "172.18.0.2"
jan 07 12:46:11 pop-os ldddns[5414]: added service "_https._tcp" pointing to "my-example.local"
jan 07 12:46:12 pop-os ldddns[5414]: mDNS name my-example.local. of container 3f0c… is live
jan 07 12:46:12 pop-os ldddns[5414]: mDNS name my-example._https._tcp.local. of container 3f0c… is live
```

Or follow the log with:
Expand Down
102 changes: 43 additions & 59 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,40 @@ package main
import (
"context"
"fmt"
"maps"
"net/netip"
"slices"
"strconv"
"time"

"github.com/holoplot/go-avahi"
"github.com/moby/moby/api/types/events"
"github.com/moby/moby/client"
internalContainer "ldddns.arnested.dk/internal/container"
"ldddns.arnested.dk/internal/hostname"
"ldddns.arnested.dk/internal/log"
"ldddns.arnested.dk/internal/mdns"
)

//nolint:cyclop
// publisher publishes the mDNS records of containers.
type publisher interface {
Publish(owner string, set mdns.RecordSet)
Unpublish(owner string)
}

func handleContainer(
ctx context.Context,
docker *client.Client,
containerID string,
egs *entryGroups,
pub publisher,
status events.Action,
config Config,
) error {
if status == "destroy" {
egs.free(containerID)
if status == "destroy" || status == "die" || status == "kill" || status == "pause" {
pub.Unpublish(containerID)

return nil
}

if status == "die" || status == "kill" || status == "pause" {
return resetContainer(egs, containerID)
}

result, err := docker.ContainerInspect(ctx, containerID, client.ContainerInspectOptions{})
if err != nil {
return fmt.Errorf("inspecting container: %w", err)
Expand All @@ -44,21 +48,10 @@ func handleContainer(
return nil
}

ipNumbers := containerInfo.IPAddresses()

entryGroup, commit, err := egs.get(containerID, len(ipNumbers) > 0)
defer commit()

if err != nil {
return fmt.Errorf("cannot get entry group for container: %w", err)
}

err = resetEntryGroup(entryGroup)
if err != nil {
return err
}
addresses := ipv4Addresses(containerInfo.IPAddresses())
if len(addresses) == 0 {
pub.Unpublish(containerID)

if len(ipNumbers) == 0 {
return nil
}

Expand All @@ -67,50 +60,41 @@ func handleContainer(
return fmt.Errorf("getting hostnames: %w", err)
}

for _, hostname := range hostnames {
addAddress(entryGroup, hostname, ipNumbers)
}

if services := containerInfo.Services(); len(hostnames) > 0 {
addServices(entryGroup, hostnames[0], ipNumbers, services, containerInfo.Name())
}
pub.Publish(containerID, mdns.RecordSet{
Hostnames: hostnames,
Addresses: addresses,
Instance: containerInfo.Name(),
Services: services(containerInfo.Services()),
})

return nil
}

// resetContainer removes the entries of a container without creating an
// entry group for it.
func resetContainer(egs *entryGroups, containerID string) error {
entryGroup, commit, err := egs.get(containerID, false)
defer commit()
func ipv4Addresses(ipNumbers []string) []netip.Addr {
var addresses []netip.Addr

if err != nil {
return fmt.Errorf("cannot get entry group for container: %w", err)
for _, ipNumber := range ipNumbers {
addr, err := netip.ParseAddr(ipNumber)
if err != nil || !addr.Is4() {
continue
}

addresses = append(addresses, addr)
}

return resetEntryGroup(entryGroup)
return addresses
}

// resetEntryGroup removes all entries from an entry group. A nil group is
// a container without a group, so there is nothing to reset.
func resetEntryGroup(entryGroup *avahi.EntryGroup) error {
if entryGroup == nil {
return nil
}
// services returns the services sorted by type, so that the same
// container gives the same record set.
func services(ports map[string]uint16) []mdns.Service {
result := make([]mdns.Service, 0, len(ports))

empty, err := entryGroup.IsEmpty()
if err != nil {
return fmt.Errorf("checking whether Avahi entry group is empty: %w", err)
}

if !empty {
err := entryGroup.Reset()
if err != nil {
return fmt.Errorf("resetting Avahi entry group: %w", err)
}
for _, serviceType := range slices.Sorted(maps.Keys(ports)) {
result = append(result, mdns.Service{Type: serviceType, Port: ports[serviceType]})
}

return nil
return result
}

func ignoreOneoff(containerInfo internalContainer.Container, config Config) bool {
Expand All @@ -132,7 +116,7 @@ func ignoreOneoff(containerInfo internalContainer.Container, config Config) bool
return true
}

func handleExistingContainers(ctx context.Context, config Config, docker *client.Client, egs *entryGroups) {
func handleExistingContainers(ctx context.Context, config Config, docker *client.Client, pub publisher) {
result, err := docker.ContainerList(ctx, client.ContainerListOptions{})
if err != nil {
log.Logf(log.PriErr, "getting container list: %v", err)
Expand All @@ -143,7 +127,7 @@ func handleExistingContainers(ctx context.Context, config Config, docker *client
return
}

err = handleContainer(ctx, docker, container.ID, egs, "start", config)
err = handleContainer(ctx, docker, container.ID, pub, "start", config)
if err != nil {
log.Logf(log.PriErr, "handling container: %v", err)

Expand All @@ -152,7 +136,7 @@ func handleExistingContainers(ctx context.Context, config Config, docker *client
}
}

func listen(ctx context.Context, config Config, docker *client.Client, egs *entryGroups, started time.Time) {
func listen(ctx context.Context, config Config, docker *client.Client, pub publisher, started time.Time) {
filter := make(client.Filters)
filter.Add("type", "container")
filter.Add("event", "destroy")
Expand Down Expand Up @@ -180,7 +164,7 @@ func listen(ctx context.Context, config Config, docker *client.Client, egs *entr

panic(fmt.Errorf("go error reading docker events: %w", err))
case msg := <-result.Messages:
err := handleContainer(ctx, docker, msg.Actor.ID, egs, msg.Action, config)
err := handleContainer(ctx, docker, msg.Actor.ID, pub, msg.Action, config)
if err != nil {
log.Logf(log.PriErr, "handling container: %v", err)
}
Expand Down
Loading