github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/integration-cli/docker_cli_create_test.go (about)

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