readme.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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("simplebridge", 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.
  31. _, sinfo, err := network.CreateEndpoint("Endpoint1", networkNamespace.Key(), "")
  32. if err != nil {
  33. return
  34. }
  35. // Add interfaces to the namespace.
  36. for _, iface := range sinfo.Interfaces {
  37. if err := networkNamespace.AddInterface(iface); err != nil {
  38. return
  39. }
  40. }
  41. // Set the gateway IP
  42. if err := networkNamespace.SetGateway(sinfo.Gateway); err != nil {
  43. return
  44. }
  45. }