docker_cli_port_test.go 12 KB

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