readme.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package main
  2. import (
  3. "github.com/docker/libnetwork"
  4. "github.com/docker/libnetwork/pkg/options"
  5. "github.com/docker/libnetwork/sandbox"
  6. )
  7. func main() {
  8. // Create a new controller instance
  9. controller := libnetwork.New()
  10. option := options.Generic{}
  11. driver, err := controller.NewNetworkDriver("bridge", option)
  12. if err != nil {
  13. return
  14. }
  15. netOptions := options.Generic{}
  16. // Create a network for containers to join.
  17. network, err := controller.NewNetwork(driver, "network1", netOptions)
  18. if err != nil {
  19. return
  20. }
  21. // For a new container: create a sandbox instance (providing a unique key).
  22. // For linux it is a filesystem path
  23. networkPath := "/var/lib/docker/.../4d23e"
  24. networkNamespace, err := sandbox.NewSandbox(networkPath)
  25. if err != nil {
  26. return
  27. }
  28. // For each new container: allocate IP and interfaces. The returned network
  29. // settings will be used for container infos (inspect and such), as well as
  30. // iptables rules for port publishing. This info is contained or accessible
  31. // from the returned endpoint.
  32. ep, err := network.CreateEndpoint("Endpoint1", networkNamespace.Key(), nil)
  33. if err != nil {
  34. return
  35. }
  36. // Add interfaces to the namespace.
  37. sinfo := ep.SandboxInfo()
  38. for _, iface := range sinfo.Interfaces {
  39. if err := networkNamespace.AddInterface(iface); err != nil {
  40. return
  41. }
  42. }
  43. // Set the gateway IP
  44. if err := networkNamespace.SetGateway(sinfo.Gateway); err != nil {
  45. return
  46. }
  47. }