readme.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/docker/libnetwork"
  5. "github.com/docker/libnetwork/netutils"
  6. "github.com/docker/libnetwork/pkg/netlabel"
  7. "github.com/docker/libnetwork/pkg/options"
  8. )
  9. func main() {
  10. // Create a new controller instance
  11. controller := libnetwork.New()
  12. // Select and configure the network driver
  13. networkType := "bridge"
  14. driverOptions := options.Generic{}
  15. genericOption := make(map[string]interface{})
  16. genericOption[netlabel.GenericData] = driverOptions
  17. err := controller.ConfigureNetworkDriver(networkType, genericOption)
  18. if err != nil {
  19. return
  20. }
  21. // Create a network for containers to join.
  22. // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make of
  23. network, err := controller.NewNetwork(networkType, "network1")
  24. if err != nil {
  25. return
  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. return
  34. }
  35. // A container can join the endpoint by providing the container ID to the join
  36. // api which returns the sandbox key which can be used to access the sandbox
  37. // created for the container during join.
  38. // Join acceps Variadic arguments which will be made use of by libnetwork and Drivers
  39. _, err = ep.Join("container1",
  40. libnetwork.JoinOptionHostname("test"),
  41. libnetwork.JoinOptionDomainname("docker.io"))
  42. if err != nil {
  43. return
  44. }
  45. // libentwork client can check the endpoint's operational data via the Info() API
  46. epInfo, err := ep.Info()
  47. mapData, ok := epInfo[netlabel.PortMap]
  48. if ok {
  49. portMapping, ok := mapData.([]netutils.PortBinding)
  50. if ok {
  51. fmt.Printf("Current port mapping for endpoint %s: %v", ep.Name(), portMapping)
  52. }
  53. }
  54. }