readme.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/docker/libnetwork"
  5. "github.com/docker/libnetwork/netlabel"
  6. "github.com/docker/libnetwork/netutils"
  7. "github.com/docker/libnetwork/options"
  8. )
  9. func main() {
  10. // Create a new controller instance
  11. controller, err := libnetwork.New()
  12. if err != nil {
  13. return
  14. }
  15. // Select and configure the network driver
  16. networkType := "bridge"
  17. driverOptions := options.Generic{}
  18. genericOption := make(map[string]interface{})
  19. genericOption[netlabel.GenericData] = driverOptions
  20. err = controller.ConfigureNetworkDriver(networkType, genericOption)
  21. if err != nil {
  22. return
  23. }
  24. // Create a network for containers to join.
  25. // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make of
  26. network, err := controller.NewNetwork(networkType, "network1")
  27. if err != nil {
  28. return
  29. }
  30. // For each new container: allocate IP and interfaces. The returned network
  31. // settings will be used for container infos (inspect and such), as well as
  32. // iptables rules for port publishing. This info is contained or accessible
  33. // from the returned endpoint.
  34. ep, err := network.CreateEndpoint("Endpoint1")
  35. if err != nil {
  36. return
  37. }
  38. // A container can join the endpoint by providing the container ID to the join
  39. // api which returns the sandbox key which can be used to access the sandbox
  40. // created for the container during join.
  41. // Join acceps Variadic arguments which will be made use of by libnetwork and Drivers
  42. _, err = ep.Join("container1",
  43. libnetwork.JoinOptionHostname("test"),
  44. libnetwork.JoinOptionDomainname("docker.io"))
  45. if err != nil {
  46. return
  47. }
  48. // libentwork client can check the endpoint's operational data via the Info() API
  49. epInfo, err := ep.Info()
  50. mapData, ok := epInfo[netlabel.PortMap]
  51. if ok {
  52. portMapping, ok := mapData.([]netutils.PortBinding)
  53. if ok {
  54. fmt.Printf("Current port mapping for endpoint %s: %v", ep.Name(), portMapping)
  55. }
  56. }
  57. }