docker_cli_create_test.go 12 KB

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