docker_cli_port_test.go 12 KB

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