docker_cli_port_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "regexp"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "testing"
  10. "github.com/docker/docker/integration-cli/cli"
  11. "github.com/docker/docker/testutil"
  12. "gotest.tools/v3/assert"
  13. is "gotest.tools/v3/assert/cmp"
  14. )
  15. type DockerCLIPortSuite struct {
  16. ds *DockerSuite
  17. }
  18. func (s *DockerCLIPortSuite) TearDownTest(ctx context.Context, c *testing.T) {
  19. s.ds.TearDownTest(ctx, c)
  20. }
  21. func (s *DockerCLIPortSuite) OnTimeout(c *testing.T) {
  22. s.ds.OnTimeout(c)
  23. }
  24. func (s *DockerCLIPortSuite) TestPortList(c *testing.T) {
  25. testRequires(c, DaemonIsLinux)
  26. ctx := testutil.GetContext(c)
  27. // one port
  28. firstID := cli.DockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "top").Stdout()
  29. firstID = strings.TrimSpace(firstID)
  30. out := cli.DockerCmd(c, "port", firstID, "80").Stdout()
  31. assertPortList(c, out, []string{"0.0.0.0:9876", "[::]:9876"})
  32. out = cli.DockerCmd(c, "port", firstID).Stdout()
  33. assertPortList(c, out, []string{"80/tcp -> 0.0.0.0:9876", "80/tcp -> [::]:9876"})
  34. cli.DockerCmd(c, "rm", "-f", firstID)
  35. // three port
  36. id := cli.DockerCmd(c, "run", "-d",
  37. "-p", "9876:80",
  38. "-p", "9877:81",
  39. "-p", "9878:82",
  40. "busybox", "top",
  41. ).Stdout()
  42. id = strings.TrimSpace(id)
  43. out = cli.DockerCmd(c, "port", id, "80").Stdout()
  44. assertPortList(c, out, []string{"0.0.0.0:9876", "[::]:9876"})
  45. out = cli.DockerCmd(c, "port", id).Stdout()
  46. assertPortList(c, out, []string{
  47. "80/tcp -> 0.0.0.0:9876",
  48. "80/tcp -> [::]:9876",
  49. "81/tcp -> 0.0.0.0:9877",
  50. "81/tcp -> [::]:9877",
  51. "82/tcp -> 0.0.0.0:9878",
  52. "82/tcp -> [::]:9878",
  53. })
  54. cli.DockerCmd(c, "rm", "-f", id)
  55. // more and one port mapped to the same container port
  56. id = cli.DockerCmd(c, "run", "-d",
  57. "-p", "9876:80",
  58. "-p", "9999:80",
  59. "-p", "9877:81",
  60. "-p", "9878:82",
  61. "busybox", "top",
  62. ).Stdout()
  63. id = strings.TrimSpace(id)
  64. out = cli.DockerCmd(c, "port", id, "80").Stdout()
  65. assertPortList(c, out, []string{"0.0.0.0:9876", "[::]:9876", "0.0.0.0:9999", "[::]:9999"})
  66. out = cli.DockerCmd(c, "port", id).Stdout()
  67. assertPortList(c, out, []string{
  68. "80/tcp -> 0.0.0.0:9876",
  69. "80/tcp -> 0.0.0.0:9999",
  70. "80/tcp -> [::]:9876",
  71. "80/tcp -> [::]:9999",
  72. "81/tcp -> 0.0.0.0:9877",
  73. "81/tcp -> [::]:9877",
  74. "82/tcp -> 0.0.0.0:9878",
  75. "82/tcp -> [::]:9878",
  76. })
  77. cli.DockerCmd(c, "rm", "-f", id)
  78. testRange := func() {
  79. // host port ranges used
  80. IDs := make([]string, 3)
  81. for i := 0; i < 3; i++ {
  82. out = cli.DockerCmd(c, "run", "-d", "-p", "9090-9092:80", "busybox", "top").Stdout()
  83. IDs[i] = strings.TrimSpace(out)
  84. out = cli.DockerCmd(c, "port", IDs[i]).Stdout()
  85. assertPortList(c, out, []string{
  86. fmt.Sprintf("80/tcp -> 0.0.0.0:%d", 9090+i),
  87. fmt.Sprintf("80/tcp -> [::]:%d", 9090+i),
  88. })
  89. }
  90. // test port range exhaustion
  91. out, _, err := dockerCmdWithError("run", "-d", "-p", "9090-9092:80", "busybox", "top")
  92. // Exhausted port range did not return an error
  93. assert.Assert(c, err != nil, "out: %s", out)
  94. for i := 0; i < 3; i++ {
  95. cli.DockerCmd(c, "rm", "-f", IDs[i])
  96. }
  97. }
  98. testRange()
  99. // Verify we ran re-use port ranges after they are no longer in use.
  100. testRange()
  101. // test invalid port ranges
  102. for _, invalidRange := range []string{"9090-9089:80", "9090-:80", "-9090:80"} {
  103. out, _, err := dockerCmdWithError("run", "-d", "-p", invalidRange, "busybox", "top")
  104. // Port range should have returned an error
  105. assert.Assert(c, err != nil, "out: %s", out)
  106. }
  107. // test host range:container range spec.
  108. id = cli.DockerCmd(c, "run", "-d", "-p", "9800-9803:80-83", "busybox", "top").Stdout()
  109. id = strings.TrimSpace(id)
  110. out = cli.DockerCmd(c, "port", id).Stdout()
  111. assertPortList(c, out, []string{
  112. "80/tcp -> 0.0.0.0:9800",
  113. "80/tcp -> [::]:9800",
  114. "81/tcp -> 0.0.0.0:9801",
  115. "81/tcp -> [::]:9801",
  116. "82/tcp -> 0.0.0.0:9802",
  117. "82/tcp -> [::]:9802",
  118. "83/tcp -> 0.0.0.0:9803",
  119. "83/tcp -> [::]:9803",
  120. })
  121. cli.DockerCmd(c, "rm", "-f", id)
  122. // test mixing protocols in same port range
  123. id = cli.DockerCmd(c, "run", "-d", "-p", "8000-8080:80", "-p", "8000-8080:80/udp", "busybox", "top").Stdout()
  124. id = strings.TrimSpace(id)
  125. out = cli.DockerCmd(c, "port", id).Stdout()
  126. // Running this test multiple times causes the TCP port to increment.
  127. err := assertPortRange(ctx, id, []int{8000, 8080}, []int{8000, 8080})
  128. assert.Check(c, err)
  129. cli.DockerCmd(c, "rm", "-f", id)
  130. }
  131. func assertPortList(c *testing.T, out string, expected []string) {
  132. c.Helper()
  133. lines := strings.Split(strings.Trim(out, "\n "), "\n")
  134. assert.Assert(c, is.Len(lines, len(expected)), "exepcted: %s", strings.Join(expected, ", "))
  135. sort.Strings(lines)
  136. sort.Strings(expected)
  137. // "docker port" does not yet have a "--format" flag, and older versions
  138. // of the CLI used an incorrect output format for mappings on IPv6 addresses
  139. // for example, "80/tcp -> :::80" instead of "80/tcp -> [::]:80".
  140. oldFormat := func(mapping string) string {
  141. old := strings.Replace(mapping, "[", "", 1)
  142. old = strings.Replace(old, "]:", ":", 1)
  143. return old
  144. }
  145. for i := 0; i < len(expected); i++ {
  146. if lines[i] == expected[i] {
  147. continue
  148. }
  149. assert.Equal(c, lines[i], oldFormat(expected[i]))
  150. }
  151. }
  152. func assertPortRange(ctx context.Context, id string, expectedTCP, expectedUDP []int) error {
  153. client := testEnv.APIClient()
  154. inspect, err := client.ContainerInspect(ctx, id)
  155. if err != nil {
  156. return err
  157. }
  158. var validTCP, validUDP bool
  159. for portAndProto, binding := range inspect.NetworkSettings.Ports {
  160. if portAndProto.Proto() == "tcp" && len(expectedTCP) == 0 {
  161. continue
  162. }
  163. if portAndProto.Proto() == "udp" && len(expectedTCP) == 0 {
  164. continue
  165. }
  166. for _, b := range binding {
  167. port, err := strconv.Atoi(b.HostPort)
  168. if err != nil {
  169. return err
  170. }
  171. if len(expectedTCP) > 0 {
  172. if port < expectedTCP[0] || port > expectedTCP[1] {
  173. return fmt.Errorf("tcp port (%d) not in range expected range %d-%d", port, expectedTCP[0], expectedTCP[1])
  174. }
  175. validTCP = true
  176. }
  177. if len(expectedUDP) > 0 {
  178. if port < expectedUDP[0] || port > expectedUDP[1] {
  179. return fmt.Errorf("udp port (%d) not in range expected range %d-%d", port, expectedUDP[0], expectedUDP[1])
  180. }
  181. validUDP = true
  182. }
  183. }
  184. }
  185. if !validTCP {
  186. return fmt.Errorf("tcp port not found")
  187. }
  188. if !validUDP {
  189. return fmt.Errorf("udp port not found")
  190. }
  191. return nil
  192. }
  193. func stopRemoveContainer(id string, c *testing.T) {
  194. cli.DockerCmd(c, "rm", "-f", id)
  195. }
  196. func (s *DockerCLIPortSuite) TestUnpublishedPortsInPsOutput(c *testing.T) {
  197. testRequires(c, DaemonIsLinux)
  198. // Run busybox with command line expose (equivalent to EXPOSE in image's Dockerfile) for the following ports
  199. port1 := 80
  200. port2 := 443
  201. expose1 := fmt.Sprintf("--expose=%d", port1)
  202. expose2 := fmt.Sprintf("--expose=%d", port2)
  203. cli.DockerCmd(c, "run", "-d", expose1, expose2, "busybox", "sleep", "5")
  204. // Check docker ps o/p for last created container reports the unpublished ports
  205. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  206. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  207. out := cli.DockerCmd(c, "ps", "-n=1").Stdout()
  208. // Missing unpublished ports in docker ps output
  209. assert.Assert(c, strings.Contains(out, unpPort1))
  210. // Missing unpublished ports in docker ps output
  211. assert.Assert(c, strings.Contains(out, unpPort2))
  212. // Run the container forcing to publish the exposed ports
  213. cli.DockerCmd(c, "run", "-d", "-P", expose1, expose2, "busybox", "sleep", "5")
  214. // Check docker ps o/p for last created container reports the exposed ports in the port bindings
  215. expBndRegx1 := regexp.MustCompile(`0.0.0.0:\d\d\d\d\d->` + unpPort1)
  216. expBndRegx2 := regexp.MustCompile(`0.0.0.0:\d\d\d\d\d->` + unpPort2)
  217. out = cli.DockerCmd(c, "ps", "-n=1").Stdout()
  218. // Cannot find expected port binding port (0.0.0.0:xxxxx->unpPort1) in docker ps output
  219. assert.Equal(c, expBndRegx1.MatchString(out), true, fmt.Sprintf("out: %s; unpPort1: %s", out, unpPort1))
  220. // Cannot find expected port binding port (0.0.0.0:xxxxx->unpPort2) in docker ps output
  221. assert.Equal(c, expBndRegx2.MatchString(out), true, fmt.Sprintf("out: %s; unpPort2: %s", out, unpPort2))
  222. // Run the container specifying explicit port bindings for the exposed ports
  223. offset := 10000
  224. pFlag1 := fmt.Sprintf("%d:%d", offset+port1, port1)
  225. pFlag2 := fmt.Sprintf("%d:%d", offset+port2, port2)
  226. id := cli.DockerCmd(c, "run", "-d", "-p", pFlag1, "-p", pFlag2, expose1, expose2, "busybox", "sleep", "5").Stdout()
  227. id = strings.TrimSpace(id)
  228. // Check docker ps o/p for last created container reports the specified port mappings
  229. expBnd1 := fmt.Sprintf("0.0.0.0:%d->%s", offset+port1, unpPort1)
  230. expBnd2 := fmt.Sprintf("0.0.0.0:%d->%s", offset+port2, unpPort2)
  231. out = cli.DockerCmd(c, "ps", "-n=1").Stdout()
  232. // Cannot find expected port binding (expBnd1) in docker ps output
  233. assert.Assert(c, strings.Contains(out, expBnd1))
  234. // Cannot find expected port binding (expBnd2) in docker ps output
  235. assert.Assert(c, strings.Contains(out, expBnd2))
  236. // Remove container now otherwise it will interfere with next test
  237. stopRemoveContainer(id, c)
  238. // Run the container with explicit port bindings and no exposed ports
  239. id = cli.DockerCmd(c, "run", "-d", "-p", pFlag1, "-p", pFlag2, "busybox", "sleep", "5").Stdout()
  240. id = strings.TrimSpace(id)
  241. // Check docker ps o/p for last created container reports the specified port mappings
  242. out = cli.DockerCmd(c, "ps", "-n=1").Stdout()
  243. // Cannot find expected port binding (expBnd1) in docker ps output
  244. assert.Assert(c, strings.Contains(out, expBnd1))
  245. // Cannot find expected port binding (expBnd2) in docker ps output
  246. assert.Assert(c, strings.Contains(out, expBnd2))
  247. // Remove container now otherwise it will interfere with next test
  248. stopRemoveContainer(id, c)
  249. // Run the container with one unpublished exposed port and one explicit port binding
  250. cli.DockerCmd(c, "run", "-d", expose1, "-p", pFlag2, "busybox", "sleep", "5")
  251. // Check docker ps o/p for last created container reports the specified unpublished port and port mapping
  252. out = cli.DockerCmd(c, "ps", "-n=1").Stdout()
  253. // Missing unpublished exposed ports (unpPort1) in docker ps output
  254. assert.Assert(c, strings.Contains(out, unpPort1))
  255. // Missing port binding (expBnd2) in docker ps output
  256. assert.Assert(c, strings.Contains(out, expBnd2))
  257. }
  258. func (s *DockerCLIPortSuite) TestPortHostBinding(c *testing.T) {
  259. testRequires(c, DaemonIsLinux, NotUserNamespace)
  260. firstID := cli.DockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "nc", "-l", "-p", "80").Stdout()
  261. firstID = strings.TrimSpace(firstID)
  262. out := cli.DockerCmd(c, "port", firstID, "80").Stdout()
  263. assertPortList(c, out, []string{"0.0.0.0:9876", "[::]:9876"})
  264. cli.DockerCmd(c, "run", "--net=host", "busybox", "nc", "localhost", "9876")
  265. cli.DockerCmd(c, "rm", "-f", firstID)
  266. out, _, err := dockerCmdWithError("run", "--net=host", "busybox", "nc", "localhost", "9876")
  267. // Port is still bound after the Container is removed
  268. assert.Assert(c, err != nil, out)
  269. }
  270. func (s *DockerCLIPortSuite) TestPortExposeHostBinding(c *testing.T) {
  271. testRequires(c, DaemonIsLinux, NotUserNamespace)
  272. firstID := cli.DockerCmd(c, "run", "-d", "-P", "--expose", "80", "busybox", "nc", "-l", "-p", "80").Stdout()
  273. firstID = strings.TrimSpace(firstID)
  274. exposedPort := cli.DockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, firstID).Stdout()
  275. exposedPort = strings.TrimSpace(exposedPort)
  276. cli.DockerCmd(c, "run", "--net=host", "busybox", "nc", "127.0.0.1", exposedPort)
  277. cli.DockerCmd(c, "rm", "-f", firstID)
  278. out, _, err := dockerCmdWithError("run", "--net=host", "busybox", "nc", "127.0.0.1", exposedPort)
  279. // Port is still bound after the Container is removed
  280. assert.Assert(c, err != nil, "out: %s", out)
  281. }
  282. func (s *DockerCLIPortSuite) TestPortBindingOnSandbox(c *testing.T) {
  283. testRequires(c, DaemonIsLinux, NotUserNamespace)
  284. cli.DockerCmd(c, "network", "create", "--internal", "-d", "bridge", "internal-net")
  285. nr := getNetworkResource(c, "internal-net")
  286. assert.Equal(c, nr.Internal, true)
  287. cli.DockerCmd(c, "run", "--net", "internal-net", "-d", "--name", "c1", "-p", "8080:8080", "busybox", "nc", "-l", "-p", "8080")
  288. cli.WaitRun(c, "c1")
  289. _, _, err := dockerCmdWithError("run", "--net=host", "busybox", "nc", "localhost", "8080")
  290. assert.Assert(c, err != nil, "Port mapping on internal network is expected to fail")
  291. // Connect container to another normal bridge network
  292. cli.DockerCmd(c, "network", "create", "-d", "bridge", "foo-net")
  293. cli.DockerCmd(c, "network", "connect", "foo-net", "c1")
  294. _, _, err = dockerCmdWithError("run", "--net=host", "busybox", "nc", "localhost", "8080")
  295. assert.Assert(c, err == nil, "Port mapping on the new network is expected to succeed")
  296. }