docker_cli_create_test.go 12 KB

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