2015-03-24 23:57:23 -04:00
package client
import (
2015-04-04 00:06:48 -04:00
"encoding/json"
2015-03-24 23:57:23 -04:00
"fmt"
"strings"
"github.com/docker/docker/nat"
flag "github.com/docker/docker/pkg/mflag"
)
2015-03-25 13:34:41 -04:00
// CmdPort lists port mappings for a container.
// If a private port is specified, it also shows the public-facing port that is NATed to the private port.
//
// Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]]
2015-03-24 23:57:23 -04:00
func ( cli * DockerCli ) CmdPort ( args ... string ) error {
cmd := cli . Subcmd ( "port" , "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 )
cmd . Require ( flag . Min , 1 )
2015-03-28 21:22:46 -04:00
cmd . ParseFlags ( args , true )
2015-03-24 23:57:23 -04:00
2015-01-12 14:56:01 -05:00
stream , _ , err := cli . call ( "GET" , "/containers/" + cmd . Arg ( 0 ) + "/json" , nil , nil )
2015-03-24 23:57:23 -04:00
if err != nil {
return err
}
2015-04-04 00:06:48 -04:00
var c struct {
NetworkSettings struct {
Ports nat . PortMap
}
2015-03-24 23:57:23 -04:00
}
2015-04-04 00:06:48 -04:00
if err := json . NewDecoder ( stream ) . Decode ( & c ) ; err != nil {
2015-03-24 23:57:23 -04:00
return err
}
if cmd . NArg ( ) == 2 {
var (
port = cmd . Arg ( 1 )
proto = "tcp"
parts = strings . SplitN ( port , "/" , 2 )
)
if len ( parts ) == 2 && len ( parts [ 1 ] ) != 0 {
port = parts [ 0 ]
proto = parts [ 1 ]
}
natPort := port + "/" + proto
2015-04-04 00:06:48 -04:00
if frontends , exists := c . NetworkSettings . Ports [ nat . Port ( port + "/" + proto ) ] ; exists && frontends != nil {
2015-03-24 23:57:23 -04:00
for _ , frontend := range frontends {
fmt . Fprintf ( cli . out , "%s:%s\n" , frontend . HostIp , frontend . HostPort )
}
return nil
}
return fmt . Errorf ( "Error: No public port '%s' published for %s" , natPort , cmd . Arg ( 0 ) )
}
2015-04-04 00:06:48 -04:00
for from , frontends := range c . NetworkSettings . Ports {
2015-03-24 23:57:23 -04:00
for _ , frontend := range frontends {
fmt . Fprintf ( cli . out , "%s -> %s:%s\n" , from , frontend . HostIp , frontend . HostPort )
}
}
return nil
}