readme.go 2.2 KB

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