port.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/cli"
  7. "github.com/docker/docker/cli/command"
  8. "github.com/docker/go-connections/nat"
  9. "github.com/spf13/cobra"
  10. )
  11. type portOptions struct {
  12. container string
  13. port string
  14. }
  15. // NewPortCommand creates a new cobra.Command for `docker port`
  16. func NewPortCommand(dockerCli *command.DockerCli) *cobra.Command {
  17. var opts portOptions
  18. cmd := &cobra.Command{
  19. Use: "port CONTAINER [PRIVATE_PORT[/PROTO]]",
  20. Short: "List port mappings or a specific mapping for the container",
  21. Args: cli.RequiresRangeArgs(1, 2),
  22. RunE: func(cmd *cobra.Command, args []string) error {
  23. opts.container = args[0]
  24. if len(args) > 1 {
  25. opts.port = args[1]
  26. }
  27. return runPort(dockerCli, &opts)
  28. },
  29. }
  30. return cmd
  31. }
  32. func runPort(dockerCli *command.DockerCli, opts *portOptions) error {
  33. ctx := context.Background()
  34. c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
  35. if err != nil {
  36. return err
  37. }
  38. if opts.port != "" {
  39. port := opts.port
  40. proto := "tcp"
  41. parts := strings.SplitN(port, "/", 2)
  42. if len(parts) == 2 && len(parts[1]) != 0 {
  43. port = parts[0]
  44. proto = parts[1]
  45. }
  46. natPort := port + "/" + proto
  47. newP, err := nat.NewPort(proto, port)
  48. if err != nil {
  49. return err
  50. }
  51. if frontends, exists := c.NetworkSettings.Ports[newP]; exists && frontends != nil {
  52. for _, frontend := range frontends {
  53. fmt.Fprintf(dockerCli.Out(), "%s:%s\n", frontend.HostIP, frontend.HostPort)
  54. }
  55. return nil
  56. }
  57. return fmt.Errorf("Error: No public port '%s' published for %s", natPort, opts.container)
  58. }
  59. for from, frontends := range c.NetworkSettings.Ports {
  60. for _, frontend := range frontends {
  61. fmt.Fprintf(dockerCli.Out(), "%s -> %s:%s\n", from, frontend.HostIP, frontend.HostPort)
  62. }
  63. }
  64. return nil
  65. }