docker_cli_port_test.go 12 KB

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