docker_cli_create_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "reflect"
  8. "strings"
  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/integration-cli/cli/build/fakecontext"
  14. "github.com/docker/docker/pkg/stringid"
  15. icmd "github.com/docker/docker/pkg/testutil/cmd"
  16. "github.com/docker/go-connections/nat"
  17. "github.com/go-check/check"
  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. 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. c.Assert(containers, checker.HasLen, 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.DaemonPlatform() != "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. c.Assert(err, check.NotNil, check.Commentf(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. 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. c.Assert(containers, checker.HasLen, 1)
  81. cont := containers[0]
  82. c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
  83. c.Assert(cont.HostConfig.PublishAllPorts, check.NotNil, 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. 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. c.Assert(containers, checker.HasLen, 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. 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. c.Assert(containers, checker.HasLen, 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. c.Assert(out, checker.Equals, "test123\n", check.Commentf("container should've printed 'test123', got %q", out))
  131. }
  132. func (s *DockerSuite) TestCreateVolumesCreated(c *check.C) {
  133. testRequires(c, SameHostDaemon)
  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.DaemonPlatform() == "windows" {
  173. image = testEnv.MinimalBaseImage()
  174. }
  175. out, _ := dockerCmd(c, "run", "-h", "web.0", image, "hostname")
  176. c.Assert(strings.TrimSpace(out), checker.Equals, "web.0", check.Commentf("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, SameHostDaemon)
  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. dockerCmd(c, "create", fmt.Sprintf("%s:%s", imageName, 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. out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", truncatedImageID))
  215. if exit == 0 {
  216. c.Fatalf("expected non-zero exit code; received %d", exit)
  217. }
  218. if expected := "Unable to find image"; !strings.Contains(out, expected) {
  219. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  220. }
  221. }
  222. func (s *DockerTrustSuite) TestTrustedCreate(c *check.C) {
  223. repoName := s.setupTrustedImage(c, "trusted-create")
  224. // Try create
  225. cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, SuccessTagging)
  226. cli.DockerCmd(c, "rmi", repoName)
  227. // Try untrusted create to ensure we pushed the tag to the registry
  228. cli.Docker(cli.Args("create", "--disable-content-trust=true", repoName)).Assert(c, SuccessDownloadedOnStderr)
  229. }
  230. func (s *DockerTrustSuite) TestUntrustedCreate(c *check.C) {
  231. repoName := fmt.Sprintf("%v/dockercliuntrusted/createtest", privateRegistryURL)
  232. withTagName := fmt.Sprintf("%s:latest", repoName)
  233. // tag the image and upload it to the private registry
  234. cli.DockerCmd(c, "tag", "busybox", withTagName)
  235. cli.DockerCmd(c, "push", withTagName)
  236. cli.DockerCmd(c, "rmi", withTagName)
  237. // Try trusted create on untrusted tag
  238. cli.Docker(cli.Args("create", withTagName), trustedCmd).Assert(c, icmd.Expected{
  239. ExitCode: 1,
  240. Err: fmt.Sprintf("does not have trust data for %s", repoName),
  241. })
  242. }
  243. func (s *DockerTrustSuite) TestTrustedIsolatedCreate(c *check.C) {
  244. repoName := s.setupTrustedImage(c, "trusted-isolated-create")
  245. // Try create
  246. cli.Docker(cli.Args("--config", "/tmp/docker-isolated-create", "create", repoName), trustedCmd).Assert(c, SuccessTagging)
  247. defer os.RemoveAll("/tmp/docker-isolated-create")
  248. cli.DockerCmd(c, "rmi", repoName)
  249. }
  250. func (s *DockerTrustSuite) TestTrustedCreateFromBadTrustServer(c *check.C) {
  251. repoName := fmt.Sprintf("%v/dockerclievilcreate/trusted:latest", privateRegistryURL)
  252. evilLocalConfigDir, err := ioutil.TempDir("", "evilcreate-local-config-dir")
  253. c.Assert(err, check.IsNil)
  254. // tag the image and upload it to the private registry
  255. cli.DockerCmd(c, "tag", "busybox", repoName)
  256. cli.Docker(cli.Args("push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
  257. cli.DockerCmd(c, "rmi", repoName)
  258. // Try create
  259. cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, SuccessTagging)
  260. cli.DockerCmd(c, "rmi", repoName)
  261. // Kill the notary server, start a new "evil" one.
  262. s.not.Close()
  263. s.not, err = newTestNotary(c)
  264. c.Assert(err, check.IsNil)
  265. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  266. // tag an image and upload it to the private registry
  267. cli.DockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  268. // Push up to the new server
  269. cli.Docker(cli.Args("--config", evilLocalConfigDir, "push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
  270. // Now, try creating with the original client from this new trust server. This should fail because the new root is invalid.
  271. cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, icmd.Expected{
  272. ExitCode: 1,
  273. Err: "could not rotate trust to a new trusted root",
  274. })
  275. }
  276. func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
  277. name := "test_create_stop_signal"
  278. dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
  279. res := inspectFieldJSON(c, name, "Config.StopSignal")
  280. c.Assert(res, checker.Contains, "9")
  281. }
  282. func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
  283. name := "foo"
  284. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  285. dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
  286. dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
  287. // Windows does not create the workdir until the container is started
  288. if testEnv.DaemonPlatform() == "windows" {
  289. dockerCmd(c, "start", name)
  290. }
  291. dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
  292. }
  293. func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
  294. name := "test-invalidate-log-opts"
  295. out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
  296. c.Assert(err, checker.NotNil)
  297. c.Assert(out, checker.Contains, "unknown log opt")
  298. out, _ = dockerCmd(c, "ps", "-a")
  299. c.Assert(out, checker.Not(checker.Contains), name)
  300. }
  301. // #20972
  302. func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
  303. out := inspectField(c, "busybox", "Id")
  304. imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
  305. dockerCmd(c, "create", imageID)
  306. }
  307. // Test case for #23498
  308. func (s *DockerSuite) TestCreateUnsetEntrypoint(c *check.C) {
  309. name := "test-entrypoint"
  310. dockerfile := `FROM busybox
  311. ADD entrypoint.sh /entrypoint.sh
  312. RUN chmod 755 /entrypoint.sh
  313. ENTRYPOINT ["/entrypoint.sh"]
  314. CMD echo foobar`
  315. ctx := fakecontext.New(c, "",
  316. fakecontext.WithDockerfile(dockerfile),
  317. fakecontext.WithFiles(map[string]string{
  318. "entrypoint.sh": `#!/bin/sh
  319. echo "I am an entrypoint"
  320. exec "$@"`,
  321. }))
  322. defer ctx.Close()
  323. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  324. out := cli.DockerCmd(c, "create", "--entrypoint=", name, "echo", "foo").Combined()
  325. id := strings.TrimSpace(out)
  326. c.Assert(id, check.Not(check.Equals), "")
  327. out = cli.DockerCmd(c, "start", "-a", id).Combined()
  328. c.Assert(strings.TrimSpace(out), check.Equals, "foo")
  329. }
  330. // #22471
  331. func (s *DockerSuite) TestCreateStopTimeout(c *check.C) {
  332. name1 := "test_create_stop_timeout_1"
  333. dockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox")
  334. res := inspectFieldJSON(c, name1, "Config.StopTimeout")
  335. c.Assert(res, checker.Contains, "15")
  336. name2 := "test_create_stop_timeout_2"
  337. dockerCmd(c, "create", "--name", name2, "busybox")
  338. res = inspectFieldJSON(c, name2, "Config.StopTimeout")
  339. c.Assert(res, checker.Contains, "null")
  340. }