Skip to content

Commit

Permalink
handle docker-compose network fix dup shinebayar-g#1 in Go
Browse files Browse the repository at this point in the history
  • Loading branch information
shinebayar-g committed Sep 7, 2021
1 parent dd11dcc commit 6fb26ae
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func isUfwManaged(containerLabel string) bool {

func handleUfwRule(ch <-chan ufwEvent) {
for event := range ch {
for port, portMaps := range event.container.NetworkSettings.Ports {
for port, portMaps := range event.container.HostConfig.PortBindings {
// List is non empty if port is published
if len(portMaps) > 0 {
ufwSourceList := []ufwSource{}
Expand All @@ -66,13 +66,19 @@ func handleUfwRule(ch <-chan ufwEvent) {
ufwSourceList = append(ufwSourceList, ufwSource{CIDR: "any"})
}

containerIP := event.container.NetworkSettings.IPAddress
if containerIP == "" {
networkMode := event.container.HostConfig.NetworkMode.NetworkName()
containerIP = event.container.NetworkSettings.Networks[networkMode].IPAddress
}

for _, source := range ufwSourceList {
var cmd *exec.Cmd
if event.msg.Action == "start" {
cmd = exec.Command("ufw", "route", "allow", "proto", port.Proto(), "from", source.CIDR, "to", event.container.NetworkSettings.IPAddress, "port", port.Port(), "comment", event.msg.Actor.Attributes["name"]+":"+event.msg.ID[:12]+source.comment)
cmd = exec.Command("ufw", "route", "allow", "proto", port.Proto(), "from", source.CIDR, "to", containerIP, "port", port.Port(), "comment", event.msg.Actor.Attributes["name"]+":"+event.msg.ID[:12]+source.comment)
fmt.Println("ufw-docker-automated: Adding rule:", cmd)
} else {
cmd = exec.Command("ufw", "route", "delete", "allow", "proto", port.Proto(), "from", source.CIDR, "to", event.container.NetworkSettings.IPAddress, "port", port.Port(), "comment", event.msg.Actor.Attributes["name"]+":"+event.msg.ID[:12]+source.comment)
cmd = exec.Command("ufw", "route", "delete", "allow", "proto", port.Proto(), "from", source.CIDR, "to", containerIP, "port", port.Port(), "comment", event.msg.Actor.Attributes["name"]+":"+event.msg.ID[:12]+source.comment)
fmt.Println("ufw-docker-automated: Deleting rule:", cmd)
}
var stdout, stderr bytes.Buffer
Expand Down

0 comments on commit 6fb26ae

Please sign in to comment.