Skip to content
This repository has been archived by the owner on Dec 2, 2018. It is now read-only.

Commit

Permalink
Must maintain file's inode when rewriting
Browse files Browse the repository at this point in the history
Otherwise running containers will only see that the file bind-mounted
at `/etc/hosts` has been deleted.
  • Loading branch information
blalor committed Jul 28, 2014
1 parent 18ad99a commit f9a02d0
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 18 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.godeps/
docker-hosts
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@ Optionally specify `DOCKER_HOST` environment variable.

Then start a container:

docker run -i -t -v /path/to/hosts:/etc/hosts centos /bin/bash
docker run -i -t -v /path/to/hosts:/etc/hosts:ro centos /bin/bash

Within the `centos` container, you'll see `/etc/hosts` has an entry for the
container you just started, as well as any other containers already running.
`/etc/hosts` will continue to reflect all of the containers currently running on
this Docker host.

The **only** container that should have write access to the generated hosts file
is the container running this application.

[gpm]: https://github.com/pote/gpm
[gvp]: https://github.com/pote/gvp
26 changes: 9 additions & 17 deletions hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
dockerapi "github.com/fsouza/go-dockerclient"
"io/ioutil"
"log"
"os"
"strings"
Expand Down Expand Up @@ -67,26 +66,25 @@ func NewHosts(docker *dockerapi.Client, path string) *Hosts {
return hosts
}

func (h *Hosts) WriteFile() error {
tempFile, err := ioutil.TempFile(os.TempDir(), "hosts")
func (h *Hosts) WriteFile() {
file, err := os.Create(h.path)

if err != nil {
return err
log.Println("unable to write to", h.path, err)
return
}

defer file.Close()

for _, entry := range h.entries {
tempFile.WriteString(strings.Join(
file.WriteString(strings.Join(
append(
[]string{entry.IPAddress, entry.CanonicalHostname},
entry.Aliases...,
),
"\t",
) + "\n")
}

tempFile.Close() // can't close? ignore!

return os.Rename(tempFile.Name(), h.path)
}

func (h *Hosts) Add(containerId string) {
Expand All @@ -105,10 +103,7 @@ func (h *Hosts) Add(containerId string) {
// Aliases: []string{container.Name[1:]}, // could contain "_"
}

err = h.WriteFile()
if err != nil {
log.Println("unable to write file", err)
}
h.WriteFile()
}

func (h *Hosts) Remove(containerId string) {
Expand All @@ -117,8 +112,5 @@ func (h *Hosts) Remove(containerId string) {

delete(h.entries, containerId)

err := h.WriteFile()
if err != nil {
log.Println("unable to write file", err)
}
h.WriteFile()
}

0 comments on commit f9a02d0

Please sign in to comment.