docker_cli_create_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "reflect"
  7. "strings"
  8. "testing"
  9. "github.com/docker/docker/integration-cli/cli"
  10. "github.com/docker/docker/integration-cli/cli/build"
  11. "github.com/docker/docker/pkg/stringid"
  12. "github.com/docker/docker/testutil/fakecontext"
  13. "github.com/docker/go-connections/nat"
  14. "gotest.tools/v3/assert"
  15. is "gotest.tools/v3/assert/cmp"
  16. )
  17. type DockerCLICreateSuite struct {
  18. ds *DockerSuite
  19. }
  20. func (s *DockerCLICreateSuite) TearDownTest(c *testing.T) {
  21. s.ds.TearDownTest(c)
  22. }
  23. func (s *DockerCLICreateSuite) OnTimeout(c *testing.T) {
  24. s.ds.OnTimeout(c)
  25. }
  26. // Make sure we can create a simple container with some args
  27. func (s *DockerCLICreateSuite) TestCreateArgs(c *testing.T) {
  28. // Intentionally clear entrypoint, as the Windows busybox image needs an entrypoint, which breaks this test
  29. out, _ := dockerCmd(c, "create", "--entrypoint=", "busybox", "command", "arg1", "arg2", "arg with space", "-c", "flags")
  30. cleanedContainerID := strings.TrimSpace(out)
  31. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  32. var containers []struct {
  33. Path string
  34. Args []string
  35. }
  36. err := json.Unmarshal([]byte(out), &containers)
  37. assert.Assert(c, err == nil, "Error inspecting the container: %s", err)
  38. assert.Equal(c, len(containers), 1)
  39. cont := containers[0]
  40. assert.Equal(c, cont.Path, "command", fmt.Sprintf("Unexpected container path. Expected command, received: %s", cont.Path))
  41. b := false
  42. expected := []string{"arg1", "arg2", "arg with space", "-c", "flags"}
  43. for i, arg := range expected {
  44. if arg != cont.Args[i] {
  45. b = true
  46. break
  47. }
  48. }
  49. if len(cont.Args) != len(expected) || b {
  50. c.Fatalf("Unexpected args. Expected %v, received: %v", expected, cont.Args)
  51. }
  52. }
  53. // Make sure we can grow the container's rootfs at creation time.
  54. func (s *DockerCLICreateSuite) TestCreateGrowRootfs(c *testing.T) {
  55. // Windows and Devicemapper support growing the rootfs
  56. if testEnv.OSType != "windows" {
  57. testRequires(c, Devicemapper)
  58. }
  59. out, _ := dockerCmd(c, "create", "--storage-opt", "size=120G", "busybox")
  60. cleanedContainerID := strings.TrimSpace(out)
  61. inspectOut := inspectField(c, cleanedContainerID, "HostConfig.StorageOpt")
  62. assert.Equal(c, inspectOut, "map[size:120G]")
  63. }
  64. // Make sure we cannot shrink the container's rootfs at creation time.
  65. func (s *DockerCLICreateSuite) TestCreateShrinkRootfs(c *testing.T) {
  66. testRequires(c, Devicemapper)
  67. // Ensure this fails because of the defaultBaseFsSize is 10G
  68. out, _, err := dockerCmdWithError("create", "--storage-opt", "size=5G", "busybox")
  69. assert.ErrorContains(c, err, "", out)
  70. assert.Assert(c, strings.Contains(out, "Container size cannot be smaller than"))
  71. }
  72. // Make sure we can set hostconfig options too
  73. func (s *DockerCLICreateSuite) TestCreateHostConfig(c *testing.T) {
  74. out, _ := dockerCmd(c, "create", "-P", "busybox", "echo")
  75. cleanedContainerID := strings.TrimSpace(out)
  76. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  77. var containers []struct {
  78. HostConfig *struct {
  79. PublishAllPorts bool
  80. }
  81. }
  82. err := json.Unmarshal([]byte(out), &containers)
  83. assert.Assert(c, err == nil, "Error inspecting the container: %s", err)
  84. assert.Equal(c, len(containers), 1)
  85. cont := containers[0]
  86. assert.Assert(c, cont.HostConfig != nil, "Expected HostConfig, got none")
  87. assert.Assert(c, cont.HostConfig.PublishAllPorts, "Expected PublishAllPorts, got false")
  88. }
  89. func (s *DockerCLICreateSuite) TestCreateWithPortRange(c *testing.T) {
  90. out, _ := dockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo")
  91. cleanedContainerID := strings.TrimSpace(out)
  92. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  93. var containers []struct {
  94. HostConfig *struct {
  95. PortBindings map[nat.Port][]nat.PortBinding
  96. }
  97. }
  98. err := json.Unmarshal([]byte(out), &containers)
  99. assert.Assert(c, err == nil, "Error inspecting the container: %s", err)
  100. assert.Equal(c, len(containers), 1)
  101. cont := containers[0]
  102. assert.Assert(c, cont.HostConfig != nil, "Expected HostConfig, got none")
  103. assert.Equal(c, len(cont.HostConfig.PortBindings), 4, fmt.Sprintf("Expected 4 ports bindings, got %d", len(cont.HostConfig.PortBindings)))
  104. for k, v := range cont.HostConfig.PortBindings {
  105. assert.Equal(c, len(v), 1, fmt.Sprintf("Expected 1 ports binding, for the port %s but found %s", k, v))
  106. assert.Equal(c, k.Port(), v[0].HostPort, fmt.Sprintf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
  107. }
  108. }
  109. func (s *DockerCLICreateSuite) TestCreateWithLargePortRange(c *testing.T) {
  110. out, _ := dockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo")
  111. cleanedContainerID := strings.TrimSpace(out)
  112. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  113. var containers []struct {
  114. HostConfig *struct {
  115. PortBindings map[nat.Port][]nat.PortBinding
  116. }
  117. }
  118. err := json.Unmarshal([]byte(out), &containers)
  119. assert.Assert(c, err == nil, "Error inspecting the container: %s", err)
  120. assert.Equal(c, len(containers), 1)
  121. cont := containers[0]
  122. assert.Assert(c, cont.HostConfig != nil, "Expected HostConfig, got none")
  123. assert.Equal(c, len(cont.HostConfig.PortBindings), 65535)
  124. for k, v := range cont.HostConfig.PortBindings {
  125. assert.Equal(c, len(v), 1)
  126. assert.Equal(c, k.Port(), v[0].HostPort, fmt.Sprintf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
  127. }
  128. }
  129. // "test123" should be printed by docker create + start
  130. func (s *DockerCLICreateSuite) TestCreateEchoStdout(c *testing.T) {
  131. out, _ := dockerCmd(c, "create", "busybox", "echo", "test123")
  132. cleanedContainerID := strings.TrimSpace(out)
  133. out, _ = dockerCmd(c, "start", "-ai", cleanedContainerID)
  134. assert.Equal(c, out, "test123\n", "container should've printed 'test123', got %q", out)
  135. }
  136. func (s *DockerCLICreateSuite) TestCreateVolumesCreated(c *testing.T) {
  137. testRequires(c, testEnv.IsLocalDaemon)
  138. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  139. name := "test_create_volume"
  140. dockerCmd(c, "create", "--name", name, "-v", prefix+slash+"foo", "busybox")
  141. dir, err := inspectMountSourceField(name, prefix+slash+"foo")
  142. assert.Assert(c, err == nil, "Error getting volume host path: %q", err)
  143. if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
  144. c.Fatalf("Volume was not created")
  145. }
  146. if err != nil {
  147. c.Fatalf("Error statting volume host path: %q", err)
  148. }
  149. }
  150. func (s *DockerCLICreateSuite) TestCreateLabels(c *testing.T) {
  151. name := "test_create_labels"
  152. expected := map[string]string{"k1": "v1", "k2": "v2"}
  153. dockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox")
  154. actual := make(map[string]string)
  155. inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
  156. if !reflect.DeepEqual(expected, actual) {
  157. c.Fatalf("Expected %s got %s", expected, actual)
  158. }
  159. }
  160. func (s *DockerCLICreateSuite) TestCreateLabelFromImage(c *testing.T) {
  161. imageName := "testcreatebuildlabel"
  162. buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox
  163. LABEL k1=v1 k2=v2`))
  164. name := "test_create_labels_from_image"
  165. expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"}
  166. dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName)
  167. actual := make(map[string]string)
  168. inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
  169. if !reflect.DeepEqual(expected, actual) {
  170. c.Fatalf("Expected %s got %s", expected, actual)
  171. }
  172. }
  173. func (s *DockerCLICreateSuite) TestCreateHostnameWithNumber(c *testing.T) {
  174. image := "busybox"
  175. // Busybox on Windows does not implement hostname command
  176. if testEnv.OSType == "windows" {
  177. image = testEnv.PlatformDefaults.BaseImage
  178. }
  179. out, _ := dockerCmd(c, "run", "-h", "web.0", image, "hostname")
  180. assert.Equal(c, strings.TrimSpace(out), "web.0", "hostname not set, expected `web.0`, got: %s", out)
  181. }
  182. func (s *DockerCLICreateSuite) TestCreateRM(c *testing.T) {
  183. // Test to make sure we can 'rm' a new container that is in
  184. // "Created" state, and has ever been run. Test "rm -f" too.
  185. // create a container
  186. out, _ := dockerCmd(c, "create", "busybox")
  187. cID := strings.TrimSpace(out)
  188. dockerCmd(c, "rm", cID)
  189. // Now do it again so we can "rm -f" this time
  190. out, _ = dockerCmd(c, "create", "busybox")
  191. cID = strings.TrimSpace(out)
  192. dockerCmd(c, "rm", "-f", cID)
  193. }
  194. func (s *DockerCLICreateSuite) TestCreateModeIpcContainer(c *testing.T) {
  195. // Uses Linux specific functionality (--ipc)
  196. testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  197. out, _ := dockerCmd(c, "create", "busybox")
  198. id := strings.TrimSpace(out)
  199. dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  200. }
  201. func (s *DockerCLICreateSuite) TestCreateByImageID(c *testing.T) {
  202. imageName := "testcreatebyimageid"
  203. buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox
  204. MAINTAINER dockerio`))
  205. imageID := getIDByName(c, imageName)
  206. truncatedImageID := stringid.TruncateID(imageID)
  207. dockerCmd(c, "create", imageID)
  208. dockerCmd(c, "create", truncatedImageID)
  209. // Ensure this fails
  210. out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
  211. if exit == 0 {
  212. c.Fatalf("expected non-zero exit code; received %d", exit)
  213. }
  214. if expected := "invalid reference format"; !strings.Contains(out, expected) {
  215. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  216. }
  217. if i := strings.IndexRune(imageID, ':'); i >= 0 {
  218. imageID = imageID[i+1:]
  219. }
  220. out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", imageID))
  221. if exit == 0 {
  222. c.Fatalf("expected non-zero exit code; received %d", exit)
  223. }
  224. if expected := "Unable to find image"; !strings.Contains(out, expected) {
  225. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  226. }
  227. }
  228. func (s *DockerCLICreateSuite) TestCreateStopSignal(c *testing.T) {
  229. name := "test_create_stop_signal"
  230. dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
  231. res := inspectFieldJSON(c, name, "Config.StopSignal")
  232. assert.Assert(c, strings.Contains(res, "9"))
  233. }
  234. func (s *DockerCLICreateSuite) TestCreateWithWorkdir(c *testing.T) {
  235. name := "foo"
  236. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  237. dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
  238. dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
  239. // Windows does not create the workdir until the container is started
  240. if testEnv.OSType == "windows" {
  241. dockerCmd(c, "start", name)
  242. if testEnv.DaemonInfo.Isolation.IsHyperV() {
  243. // Hyper-V isolated containers do not allow file-operations on a
  244. // running container. This test currently uses `docker cp` to verify
  245. // that the WORKDIR was automatically created, which cannot be done
  246. // while the container is running.
  247. dockerCmd(c, "stop", name)
  248. }
  249. }
  250. // TODO: rewrite this test to not use `docker cp` for verifying that the WORKDIR was created
  251. dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
  252. }
  253. func (s *DockerCLICreateSuite) TestCreateWithInvalidLogOpts(c *testing.T) {
  254. name := "test-invalidate-log-opts"
  255. out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
  256. assert.ErrorContains(c, err, "")
  257. assert.Assert(c, strings.Contains(out, "unknown log opt"))
  258. assert.Assert(c, is.Contains(out, "unknown log opt"))
  259. out, _ = dockerCmd(c, "ps", "-a")
  260. assert.Assert(c, !strings.Contains(out, name))
  261. }
  262. // #20972
  263. func (s *DockerCLICreateSuite) TestCreate64ByteHexID(c *testing.T) {
  264. out := inspectField(c, "busybox", "Id")
  265. imageID := strings.TrimPrefix(strings.TrimSpace(out), "sha256:")
  266. dockerCmd(c, "create", imageID)
  267. }
  268. // Test case for #23498
  269. func (s *DockerCLICreateSuite) TestCreateUnsetEntrypoint(c *testing.T) {
  270. name := "test-entrypoint"
  271. dockerfile := `FROM busybox
  272. ADD entrypoint.sh /entrypoint.sh
  273. RUN chmod 755 /entrypoint.sh
  274. ENTRYPOINT ["/entrypoint.sh"]
  275. CMD echo foobar`
  276. ctx := fakecontext.New(c, "",
  277. fakecontext.WithDockerfile(dockerfile),
  278. fakecontext.WithFiles(map[string]string{
  279. "entrypoint.sh": `#!/bin/sh
  280. echo "I am an entrypoint"
  281. exec "$@"`,
  282. }))
  283. defer ctx.Close()
  284. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  285. out := cli.DockerCmd(c, "create", "--entrypoint=", name, "echo", "foo").Combined()
  286. id := strings.TrimSpace(out)
  287. assert.Assert(c, id != "")
  288. out = cli.DockerCmd(c, "start", "-a", id).Combined()
  289. assert.Equal(c, strings.TrimSpace(out), "foo")
  290. }
  291. // #22471
  292. func (s *DockerCLICreateSuite) TestCreateStopTimeout(c *testing.T) {
  293. name1 := "test_create_stop_timeout_1"
  294. dockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox")
  295. res := inspectFieldJSON(c, name1, "Config.StopTimeout")
  296. assert.Assert(c, strings.Contains(res, "15"))
  297. name2 := "test_create_stop_timeout_2"
  298. dockerCmd(c, "create", "--name", name2, "busybox")
  299. res = inspectFieldJSON(c, name2, "Config.StopTimeout")
  300. assert.Assert(c, strings.Contains(res, "null"))
  301. }