readme.go 1.8 KB

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