docker_cli_create_test.go 12 KB

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