docker_cli_create_test.go 12 KB

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