port.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/client"
  7. "github.com/docker/docker/cli"
  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 *client.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. cmd.SetFlagErrorFunc(flagErrorFunc)
  31. return cmd
  32. }
  33. func runPort(dockerCli *client.DockerCli, opts *portOptions) error {
  34. ctx := context.Background()
  35. c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
  36. if err != nil {
  37. return err
  38. }
  39. if opts.port != "" {
  40. port := opts.port
  41. proto := "tcp"
  42. parts := strings.SplitN(port, "/", 2)
  43. if len(parts) == 2 && len(parts[1]) != 0 {
  44. port = parts[0]
  45. proto = parts[1]
  46. }
  47. natPort := port + "/" + proto
  48. newP, err := nat.NewPort(proto, port)
  49. if err != nil {
  50. return err
  51. }
  52. if frontends, exists := c.NetworkSettings.Ports[newP]; exists && frontends != nil {
  53. for _, frontend := range frontends {
  54. fmt.Fprintf(dockerCli.Out(), "%s:%s\n", frontend.HostIP, frontend.HostPort)
  55. }
  56. return nil
  57. }
  58. return fmt.Errorf("Error: No public port '%s' published for %s", natPort, opts.container)
  59. }
  60. for from, frontends := range c.NetworkSettings.Ports {
  61. for _, frontend := range frontends {
  62. fmt.Fprintf(dockerCli.Out(), "%s -> %s:%s\n", from, frontend.HostIP, frontend.HostPort)
  63. }
  64. }
  65. return nil
  66. }