docker_cli_port_test.go 12 KB

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