readme.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/docker/docker/libnetwork"
  6. "github.com/docker/docker/libnetwork/config"
  7. "github.com/docker/docker/libnetwork/netlabel"
  8. "github.com/docker/docker/libnetwork/options"
  9. )
  10. func main() {
  11. // Select and configure the network driver
  12. networkType := "bridge"
  13. // Create a new controller instance
  14. driverOptions := options.Generic{}
  15. genericOption := make(map[string]interface{})
  16. genericOption[netlabel.GenericData] = driverOptions
  17. controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
  18. if err != nil {
  19. log.Fatalf("libnetwork.New: %s", err)
  20. }
  21. // Create a network for containers to join.
  22. // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use.
  23. network, err := controller.NewNetwork(networkType, "network1", "")
  24. if err != nil {
  25. log.Fatalf("controller.NewNetwork: %s", err)
  26. }
  27. // For each new container: allocate IP and interfaces. The returned network
  28. // settings will be used for container infos (inspect and such), as well as
  29. // iptables rules for port publishing. This info is contained or accessible
  30. // from the returned endpoint.
  31. ep, err := network.CreateEndpoint("Endpoint1")
  32. if err != nil {
  33. log.Fatalf("network.CreateEndpoint: %s", err)
  34. }
  35. // Create the sandbox for the container.
  36. // NewSandbox accepts Variadic optional arguments which libnetwork can use.
  37. sbx, err := controller.NewSandbox("container1",
  38. libnetwork.OptionHostname("test"),
  39. libnetwork.OptionDomainname("example.com"))
  40. if err != nil {
  41. log.Fatalf("controller.NewSandbox: %s", err)
  42. }
  43. // A sandbox can join the endpoint via the join api.
  44. err = ep.Join(sbx)
  45. if err != nil {
  46. log.Fatalf("ep.Join: %s", err)
  47. }
  48. // libnetwork client can check the endpoint's operational data via the Info() API
  49. epInfo, err := ep.DriverInfo()
  50. if err != nil {
  51. log.Fatalf("ep.DriverInfo: %s", err)
  52. }
  53. macAddress, ok := epInfo[netlabel.MacAddress]
  54. if !ok {
  55. log.Fatal("failed to get mac address from endpoint info")
  56. }
  57. fmt.Printf("Joined endpoint %s (%s) to sandbox %s (%s)\n", ep.Name(), macAddress, sbx.ContainerID(), sbx.Key())
  58. }