docker_cli_create_test.go 12 KB

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