readme.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/docker/libnetwork"
  5. "github.com/docker/libnetwork/config"
  6. "github.com/docker/libnetwork/netlabel"
  7. "github.com/docker/libnetwork/options"
  8. "github.com/docker/libnetwork/types"
  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. return
  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. 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. // Create the sandbox for the containr.
  36. sbx, err := controller.NewSandbox("container1",
  37. libnetwork.OptionHostname("test"),
  38. libnetwork.OptionDomainname("docker.io"))
  39. // A sandbox can join the endpoint via the join api.
  40. // Join accepts Variadic arguments which libnetwork and Drivers can use.
  41. err = ep.Join(sbx)
  42. if err != nil {
  43. return
  44. }
  45. // libnetwork client can check the endpoint's operational data via the Info() API
  46. epInfo, err := ep.DriverInfo()
  47. mapData, ok := epInfo[netlabel.PortMap]
  48. if ok {
  49. portMapping, ok := mapData.([]types.PortBinding)
  50. if ok {
  51. fmt.Printf("Current port mapping for endpoint %s: %v", ep.Name(), portMapping)
  52. }
  53. }
  54. }