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