@@ -20,16 +20,26 @@ func main() {
20
20
}
21
21
22
22
currentNetworks := getJoinedNetworks (client , * containerName )
23
- bridgeNetworks := getBridgeNetworks (client )
23
+ bridgeNetworks := getActiveBridgeNetworks (client )
24
24
25
- for _ , id := range bridgeNetworks {
26
- if ! currentNetworks [id ] {
27
- err := client .ConnectNetwork (id , docker.NetworkConnectionOptions {
28
- Container : * containerName ,
29
- })
30
- if err != nil {
31
- panic (err )
32
- }
25
+ toJoin := getNetworksToJoin (currentNetworks , bridgeNetworks )
26
+ toLeave := getNetworksToLeave (currentNetworks , bridgeNetworks )
27
+
28
+ for _ , id := range toLeave {
29
+ err := client .DisconnectNetwork (id , docker.NetworkConnectionOptions {
30
+ Container : * containerName ,
31
+ })
32
+ if err != nil {
33
+ panic (err )
34
+ }
35
+ }
36
+
37
+ for _ , id := range toJoin {
38
+ err := client .ConnectNetwork (id , docker.NetworkConnectionOptions {
39
+ Container : * containerName ,
40
+ })
41
+ if err != nil {
42
+ panic (err )
33
43
}
34
44
}
35
45
}
@@ -49,16 +59,39 @@ func getJoinedNetworks(client *docker.Client, containerName string) (networks ma
49
59
return
50
60
}
51
61
52
- func getBridgeNetworks (client * docker.Client ) (ids []string ) {
53
- networks , err := client .ListNetworks ()
62
+ func getActiveBridgeNetworks (client * docker.Client ) (networks map [string ]bool ) {
63
+ networks = make (map [string ]bool )
64
+
65
+ allNetworks , err := client .ListNetworks ()
54
66
if err != nil {
55
67
panic (err )
56
68
}
57
69
58
- for _ , net := range networks {
59
- if net .Driver == "bridge" {
60
- ids = append ( ids , net .ID )
70
+ for _ , net := range allNetworks {
71
+ if net .Driver == "bridge" && len ( net . Containers ) > 0 {
72
+ networks [ net .ID ] = true
61
73
}
62
74
}
75
+
76
+ return
77
+ }
78
+
79
+ func getNetworksToJoin (currentNetworks map [string ]bool , bridgeNetworks map [string ]bool ) (ids []string ) {
80
+ for id := range bridgeNetworks {
81
+ if ! currentNetworks [id ] {
82
+ ids = append (ids , id )
83
+ }
84
+ }
85
+
86
+ return
87
+ }
88
+
89
+ func getNetworksToLeave (currentNetworks map [string ]bool , bridgeNetworks map [string ]bool ) (ids []string ) {
90
+ for id := range currentNetworks {
91
+ if ! bridgeNetworks [id ] {
92
+ ids = append (ids , id )
93
+ }
94
+ }
95
+
63
96
return
64
97
}
0 commit comments