docker_cli_create_test.go 12 KB

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