port.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package client
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. flag "github.com/docker/docker/pkg/mflag"
  7. "github.com/docker/docker/pkg/nat"
  8. )
  9. // CmdPort lists port mappings for a container.
  10. // If a private port is specified, it also shows the public-facing port that is NATed to the private port.
  11. //
  12. // Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]]
  13. func (cli *DockerCli) CmdPort(args ...string) error {
  14. cmd := cli.Subcmd("port", []string{"CONTAINER [PRIVATE_PORT[/PROTO]]"}, "List port mappings for the CONTAINER, or lookup the public-facing port that\nis NAT-ed to the PRIVATE_PORT", true)
  15. cmd.Require(flag.Min, 1)
  16. cmd.ParseFlags(args, true)
  17. serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
  18. if err != nil {
  19. return err
  20. }
  21. defer serverResp.body.Close()
  22. var c struct {
  23. NetworkSettings struct {
  24. Ports nat.PortMap
  25. }
  26. }
  27. if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
  28. return err
  29. }
  30. if cmd.NArg() == 2 {
  31. var (
  32. port = cmd.Arg(1)
  33. proto = "tcp"
  34. parts = strings.SplitN(port, "/", 2)
  35. )
  36. if len(parts) == 2 && len(parts[1]) != 0 {
  37. port = parts[0]
  38. proto = parts[1]
  39. }
  40. natPort := port + "/" + proto
  41. newP, err := nat.NewPort(proto, port)
  42. if err != nil {
  43. return err
  44. }
  45. if frontends, exists := c.NetworkSettings.Ports[newP]; exists && frontends != nil {
  46. for _, frontend := range frontends {
  47. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIP, frontend.HostPort)
  48. }
  49. return nil
  50. }
  51. return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0))
  52. }
  53. for from, frontends := range c.NetworkSettings.Ports {
  54. for _, frontend := range frontends {
  55. fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIP, frontend.HostPort)
  56. }
  57. }
  58. return nil
  59. }