github.com/rish1988/moby@v25.0.2+incompatible/integration-cli/docker_cli_run_test.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "bytes" 6 "context" 7 "encoding/json" 8 "fmt" 9 "io" 10 "net" 11 "os" 12 "os/exec" 13 "path" 14 "path/filepath" 15 "reflect" 16 "regexp" 17 "runtime" 18 "sort" 19 "strconv" 20 "strings" 21 "sync" 22 "testing" 23 "time" 24 25 "github.com/docker/docker/client" 26 "github.com/docker/docker/integration-cli/cli" 27 "github.com/docker/docker/integration-cli/cli/build" 28 "github.com/docker/docker/integration-cli/daemon" 29 "github.com/docker/docker/internal/testutils/specialimage" 30 "github.com/docker/docker/libnetwork/resolvconf" 31 "github.com/docker/docker/pkg/stringid" 32 "github.com/docker/docker/runconfig" 33 "github.com/docker/docker/testutil" 34 testdaemon "github.com/docker/docker/testutil/daemon" 35 "github.com/docker/docker/testutil/fakecontext" 36 "github.com/docker/go-connections/nat" 37 "github.com/moby/sys/mountinfo" 38 "gotest.tools/v3/assert" 39 "gotest.tools/v3/icmd" 40 "gotest.tools/v3/poll" 41 "gotest.tools/v3/skip" 42 ) 43 44 type DockerCLIRunSuite struct { 45 ds *DockerSuite 46 } 47 48 func (s *DockerCLIRunSuite) TearDownTest(ctx context.Context, c *testing.T) { 49 s.ds.TearDownTest(ctx, c) 50 } 51 52 func (s *DockerCLIRunSuite) OnTimeout(c *testing.T) { 53 s.ds.OnTimeout(c) 54 } 55 56 // "test123" should be printed by docker run 57 func (s *DockerCLIRunSuite) TestRunEchoStdout(c *testing.T) { 58 out := cli.DockerCmd(c, "run", "busybox", "echo", "test123").Combined() 59 if out != "test123\n" { 60 c.Fatalf("container should've printed 'test123', got '%s'", out) 61 } 62 } 63 64 // "test" should be printed 65 func (s *DockerCLIRunSuite) TestRunEchoNamedContainer(c *testing.T) { 66 out := cli.DockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test").Combined() 67 if out != "test\n" { 68 c.Errorf("container should've printed 'test'") 69 } 70 } 71 72 // docker run should not leak file descriptors. This test relies on Unix 73 // specific functionality and cannot run on Windows. 74 func (s *DockerCLIRunSuite) TestRunLeakyFileDescriptors(c *testing.T) { 75 testRequires(c, DaemonIsLinux) 76 out := cli.DockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd").Combined() 77 78 // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory 79 if out != "0 1 2 3\n" { 80 c.Errorf("container should've printed '0 1 2 3', not: %s", out) 81 } 82 } 83 84 // it should be possible to lookup Google DNS 85 // this will fail when Internet access is unavailable 86 func (s *DockerCLIRunSuite) TestRunLookupGoogleDNS(c *testing.T) { 87 testRequires(c, Network) 88 if testEnv.DaemonInfo.OSType == "windows" { 89 // nslookup isn't present in Windows busybox. Is built-in. Further, 90 // nslookup isn't present in nanoserver. Hence just use PowerShell... 91 cli.DockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "powershell", "Resolve-DNSName", "google.com") 92 } else { 93 cli.DockerCmd(c, "run", "busybox", "nslookup", "google.com") 94 } 95 } 96 97 // the exit code should be 0 98 func (s *DockerCLIRunSuite) TestRunExitCodeZero(c *testing.T) { 99 cli.DockerCmd(c, "run", "busybox", "true") 100 } 101 102 // the exit code should be 1 103 func (s *DockerCLIRunSuite) TestRunExitCodeOne(c *testing.T) { 104 _, exitCode, err := dockerCmdWithError("run", "busybox", "false") 105 assert.ErrorContains(c, err, "") 106 assert.Equal(c, exitCode, 1) 107 } 108 109 // it should be possible to pipe in data via stdin to a process running in a container 110 func (s *DockerCLIRunSuite) TestRunStdinPipe(c *testing.T) { 111 // TODO Windows: This needs some work to make compatible. 112 testRequires(c, DaemonIsLinux) 113 result := icmd.RunCmd(icmd.Cmd{ 114 Command: []string{dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat"}, 115 Stdin: strings.NewReader("blahblah"), 116 }) 117 result.Assert(c, icmd.Success) 118 out := result.Stdout() 119 120 out = strings.TrimSpace(out) 121 cli.DockerCmd(c, "wait", out) 122 123 containerLogs := cli.DockerCmd(c, "logs", out).Combined() 124 containerLogs = strings.TrimSpace(containerLogs) 125 if containerLogs != "blahblah" { 126 c.Errorf("logs didn't print the container's logs %s", containerLogs) 127 } 128 129 cli.DockerCmd(c, "rm", out) 130 } 131 132 // the container's ID should be printed when starting a container in detached mode 133 func (s *DockerCLIRunSuite) TestRunDetachedContainerIDPrinting(c *testing.T) { 134 id := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() 135 id = strings.TrimSpace(id) 136 cli.DockerCmd(c, "wait", id) 137 138 rmOut := cli.DockerCmd(c, "rm", id).Stdout() 139 rmOut = strings.TrimSpace(rmOut) 140 if rmOut != id { 141 c.Errorf("rm didn't print the container ID %s %s", id, rmOut) 142 } 143 } 144 145 // the working directory should be set correctly 146 func (s *DockerCLIRunSuite) TestRunWorkingDirectory(c *testing.T) { 147 dir := "/root" 148 const imgName = "busybox" 149 if testEnv.DaemonInfo.OSType == "windows" { 150 dir = `C:/Windows` 151 } 152 153 // First with -w 154 out := cli.DockerCmd(c, "run", "-w", dir, imgName, "pwd").Stdout() 155 if strings.TrimSpace(out) != dir { 156 c.Errorf("-w failed to set working directory") 157 } 158 159 // Then with --workdir 160 out = cli.DockerCmd(c, "run", "--workdir", dir, imgName, "pwd").Stdout() 161 if strings.TrimSpace(out) != dir { 162 c.Errorf("--workdir failed to set working directory") 163 } 164 } 165 166 // pinging Google's DNS resolver should fail when we disable the networking 167 func (s *DockerCLIRunSuite) TestRunWithoutNetworking(c *testing.T) { 168 count := "-c" 169 imgName := "busybox" 170 if testEnv.DaemonInfo.OSType == "windows" { 171 count = "-n" 172 imgName = testEnv.PlatformDefaults.BaseImage 173 } 174 175 // First using the long form --net 176 out, exitCode, err := dockerCmdWithError("run", "--net=none", imgName, "ping", count, "1", "8.8.8.8") 177 if err != nil && exitCode != 1 { 178 c.Fatal(out, err) 179 } 180 if exitCode != 1 { 181 c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8") 182 } 183 } 184 185 // test --link use container name to link target 186 func (s *DockerCLIRunSuite) TestRunLinksContainerWithContainerName(c *testing.T) { 187 // TODO Windows: This test cannot run on a Windows daemon as the networking 188 // settings are not populated back yet on inspect. 189 testRequires(c, DaemonIsLinux) 190 cli.DockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox") 191 192 ip := inspectField(c, "parent", "NetworkSettings.Networks.bridge.IPAddress") 193 194 out := cli.DockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts").Combined() 195 if !strings.Contains(out, ip+" test") { 196 c.Fatalf("use a container name to link target failed") 197 } 198 } 199 200 // test --link use container id to link target 201 func (s *DockerCLIRunSuite) TestRunLinksContainerWithContainerID(c *testing.T) { 202 // TODO Windows: This test cannot run on a Windows daemon as the networking 203 // settings are not populated back yet on inspect. 204 testRequires(c, DaemonIsLinux) 205 cID := cli.DockerCmd(c, "run", "-i", "-t", "-d", "busybox").Stdout() 206 cID = strings.TrimSpace(cID) 207 ip := inspectField(c, cID, "NetworkSettings.Networks.bridge.IPAddress") 208 209 out := cli.DockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts").Combined() 210 if !strings.Contains(out, ip+" test") { 211 c.Fatalf("use a container id to link target failed") 212 } 213 } 214 215 func (s *DockerCLIRunSuite) TestUserDefinedNetworkLinks(c *testing.T) { 216 testRequires(c, DaemonIsLinux, NotUserNamespace) 217 cli.DockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") 218 219 cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") 220 cli.WaitRun(c, "first") 221 222 // run a container in user-defined network udlinkNet with a link for an existing container 223 // and a link for a container that doesn't exist 224 cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", "--link=third:bar", "busybox", "top") 225 cli.WaitRun(c, "second") 226 227 // ping to first and its alias foo must succeed 228 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 229 assert.NilError(c, err) 230 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 231 assert.NilError(c, err) 232 233 // ping to third and its alias must fail 234 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") 235 assert.ErrorContains(c, err, "") 236 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") 237 assert.ErrorContains(c, err, "") 238 239 // start third container now 240 cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top") 241 cli.WaitRun(c, "third") 242 243 // ping to third and its alias must succeed now 244 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") 245 assert.NilError(c, err) 246 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") 247 assert.NilError(c, err) 248 } 249 250 func (s *DockerCLIRunSuite) TestUserDefinedNetworkLinksWithRestart(c *testing.T) { 251 testRequires(c, DaemonIsLinux, NotUserNamespace) 252 cli.DockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") 253 254 cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") 255 cli.WaitRun(c, "first") 256 257 cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", "busybox", "top") 258 cli.WaitRun(c, "second") 259 260 // ping to first and its alias foo must succeed 261 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 262 assert.NilError(c, err) 263 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 264 assert.NilError(c, err) 265 266 // Restart first container 267 cli.DockerCmd(c, "restart", "first") 268 cli.WaitRun(c, "first") 269 270 // ping to first and its alias foo must still succeed 271 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 272 assert.NilError(c, err) 273 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 274 assert.NilError(c, err) 275 276 // Restart second container 277 cli.DockerCmd(c, "restart", "second") 278 cli.WaitRun(c, "second") 279 280 // ping to first and its alias foo must still succeed 281 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 282 assert.NilError(c, err) 283 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 284 assert.NilError(c, err) 285 } 286 287 func (s *DockerCLIRunSuite) TestRunWithNetAliasOnDefaultNetworks(c *testing.T) { 288 testRequires(c, DaemonIsLinux, NotUserNamespace) 289 290 defaults := []string{"bridge", "host", "none"} 291 for _, nw := range defaults { 292 out, _, err := dockerCmdWithError("run", "-d", "--net", nw, "--net-alias", "alias_"+nw, "busybox", "top") 293 assert.ErrorContains(c, err, "") 294 assert.Assert(c, strings.Contains(out, runconfig.ErrUnsupportedNetworkAndAlias.Error())) 295 } 296 } 297 298 func (s *DockerCLIRunSuite) TestUserDefinedNetworkAlias(c *testing.T) { 299 testRequires(c, DaemonIsLinux, NotUserNamespace) 300 cli.DockerCmd(c, "network", "create", "-d", "bridge", "net1") 301 302 cid1 := cli.DockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo1", "--net-alias=foo2", "busybox:glibc", "top").Stdout() 303 cli.WaitRun(c, "first") 304 305 // Check if default short-id alias is added automatically 306 id := strings.TrimSpace(cid1) 307 aliases := inspectField(c, id, "NetworkSettings.Networks.net1.Aliases") 308 assert.Assert(c, strings.Contains(aliases, stringid.TruncateID(id))) 309 cid2 := cli.DockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox:glibc", "top").Stdout() 310 cli.WaitRun(c, "second") 311 312 // Check if default short-id alias is added automatically 313 id = strings.TrimSpace(cid2) 314 aliases = inspectField(c, id, "NetworkSettings.Networks.net1.Aliases") 315 assert.Assert(c, strings.Contains(aliases, stringid.TruncateID(id))) 316 // ping to first and its network-scoped aliases 317 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 318 assert.NilError(c, err) 319 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1") 320 assert.NilError(c, err) 321 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2") 322 assert.NilError(c, err) 323 // ping first container's short-id alias 324 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1)) 325 assert.NilError(c, err) 326 327 // Restart first container 328 cli.DockerCmd(c, "restart", "first") 329 cli.WaitRun(c, "first") 330 331 // ping to first and its network-scoped aliases must succeed 332 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 333 assert.NilError(c, err) 334 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1") 335 assert.NilError(c, err) 336 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2") 337 assert.NilError(c, err) 338 // ping first container's short-id alias 339 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1)) 340 assert.NilError(c, err) 341 } 342 343 // Issue 9677. 344 func (s *DockerCLIRunSuite) TestRunWithDaemonFlags(c *testing.T) { 345 out, _, err := dockerCmdWithError("--exec-opt", "foo=bar", "run", "-i", "busybox", "true") 346 assert.ErrorContains(c, err, "") 347 assert.Assert(c, strings.Contains(out, "unknown flag: --exec-opt")) 348 } 349 350 // Regression test for #4979 351 func (s *DockerCLIRunSuite) TestRunWithVolumesFromExited(c *testing.T) { 352 var result *icmd.Result 353 354 // Create a file in a volume 355 if testEnv.DaemonInfo.OSType == "windows" { 356 result = cli.DockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `echo hello > c:\some\dir\file`) 357 } else { 358 result = cli.DockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file") 359 } 360 if result.ExitCode != 0 { 361 c.Fatal("1", result.Combined(), result.ExitCode) 362 } 363 364 // Read the file from another container using --volumes-from to access the volume in the second container 365 if testEnv.DaemonInfo.OSType == "windows" { 366 result = cli.DockerCmd(c, "run", "--volumes-from", "test-data", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `type c:\some\dir\file`) 367 } else { 368 result = cli.DockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file") 369 } 370 if result.ExitCode != 0 { 371 c.Fatal("2", result.Combined(), result.ExitCode) 372 } 373 } 374 375 // Volume path is a symlink which also exists on the host, and the host side is a file not a dir 376 // But the volume call is just a normal volume, not a bind mount 377 func (s *DockerCLIRunSuite) TestRunCreateVolumesInSymlinkDir(c *testing.T) { 378 var ( 379 dockerFile string 380 containerPath string 381 cmd string 382 ) 383 // This test cannot run on a Windows daemon as 384 // Windows does not support symlinks inside a volume path 385 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 386 name := "test-volume-symlink" 387 388 dir, err := os.MkdirTemp("", name) 389 if err != nil { 390 c.Fatal(err) 391 } 392 defer os.RemoveAll(dir) 393 394 // In the case of Windows to Windows CI, if the machine is setup so that 395 // the temp directory is not the C: drive, this test is invalid and will 396 // not work. 397 if testEnv.DaemonInfo.OSType == "windows" && strings.ToLower(dir[:1]) != "c" { 398 c.Skip("Requires TEMP to point to C: drive") 399 } 400 401 f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0o700) 402 if err != nil { 403 c.Fatal(err) 404 } 405 f.Close() 406 407 if testEnv.DaemonInfo.OSType == "windows" { 408 dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir %s\nRUN mklink /D c:\\test %s", testEnv.PlatformDefaults.BaseImage, dir, dir) 409 containerPath = `c:\test\test` 410 cmd = "tasklist" 411 } else { 412 dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir) 413 containerPath = "/test/test" 414 cmd = "true" 415 } 416 buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile)) 417 cli.DockerCmd(c, "run", "-v", containerPath, name, cmd) 418 } 419 420 // Volume path is a symlink in the container 421 func (s *DockerCLIRunSuite) TestRunCreateVolumesInSymlinkDir2(c *testing.T) { 422 var ( 423 dockerFile string 424 containerPath string 425 cmd string 426 ) 427 // This test cannot run on a Windows daemon as 428 // Windows does not support symlinks inside a volume path 429 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 430 name := "test-volume-symlink2" 431 432 if testEnv.DaemonInfo.OSType == "windows" { 433 dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir c:\\%s\nRUN mklink /D c:\\test c:\\%s", testEnv.PlatformDefaults.BaseImage, name, name) 434 containerPath = `c:\test\test` 435 cmd = "tasklist" 436 } else { 437 dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p /%s\nRUN ln -s /%s /test", name, name) 438 containerPath = "/test/test" 439 cmd = "true" 440 } 441 buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile)) 442 cli.DockerCmd(c, "run", "-v", containerPath, name, cmd) 443 } 444 445 func (s *DockerCLIRunSuite) TestRunVolumesMountedAsReadonly(c *testing.T) { 446 if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 { 447 c.Fatalf("run should fail because volume is ro: exit code %d", code) 448 } 449 } 450 451 func (s *DockerCLIRunSuite) TestRunVolumesFromInReadonlyModeFails(c *testing.T) { 452 var ( 453 volumeDir string 454 fileInVol string 455 ) 456 if testEnv.DaemonInfo.OSType == "windows" { 457 volumeDir = `c:/test` // Forward-slash as using busybox 458 fileInVol = `c:/test/file` 459 } else { 460 testRequires(c, DaemonIsLinux) 461 volumeDir = "/test" 462 fileInVol = `/test/file` 463 } 464 cli.DockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") 465 466 if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", fileInVol); err == nil || code == 0 { 467 c.Fatalf("run should fail because volume is ro: exit code %d", code) 468 } 469 } 470 471 // Regression test for #1201 472 func (s *DockerCLIRunSuite) TestRunVolumesFromInReadWriteMode(c *testing.T) { 473 var ( 474 volumeDir string 475 fileInVol string 476 ) 477 if testEnv.DaemonInfo.OSType == "windows" { 478 volumeDir = `c:/test` // Forward-slash as using busybox 479 fileInVol = `c:/test/file` 480 } else { 481 volumeDir = "/test" 482 fileInVol = "/test/file" 483 } 484 485 cli.DockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") 486 cli.DockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", fileInVol) 487 488 if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", fileInVol); err == nil || !strings.Contains(out, `invalid mode: bar`) { 489 c.Fatalf("running --volumes-from parent:bar should have failed with invalid mode: %q", out) 490 } 491 492 cli.DockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", fileInVol) 493 } 494 495 func (s *DockerCLIRunSuite) TestVolumesFromGetsProperMode(c *testing.T) { 496 testRequires(c, testEnv.IsLocalDaemon) 497 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 498 hostpath := RandomTmpDirPath("test", testEnv.DaemonInfo.OSType) 499 if err := os.MkdirAll(hostpath, 0o755); err != nil { 500 c.Fatalf("Failed to create %s: %q", hostpath, err) 501 } 502 defer os.RemoveAll(hostpath) 503 504 cli.DockerCmd(c, "run", "--name", "parent", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true") 505 506 // Expect this "rw" mode to be be ignored since the inherited volume is "ro" 507 if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil { 508 c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`") 509 } 510 511 cli.DockerCmd(c, "run", "--name", "parent2", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true") 512 513 // Expect this to be read-only since both are "ro" 514 if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil { 515 c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`") 516 } 517 } 518 519 // Test for GH#10618 520 func (s *DockerCLIRunSuite) TestRunNoDupVolumes(c *testing.T) { 521 path1 := RandomTmpDirPath("test1", testEnv.DaemonInfo.OSType) 522 path2 := RandomTmpDirPath("test2", testEnv.DaemonInfo.OSType) 523 524 someplace := ":/someplace" 525 if testEnv.DaemonInfo.OSType == "windows" { 526 // Windows requires that the source directory exists before calling HCS 527 testRequires(c, testEnv.IsLocalDaemon) 528 someplace = `:c:\someplace` 529 if err := os.MkdirAll(path1, 0o755); err != nil { 530 c.Fatalf("Failed to create %s: %q", path1, err) 531 } 532 defer os.RemoveAll(path1) 533 if err := os.MkdirAll(path2, 0o755); err != nil { 534 c.Fatalf("Failed to create %s: %q", path1, err) 535 } 536 defer os.RemoveAll(path2) 537 } 538 mountstr1 := path1 + someplace 539 mountstr2 := path2 + someplace 540 541 if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil { 542 c.Fatal("Expected error about duplicate mount definitions") 543 } else { 544 if !strings.Contains(out, "Duplicate mount point") { 545 c.Fatalf("Expected 'duplicate mount point' error, got %v", out) 546 } 547 } 548 549 // Test for https://github.com/docker/docker/issues/22093 550 volumename1 := "test1" 551 volumename2 := "test2" 552 volume1 := volumename1 + someplace 553 volume2 := volumename2 + someplace 554 if out, _, err := dockerCmdWithError("run", "-v", volume1, "-v", volume2, "busybox", "true"); err == nil { 555 c.Fatal("Expected error about duplicate mount definitions") 556 } else { 557 if !strings.Contains(out, "Duplicate mount point") { 558 c.Fatalf("Expected 'duplicate mount point' error, got %v", out) 559 } 560 } 561 // create failed should have create volume volumename1 or volumename2 562 // we should remove volumename2 or volumename2 successfully 563 out := cli.DockerCmd(c, "volume", "ls").Stdout() 564 if strings.Contains(out, volumename1) { 565 cli.DockerCmd(c, "volume", "rm", volumename1) 566 } else { 567 cli.DockerCmd(c, "volume", "rm", volumename2) 568 } 569 } 570 571 // Test for #1351 572 func (s *DockerCLIRunSuite) TestRunApplyVolumesFromBeforeVolumes(c *testing.T) { 573 prefix := "" 574 if testEnv.DaemonInfo.OSType == "windows" { 575 prefix = `c:` 576 } 577 cli.DockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") 578 cli.DockerCmd(c, "run", "--volumes-from", "parent", "-v", prefix+"/test", "busybox", "cat", prefix+"/test/foo") 579 } 580 581 func (s *DockerCLIRunSuite) TestRunMultipleVolumesFrom(c *testing.T) { 582 prefix := "" 583 if testEnv.DaemonInfo.OSType == "windows" { 584 prefix = `c:` 585 } 586 cli.DockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") 587 cli.DockerCmd(c, "run", "--name", "parent2", "-v", prefix+"/other", "busybox", "touch", prefix+"/other/bar") 588 cli.DockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar") 589 } 590 591 // this tests verifies the ID format for the container 592 func (s *DockerCLIRunSuite) TestRunVerifyContainerID(c *testing.T) { 593 out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true") 594 if err != nil { 595 c.Fatal(err) 596 } 597 if exit != 0 { 598 c.Fatalf("expected exit code 0 received %d", exit) 599 } 600 601 match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n")) 602 if err != nil { 603 c.Fatal(err) 604 } 605 if !match { 606 c.Fatalf("Invalid container ID: %s", out) 607 } 608 } 609 610 // Test that creating a container with a volume doesn't crash. Regression test for #995. 611 func (s *DockerCLIRunSuite) TestRunCreateVolume(c *testing.T) { 612 prefix := "" 613 if testEnv.DaemonInfo.OSType == "windows" { 614 prefix = `c:` 615 } 616 cli.DockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true") 617 } 618 619 // Test that creating a volume with a symlink in its path works correctly. Test for #5152. 620 // Note that this bug happens only with symlinks with a target that starts with '/'. 621 func (s *DockerCLIRunSuite) TestRunCreateVolumeWithSymlink(c *testing.T) { 622 // Cannot run on Windows as relies on Linux-specific functionality (sh -c mount...) 623 testRequires(c, DaemonIsLinux) 624 workingDirectory, err := os.MkdirTemp("", "TestRunCreateVolumeWithSymlink") 625 assert.NilError(c, err) 626 const imgName = "docker-test-createvolumewithsymlink" 627 628 buildCmd := exec.Command(dockerBinary, "build", "-t", imgName, "-") 629 buildCmd.Stdin = strings.NewReader(`FROM busybox 630 RUN ln -s home /bar`) 631 buildCmd.Dir = workingDirectory 632 err = buildCmd.Run() 633 if err != nil { 634 c.Fatalf("could not build '%s': %v", imgName, err) 635 } 636 637 _, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", imgName, "sh", "-c", "mount | grep -q /home/foo") 638 if err != nil || exitCode != 0 { 639 c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) 640 } 641 642 volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo") 643 assert.NilError(c, err) 644 645 _, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink") 646 if err != nil || exitCode != 0 { 647 c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode) 648 } 649 650 _, err = os.Stat(volPath) 651 if !os.IsNotExist(err) { 652 c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath) 653 } 654 } 655 656 // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`. 657 func (s *DockerCLIRunSuite) TestRunVolumesFromSymlinkPath(c *testing.T) { 658 // This test cannot run on a Windows daemon as 659 // Windows does not support symlinks inside a volume path 660 testRequires(c, DaemonIsLinux) 661 662 workingDirectory, err := os.MkdirTemp("", "TestRunVolumesFromSymlinkPath") 663 assert.NilError(c, err) 664 name := "docker-test-volumesfromsymlinkpath" 665 prefix := "" 666 dfContents := `FROM busybox 667 RUN ln -s home /foo 668 VOLUME ["/foo/bar"]` 669 670 if testEnv.DaemonInfo.OSType == "windows" { 671 prefix = `c:` 672 dfContents = `FROM ` + testEnv.PlatformDefaults.BaseImage + ` 673 RUN mkdir c:\home 674 RUN mklink /D c:\foo c:\home 675 VOLUME ["c:/foo/bar"] 676 ENTRYPOINT c:\windows\system32\cmd.exe` 677 } 678 679 buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-") 680 buildCmd.Stdin = strings.NewReader(dfContents) 681 buildCmd.Dir = workingDirectory 682 err = buildCmd.Run() 683 if err != nil { 684 c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err) 685 } 686 687 out, exitCode, err := dockerCmdWithError("run", "--name", "test-volumesfromsymlinkpath", name) 688 if err != nil || exitCode != 0 { 689 c.Fatalf("[run] (volume) err: %v, exitcode: %d, out: %s", err, exitCode, out) 690 } 691 692 _, exitCode, err = dockerCmdWithError("run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls "+prefix+"/foo | grep -q bar") 693 if err != nil || exitCode != 0 { 694 c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) 695 } 696 } 697 698 func (s *DockerCLIRunSuite) TestRunExitCode(c *testing.T) { 699 var ( 700 exit int 701 err error 702 ) 703 704 _, exit, err = dockerCmdWithError("run", "busybox", "/bin/sh", "-c", "exit 72") 705 706 if err == nil { 707 c.Fatal("should not have a non nil error") 708 } 709 if exit != 72 { 710 c.Fatalf("expected exit code 72 received %d", exit) 711 } 712 } 713 714 func (s *DockerCLIRunSuite) TestRunUserDefaults(c *testing.T) { 715 expected := "uid=0(root) gid=0(root)" 716 if testEnv.DaemonInfo.OSType == "windows" { 717 expected = "uid=0(root) gid=0(root) groups=0(root)" 718 } 719 out := cli.DockerCmd(c, "run", "busybox", "id").Stdout() 720 if !strings.Contains(out, expected) { 721 c.Fatalf("expected '%s' got %s", expected, out) 722 } 723 } 724 725 func (s *DockerCLIRunSuite) TestRunUserByName(c *testing.T) { 726 // TODO Windows: This test cannot run on a Windows daemon as Windows does 727 // not support the use of -u 728 testRequires(c, DaemonIsLinux) 729 out := cli.DockerCmd(c, "run", "-u", "root", "busybox", "id").Stdout() 730 if !strings.Contains(out, "uid=0(root) gid=0(root)") { 731 c.Fatalf("expected root user got %s", out) 732 } 733 } 734 735 func (s *DockerCLIRunSuite) TestRunUserByID(c *testing.T) { 736 // TODO Windows: This test cannot run on a Windows daemon as Windows does 737 // not support the use of -u 738 testRequires(c, DaemonIsLinux) 739 out := cli.DockerCmd(c, "run", "-u", "1", "busybox", "id").Stdout() 740 if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") { 741 c.Fatalf("expected daemon user got %s", out) 742 } 743 } 744 745 func (s *DockerCLIRunSuite) TestRunUserByIDBig(c *testing.T) { 746 // TODO Windows: This test cannot run on a Windows daemon as Windows does 747 // not support the use of -u 748 testRequires(c, DaemonIsLinux) 749 out, _, err := dockerCmdWithError("run", "-u", "2147483648", "busybox", "id") 750 if err == nil { 751 c.Fatal("No error, but must be.", out) 752 } 753 if !strings.Contains(strings.ToLower(out), "uids and gids must be in range") { 754 c.Fatalf("expected error about uids range, got %s", out) 755 } 756 } 757 758 func (s *DockerCLIRunSuite) TestRunUserByIDNegative(c *testing.T) { 759 // TODO Windows: This test cannot run on a Windows daemon as Windows does 760 // not support the use of -u 761 testRequires(c, DaemonIsLinux) 762 out, _, err := dockerCmdWithError("run", "-u", "-1", "busybox", "id") 763 if err == nil { 764 c.Fatal("No error, but must be.", out) 765 } 766 if !strings.Contains(strings.ToLower(out), "uids and gids must be in range") { 767 c.Fatalf("expected error about uids range, got %s", out) 768 } 769 } 770 771 func (s *DockerCLIRunSuite) TestRunUserByIDZero(c *testing.T) { 772 // TODO Windows: This test cannot run on a Windows daemon as Windows does 773 // not support the use of -u 774 testRequires(c, DaemonIsLinux) 775 out, _, err := dockerCmdWithError("run", "-u", "0", "busybox", "id") 776 if err != nil { 777 c.Fatal(err, out) 778 } 779 if !strings.Contains(out, "uid=0(root) gid=0(root) groups=0(root),10(wheel)") { 780 c.Fatalf("expected daemon user got %s", out) 781 } 782 } 783 784 func (s *DockerCLIRunSuite) TestRunUserNotFound(c *testing.T) { 785 // TODO Windows: This test cannot run on a Windows daemon as Windows does 786 // not support the use of -u 787 testRequires(c, DaemonIsLinux) 788 _, _, err := dockerCmdWithError("run", "-u", "notme", "busybox", "id") 789 if err == nil { 790 c.Fatal("unknown user should cause container to fail") 791 } 792 } 793 794 func (s *DockerCLIRunSuite) TestRunTwoConcurrentContainers(c *testing.T) { 795 sleepTime := "2" 796 group := sync.WaitGroup{} 797 group.Add(2) 798 799 errChan := make(chan error, 2) 800 for i := 0; i < 2; i++ { 801 go func() { 802 defer group.Done() 803 _, _, err := dockerCmdWithError("run", "busybox", "sleep", sleepTime) 804 errChan <- err 805 }() 806 } 807 808 group.Wait() 809 close(errChan) 810 811 for err := range errChan { 812 assert.NilError(c, err) 813 } 814 } 815 816 func (s *DockerCLIRunSuite) TestRunEnvironment(c *testing.T) { 817 // TODO Windows: Environment handling is different between Linux and 818 // Windows and this test relies currently on unix functionality. 819 testRequires(c, DaemonIsLinux) 820 result := icmd.RunCmd(icmd.Cmd{ 821 Command: []string{dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env"}, 822 Env: append(os.Environ(), 823 "TRUE=false", 824 "TRICKY=tri\ncky\n", 825 ), 826 }) 827 result.Assert(c, icmd.Success) 828 829 actualEnv := strings.Split(strings.TrimSuffix(result.Stdout(), "\n"), "\n") 830 sort.Strings(actualEnv) 831 832 goodEnv := []string{ 833 // The first two should not be tested here, those are "inherent" environment variable. This test validates 834 // the -e behavior, not the default environment variable (that could be subject to change) 835 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 836 "HOSTNAME=testing", 837 "FALSE=true", 838 "TRUE=false", 839 "TRICKY=tri", 840 "cky", 841 "", 842 "HOME=/root", 843 } 844 sort.Strings(goodEnv) 845 if len(goodEnv) != len(actualEnv) { 846 c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", ")) 847 } 848 for i := range goodEnv { 849 if actualEnv[i] != goodEnv[i] { 850 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 851 } 852 } 853 } 854 855 func (s *DockerCLIRunSuite) TestRunEnvironmentErase(c *testing.T) { 856 // TODO Windows: Environment handling is different between Linux and 857 // Windows and this test relies currently on unix functionality. 858 testRequires(c, DaemonIsLinux) 859 860 // Test to make sure that when we use -e on env vars that are 861 // not set in our local env that they're removed (if present) in 862 // the container 863 864 result := icmd.RunCmd(icmd.Cmd{ 865 Command: []string{dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env"}, 866 Env: appendBaseEnv(true), 867 }) 868 result.Assert(c, icmd.Success) 869 870 actualEnv := strings.Split(strings.TrimSpace(result.Combined()), "\n") 871 sort.Strings(actualEnv) 872 873 goodEnv := []string{ 874 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 875 "HOME=/root", 876 } 877 sort.Strings(goodEnv) 878 if len(goodEnv) != len(actualEnv) { 879 c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", ")) 880 } 881 for i := range goodEnv { 882 if actualEnv[i] != goodEnv[i] { 883 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 884 } 885 } 886 } 887 888 func (s *DockerCLIRunSuite) TestRunEnvironmentOverride(c *testing.T) { 889 // TODO Windows: Environment handling is different between Linux and 890 // Windows and this test relies currently on unix functionality. 891 testRequires(c, DaemonIsLinux) 892 893 // Test to make sure that when we use -e on env vars that are 894 // already in the env that we're overriding them 895 896 result := icmd.RunCmd(icmd.Cmd{ 897 Command: []string{dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env"}, 898 Env: appendBaseEnv(true, "HOSTNAME=bar"), 899 }) 900 result.Assert(c, icmd.Success) 901 902 actualEnv := strings.Split(strings.TrimSpace(result.Combined()), "\n") 903 sort.Strings(actualEnv) 904 905 goodEnv := []string{ 906 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 907 "HOME=/root2", 908 "HOSTNAME=bar", 909 } 910 sort.Strings(goodEnv) 911 if len(goodEnv) != len(actualEnv) { 912 c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", ")) 913 } 914 for i := range goodEnv { 915 if actualEnv[i] != goodEnv[i] { 916 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 917 } 918 } 919 } 920 921 func (s *DockerCLIRunSuite) TestRunContainerNetwork(c *testing.T) { 922 if testEnv.DaemonInfo.OSType == "windows" { 923 // Windows busybox does not have ping. Use built in ping instead. 924 cli.DockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") 925 } else { 926 cli.DockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1") 927 } 928 } 929 930 func (s *DockerCLIRunSuite) TestRunNetHostNotAllowedWithLinks(c *testing.T) { 931 // TODO Windows: This is Linux specific as --link is not supported and 932 // this will be deprecated in favor of container networking model. 933 testRequires(c, DaemonIsLinux, NotUserNamespace) 934 cli.DockerCmd(c, "run", "--name", "linked", "busybox", "true") 935 936 _, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true") 937 if err == nil { 938 c.Fatal("Expected error") 939 } 940 } 941 942 // #7851 hostname outside container shows FQDN, inside only shortname 943 // For testing purposes it is not required to set host's hostname directly 944 // and use "--net=host" (as the original issue submitter did), as the same 945 // codepath is executed with "docker run -h <hostname>". Both were manually 946 // tested, but this testcase takes the simpler path of using "run -h .." 947 func (s *DockerCLIRunSuite) TestRunFullHostnameSet(c *testing.T) { 948 // TODO Windows: -h is not yet functional. 949 testRequires(c, DaemonIsLinux) 950 out := cli.DockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname").Combined() 951 if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" { 952 c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual) 953 } 954 } 955 956 func (s *DockerCLIRunSuite) TestRunPrivilegedCanMknod(c *testing.T) { 957 // Not applicable for Windows as Windows daemon does not support 958 // the concept of --privileged, and mknod is a Unix concept. 959 testRequires(c, DaemonIsLinux, NotUserNamespace) 960 out := cli.DockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok").Combined() 961 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 962 c.Fatalf("expected output ok received %s", actual) 963 } 964 } 965 966 func (s *DockerCLIRunSuite) TestRunUnprivilegedCanMknod(c *testing.T) { 967 // Not applicable for Windows as Windows daemon does not support 968 // the concept of --privileged, and mknod is a Unix concept. 969 testRequires(c, DaemonIsLinux, NotUserNamespace) 970 out := cli.DockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok").Combined() 971 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 972 c.Fatalf("expected output ok received %s", actual) 973 } 974 } 975 976 func (s *DockerCLIRunSuite) TestRunCapDropInvalid(c *testing.T) { 977 // Not applicable for Windows as there is no concept of --cap-drop 978 testRequires(c, DaemonIsLinux) 979 out, _, err := dockerCmdWithError("run", "--cap-drop=CHPASS", "busybox", "ls") 980 if err == nil { 981 c.Fatal(err, out) 982 } 983 } 984 985 func (s *DockerCLIRunSuite) TestRunCapDropCannotMknod(c *testing.T) { 986 // Not applicable for Windows as there is no concept of --cap-drop or mknod 987 testRequires(c, DaemonIsLinux) 988 out, _, err := dockerCmdWithError("run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 989 990 if err == nil { 991 c.Fatal(err, out) 992 } 993 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 994 c.Fatalf("expected output not ok received %s", actual) 995 } 996 } 997 998 func (s *DockerCLIRunSuite) TestRunCapDropCannotMknodLowerCase(c *testing.T) { 999 // Not applicable for Windows as there is no concept of --cap-drop or mknod 1000 testRequires(c, DaemonIsLinux) 1001 out, _, err := dockerCmdWithError("run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 1002 1003 if err == nil { 1004 c.Fatal(err, out) 1005 } 1006 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1007 c.Fatalf("expected output not ok received %s", actual) 1008 } 1009 } 1010 1011 func (s *DockerCLIRunSuite) TestRunCapDropALLCannotMknod(c *testing.T) { 1012 // Not applicable for Windows as there is no concept of --cap-drop or mknod 1013 testRequires(c, DaemonIsLinux) 1014 out, _, err := dockerCmdWithError("run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 1015 if err == nil { 1016 c.Fatal(err, out) 1017 } 1018 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1019 c.Fatalf("expected output not ok received %s", actual) 1020 } 1021 } 1022 1023 func (s *DockerCLIRunSuite) TestRunCapDropALLAddMknodCanMknod(c *testing.T) { 1024 // Not applicable for Windows as there is no concept of --cap-drop or mknod 1025 testRequires(c, DaemonIsLinux, NotUserNamespace) 1026 out := cli.DockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok").Combined() 1027 1028 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1029 c.Fatalf("expected output ok received %s", actual) 1030 } 1031 } 1032 1033 func (s *DockerCLIRunSuite) TestRunCapAddInvalid(c *testing.T) { 1034 // Not applicable for Windows as there is no concept of --cap-add 1035 testRequires(c, DaemonIsLinux) 1036 out, _, err := dockerCmdWithError("run", "--cap-add=CHPASS", "busybox", "ls") 1037 if err == nil { 1038 c.Fatal(err, out) 1039 } 1040 } 1041 1042 func (s *DockerCLIRunSuite) TestRunCapAddCanDownInterface(c *testing.T) { 1043 // Not applicable for Windows as there is no concept of --cap-add 1044 testRequires(c, DaemonIsLinux) 1045 out := cli.DockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok").Combined() 1046 1047 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1048 c.Fatalf("expected output ok received %s", actual) 1049 } 1050 } 1051 1052 func (s *DockerCLIRunSuite) TestRunCapAddALLCanDownInterface(c *testing.T) { 1053 // Not applicable for Windows as there is no concept of --cap-add 1054 testRequires(c, DaemonIsLinux) 1055 out := cli.DockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok").Combined() 1056 1057 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1058 c.Fatalf("expected output ok received %s", actual) 1059 } 1060 } 1061 1062 func (s *DockerCLIRunSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *testing.T) { 1063 // Not applicable for Windows as there is no concept of --cap-add 1064 testRequires(c, DaemonIsLinux) 1065 out, _, err := dockerCmdWithError("run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") 1066 if err == nil { 1067 c.Fatal(err, out) 1068 } 1069 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1070 c.Fatalf("expected output not ok received %s", actual) 1071 } 1072 } 1073 1074 func (s *DockerCLIRunSuite) TestRunGroupAdd(c *testing.T) { 1075 // Not applicable for Windows as there is no concept of --group-add 1076 testRequires(c, DaemonIsLinux) 1077 out := cli.DockerCmd(c, "run", "--group-add=audio", "--group-add=staff", "--group-add=777", "busybox", "sh", "-c", "id").Combined() 1078 1079 groupsList := "uid=0(root) gid=0(root) groups=0(root),10(wheel),29(audio),50(staff),777" 1080 if actual := strings.Trim(out, "\r\n"); actual != groupsList { 1081 c.Fatalf("expected output %s received %s", groupsList, actual) 1082 } 1083 } 1084 1085 func (s *DockerCLIRunSuite) TestRunPrivilegedCanMount(c *testing.T) { 1086 // Not applicable for Windows as there is no concept of --privileged 1087 testRequires(c, DaemonIsLinux, NotUserNamespace) 1088 out := cli.DockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok").Combined() 1089 1090 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1091 c.Fatalf("expected output ok received %s", actual) 1092 } 1093 } 1094 1095 func (s *DockerCLIRunSuite) TestRunUnprivilegedCannotMount(c *testing.T) { 1096 // Not applicable for Windows as there is no concept of unprivileged 1097 testRequires(c, DaemonIsLinux) 1098 out, _, err := dockerCmdWithError("run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok") 1099 1100 if err == nil { 1101 c.Fatal(err, out) 1102 } 1103 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1104 c.Fatalf("expected output not ok received %s", actual) 1105 } 1106 } 1107 1108 func (s *DockerCLIRunSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *testing.T) { 1109 // Not applicable for Windows as there is no concept of unprivileged 1110 testRequires(c, DaemonIsLinux) 1111 if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 { 1112 c.Fatal("sys should not be writable in a non privileged container") 1113 } 1114 } 1115 1116 func (s *DockerCLIRunSuite) TestRunSysWritableInPrivilegedContainers(c *testing.T) { 1117 // Not applicable for Windows as there is no concept of unprivileged 1118 testRequires(c, DaemonIsLinux, NotUserNamespace) 1119 if _, code, err := dockerCmdWithError("run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 { 1120 c.Fatalf("sys should be writable in privileged container") 1121 } 1122 } 1123 1124 func (s *DockerCLIRunSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *testing.T) { 1125 // Not applicable for Windows as there is no concept of unprivileged 1126 testRequires(c, DaemonIsLinux) 1127 if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 { 1128 c.Fatal("proc should not be writable in a non privileged container") 1129 } 1130 } 1131 1132 func (s *DockerCLIRunSuite) TestRunProcWritableInPrivilegedContainers(c *testing.T) { 1133 // Not applicable for Windows as there is no concept of --privileged 1134 testRequires(c, DaemonIsLinux, NotUserNamespace) 1135 if result := cli.DockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "touch /proc/sysrq-trigger"); result.ExitCode != 0 { 1136 c.Fatalf("proc should be writable in privileged container") 1137 } 1138 } 1139 1140 func (s *DockerCLIRunSuite) TestRunDeviceNumbers(c *testing.T) { 1141 // Not applicable on Windows as /dev/ is a Unix specific concept 1142 // TODO: NotUserNamespace could be removed here if "root" "root" is replaced w user 1143 testRequires(c, DaemonIsLinux, NotUserNamespace) 1144 out := cli.DockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null").Combined() 1145 deviceLineFields := strings.Fields(out) 1146 deviceLineFields[6] = "" 1147 deviceLineFields[7] = "" 1148 deviceLineFields[8] = "" 1149 expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"} 1150 1151 if !(reflect.DeepEqual(deviceLineFields, expected)) { 1152 c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out) 1153 } 1154 } 1155 1156 func (s *DockerCLIRunSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *testing.T) { 1157 // Not applicable on Windows as /dev/ is a Unix specific concept 1158 testRequires(c, DaemonIsLinux) 1159 out := cli.DockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero").Combined() 1160 if actual := strings.Trim(out, "\r\n"); actual[0] == '0' { 1161 c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual) 1162 } 1163 } 1164 1165 func (s *DockerCLIRunSuite) TestRunUnprivilegedWithChroot(c *testing.T) { 1166 // Not applicable on Windows as it does not support chroot 1167 testRequires(c, DaemonIsLinux) 1168 cli.DockerCmd(c, "run", "busybox", "chroot", "/", "true") 1169 } 1170 1171 func (s *DockerCLIRunSuite) TestRunAddingOptionalDevices(c *testing.T) { 1172 // Not applicable on Windows as Windows does not support --device 1173 testRequires(c, DaemonIsLinux, NotUserNamespace) 1174 out := cli.DockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo").Combined() 1175 if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" { 1176 c.Fatalf("expected output /dev/nulo, received %s", actual) 1177 } 1178 } 1179 1180 func (s *DockerCLIRunSuite) TestRunAddingOptionalDevicesNoSrc(c *testing.T) { 1181 // Not applicable on Windows as Windows does not support --device 1182 testRequires(c, DaemonIsLinux, NotUserNamespace) 1183 out := cli.DockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero").Combined() 1184 if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" { 1185 c.Fatalf("expected output /dev/zero, received %s", actual) 1186 } 1187 } 1188 1189 func (s *DockerCLIRunSuite) TestRunAddingOptionalDevicesInvalidMode(c *testing.T) { 1190 // Not applicable on Windows as Windows does not support --device 1191 testRequires(c, DaemonIsLinux, NotUserNamespace) 1192 _, _, err := dockerCmdWithError("run", "--device", "/dev/zero:ro", "busybox", "sh", "-c", "ls /dev/zero") 1193 if err == nil { 1194 c.Fatalf("run container with device mode ro should fail") 1195 } 1196 } 1197 1198 func (s *DockerCLIRunSuite) TestRunModeHostname(c *testing.T) { 1199 // Not applicable on Windows as Windows does not support -h 1200 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 1201 1202 out := cli.DockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname").Combined() 1203 1204 if actual := strings.Trim(out, "\r\n"); actual != "testhostname" { 1205 c.Fatalf("expected 'testhostname', but says: %q", actual) 1206 } 1207 1208 out = cli.DockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname").Combined() 1209 1210 hostname, err := os.Hostname() 1211 if err != nil { 1212 c.Fatal(err) 1213 } 1214 if actual := strings.Trim(out, "\r\n"); actual != hostname { 1215 c.Fatalf("expected %q, but says: %q", hostname, actual) 1216 } 1217 } 1218 1219 func (s *DockerCLIRunSuite) TestRunRootWorkdir(c *testing.T) { 1220 out := cli.DockerCmd(c, "run", "--workdir", "/", "busybox", "pwd").Combined() 1221 expected := "/\n" 1222 if testEnv.DaemonInfo.OSType == "windows" { 1223 expected = "C:" + expected 1224 } 1225 if out != expected { 1226 c.Fatalf("pwd returned %q (expected %s)", out, expected) 1227 } 1228 } 1229 1230 func (s *DockerCLIRunSuite) TestRunAllowBindMountingRoot(c *testing.T) { 1231 if testEnv.DaemonInfo.OSType == "windows" { 1232 // Windows busybox will fail with Permission Denied on items such as pagefile.sys 1233 cli.DockerCmd(c, "run", "-v", `c:\:c:\host`, testEnv.PlatformDefaults.BaseImage, "cmd", "-c", "dir", `c:\host`) 1234 } else { 1235 cli.DockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host") 1236 } 1237 } 1238 1239 func (s *DockerCLIRunSuite) TestRunDisallowBindMountingRootToRoot(c *testing.T) { 1240 mount := "/:/" 1241 targetDir := "/host" 1242 if testEnv.DaemonInfo.OSType == "windows" { 1243 mount = `c:\:c\` 1244 targetDir = "c:/host" // Forward slash as using busybox 1245 } 1246 out, _, err := dockerCmdWithError("run", "-v", mount, "busybox", "ls", targetDir) 1247 if err == nil { 1248 c.Fatal(out, err) 1249 } 1250 } 1251 1252 // Verify that a container gets default DNS when only localhost resolvers exist 1253 func (s *DockerCLIRunSuite) TestRunDNSDefaultOptions(c *testing.T) { 1254 // Not applicable on Windows as this is testing Unix specific functionality 1255 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 1256 1257 // preserve original resolv.conf for restoring after test 1258 origResolvConf, err := os.ReadFile("/etc/resolv.conf") 1259 if os.IsNotExist(err) { 1260 c.Fatalf("/etc/resolv.conf does not exist") 1261 } 1262 // defer restored original conf 1263 defer func() { 1264 if err := os.WriteFile("/etc/resolv.conf", origResolvConf, 0o644); err != nil { 1265 c.Fatal(err) 1266 } 1267 }() 1268 1269 // test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost 1270 // 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by 1271 // GetNameservers(), leading to a replacement of nameservers with the default set 1272 tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1") 1273 if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0o644); err != nil { 1274 c.Fatal(err) 1275 } 1276 1277 actual := cli.DockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf").Combined() 1278 // check that the actual defaults are appended to the commented out 1279 // localhost resolver (which should be preserved) 1280 // NOTE: if we ever change the defaults from google dns, this will break 1281 expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n" 1282 if actual != expected { 1283 c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual) 1284 } 1285 } 1286 1287 func (s *DockerCLIRunSuite) TestRunDNSOptions(c *testing.T) { 1288 // Not applicable on Windows as Windows does not support --dns*, or 1289 // the Unix-specific functionality of resolv.conf. 1290 testRequires(c, DaemonIsLinux) 1291 result := cli.DockerCmd(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "--dns-opt=ndots:9", "busybox", "cat", "/etc/resolv.conf") 1292 1293 // The client will get a warning on stderr when setting DNS to a localhost address; verify this: 1294 if !strings.Contains(result.Stderr(), "Localhost DNS setting") { 1295 c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", result.Stderr()) 1296 } 1297 1298 actual := strings.ReplaceAll(strings.Trim(result.Stdout(), "\r\n"), "\n", " ") 1299 if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" { 1300 c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual) 1301 } 1302 1303 out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf").Combined() 1304 1305 actual = strings.ReplaceAll(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ") 1306 if actual != "nameserver 1.1.1.1 options ndots:3" { 1307 c.Fatalf("expected 'nameserver 1.1.1.1 options ndots:3', but says: %q", actual) 1308 } 1309 } 1310 1311 func (s *DockerCLIRunSuite) TestRunDNSRepeatOptions(c *testing.T) { 1312 testRequires(c, DaemonIsLinux) 1313 out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns=2.2.2.2", "--dns-search=mydomain", "--dns-search=mydomain2", "--dns-opt=ndots:9", "--dns-opt=timeout:3", "busybox", "cat", "/etc/resolv.conf").Stdout() 1314 1315 actual := strings.ReplaceAll(strings.Trim(out, "\r\n"), "\n", " ") 1316 if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" { 1317 c.Fatalf("expected 'search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3', but says: %q", actual) 1318 } 1319 } 1320 1321 func (s *DockerCLIRunSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) { 1322 // Not applicable on Windows as testing Unix specific functionality 1323 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 1324 1325 origResolvConf, err := os.ReadFile("/etc/resolv.conf") 1326 if os.IsNotExist(err) { 1327 c.Fatalf("/etc/resolv.conf does not exist") 1328 } 1329 1330 hostNameservers := resolvconf.GetNameservers(origResolvConf, resolvconf.IP) 1331 hostSearch := resolvconf.GetSearchDomains(origResolvConf) 1332 1333 out := cli.DockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf").Combined() 1334 1335 if actualNameservers := resolvconf.GetNameservers([]byte(out), resolvconf.IP); actualNameservers[0] != "127.0.0.1" { 1336 c.Fatalf("expected '127.0.0.1', but says: %q", actualNameservers[0]) 1337 } 1338 1339 actualSearch := resolvconf.GetSearchDomains([]byte(out)) 1340 if len(actualSearch) != len(hostSearch) { 1341 c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch)) 1342 } 1343 for i := range actualSearch { 1344 if actualSearch[i] != hostSearch[i] { 1345 c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i]) 1346 } 1347 } 1348 1349 out = cli.DockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf").Combined() 1350 1351 actualNameservers := resolvconf.GetNameservers([]byte(out), resolvconf.IP) 1352 if len(actualNameservers) != len(hostNameservers) { 1353 c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNameservers), len(actualNameservers)) 1354 } 1355 for i := range actualNameservers { 1356 if actualNameservers[i] != hostNameservers[i] { 1357 c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNameservers[i]) 1358 } 1359 } 1360 1361 if actualSearch = resolvconf.GetSearchDomains([]byte(out)); actualSearch[0] != "mydomain" { 1362 c.Fatalf("expected 'mydomain', but says: %q", actualSearch[0]) 1363 } 1364 1365 // test with file 1366 tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1") 1367 if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0o644); err != nil { 1368 c.Fatal(err) 1369 } 1370 // put the old resolvconf back 1371 defer func() { 1372 if err := os.WriteFile("/etc/resolv.conf", origResolvConf, 0o644); err != nil { 1373 c.Fatal(err) 1374 } 1375 }() 1376 1377 resolvConf, err := os.ReadFile("/etc/resolv.conf") 1378 if os.IsNotExist(err) { 1379 c.Fatalf("/etc/resolv.conf does not exist") 1380 } 1381 1382 hostSearch = resolvconf.GetSearchDomains(resolvConf) 1383 1384 out = cli.DockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf").Combined() 1385 if actualNameservers = resolvconf.GetNameservers([]byte(out), resolvconf.IP); actualNameservers[0] != "12.34.56.78" || len(actualNameservers) != 1 { 1386 c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers) 1387 } 1388 1389 actualSearch = resolvconf.GetSearchDomains([]byte(out)) 1390 if len(actualSearch) != len(hostSearch) { 1391 c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch)) 1392 } 1393 for i := range actualSearch { 1394 if actualSearch[i] != hostSearch[i] { 1395 c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i]) 1396 } 1397 } 1398 } 1399 1400 // Test to see if a non-root user can resolve a DNS name. Also 1401 // check if the container resolv.conf file has at least 0644 perm. 1402 func (s *DockerCLIRunSuite) TestRunNonRootUserResolvName(c *testing.T) { 1403 // Not applicable on Windows as Windows does not support --user 1404 testRequires(c, testEnv.IsLocalDaemon, Network, DaemonIsLinux) 1405 1406 cli.DockerCmd(c, "run", "--name=testperm", "--user=nobody", "busybox", "nslookup", "example.com") 1407 1408 cID := getIDByName(c, "testperm") 1409 1410 fmode := (os.FileMode)(0o644) 1411 finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf")) 1412 if err != nil { 1413 c.Fatal(err) 1414 } 1415 1416 if (finfo.Mode() & fmode) != fmode { 1417 c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String()) 1418 } 1419 } 1420 1421 // Test if container resolv.conf gets updated the next time it restarts 1422 // if host /etc/resolv.conf has changed. This only applies if the container 1423 // uses the host's /etc/resolv.conf and does not have any dns options provided. 1424 func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { 1425 // Not applicable on Windows as testing unix specific functionality 1426 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 1427 c.Skip("Unstable test, to be re-activated once #19937 is resolved") 1428 1429 tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n") 1430 tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1") 1431 1432 // take a copy of resolv.conf for restoring after test completes 1433 resolvConfSystem, err := os.ReadFile("/etc/resolv.conf") 1434 if err != nil { 1435 c.Fatal(err) 1436 } 1437 1438 // This test case is meant to test monitoring resolv.conf when it is 1439 // a regular file not a bind mounc. So we unmount resolv.conf and replace 1440 // it with a file containing the original settings. 1441 mounted, err := mountinfo.Mounted("/etc/resolv.conf") 1442 if err != nil { 1443 c.Fatal(err) 1444 } 1445 if mounted { 1446 icmd.RunCommand("umount", "/etc/resolv.conf").Assert(c, icmd.Success) 1447 } 1448 1449 // cleanup 1450 defer func() { 1451 if err := os.WriteFile("/etc/resolv.conf", resolvConfSystem, 0o644); err != nil { 1452 c.Fatal(err) 1453 } 1454 }() 1455 1456 // 1. test that a restarting container gets an updated resolv.conf 1457 cli.DockerCmd(c, "run", "--name=first", "busybox", "true") 1458 containerID1 := getIDByName(c, "first") 1459 1460 // replace resolv.conf with our temporary copy 1461 if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0o644); err != nil { 1462 c.Fatal(err) 1463 } 1464 1465 // start the container again to pickup changes 1466 cli.DockerCmd(c, "start", "first") 1467 1468 // check for update in container 1469 containerResolv := readContainerFile(c, containerID1, "resolv.conf") 1470 if !bytes.Equal(containerResolv, tmpResolvConf) { 1471 c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv)) 1472 } 1473 1474 /* // make a change to resolv.conf (in this case replacing our tmp copy with orig copy) 1475 if err := os.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1476 c.Fatal(err) 1477 } */ 1478 // 2. test that a restarting container does not receive resolv.conf updates 1479 // if it modified the container copy of the starting point resolv.conf 1480 cli.DockerCmd(c, "run", "--name=second", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf") 1481 containerID2 := getIDByName(c, "second") 1482 1483 // make a change to resolv.conf (in this case replacing our tmp copy with orig copy) 1484 if err := os.WriteFile("/etc/resolv.conf", resolvConfSystem, 0o644); err != nil { 1485 c.Fatal(err) 1486 } 1487 1488 // start the container again 1489 cli.DockerCmd(c, "start", "second") 1490 1491 // check for update in container 1492 containerResolv = readContainerFile(c, containerID2, "resolv.conf") 1493 if bytes.Equal(containerResolv, resolvConfSystem) { 1494 c.Fatalf("Container's resolv.conf should not have been updated with host resolv.conf: %q", string(containerResolv)) 1495 } 1496 1497 // 3. test that a running container's resolv.conf is not modified while running 1498 runningContainerID := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() 1499 runningContainerID = strings.TrimSpace(runningContainerID) 1500 1501 // replace resolv.conf 1502 if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0o644); err != nil { 1503 c.Fatal(err) 1504 } 1505 1506 // check for update in container 1507 containerResolv = readContainerFile(c, runningContainerID, "resolv.conf") 1508 if bytes.Equal(containerResolv, tmpResolvConf) { 1509 c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv)) 1510 } 1511 1512 // 4. test that a running container's resolv.conf is updated upon restart 1513 // (the above container is still running..) 1514 cli.DockerCmd(c, "restart", runningContainerID) 1515 1516 // check for update in container 1517 containerResolv = readContainerFile(c, runningContainerID, "resolv.conf") 1518 if !bytes.Equal(containerResolv, tmpResolvConf) { 1519 c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(tmpResolvConf), string(containerResolv)) 1520 } 1521 1522 // 5. test that additions of a localhost resolver are cleaned from 1523 // host resolv.conf before updating container's resolv.conf copies 1524 1525 // replace resolv.conf with a localhost-only nameserver copy 1526 if err = os.WriteFile("/etc/resolv.conf", tmpLocalhostResolvConf, 0o644); err != nil { 1527 c.Fatal(err) 1528 } 1529 1530 // start the container again to pickup changes 1531 cli.DockerCmd(c, "start", "first") 1532 1533 // our first exited container ID should have been updated, but with default DNS 1534 // after the cleanup of resolv.conf found only a localhost nameserver: 1535 containerResolv = readContainerFile(c, containerID1, "resolv.conf") 1536 expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n" 1537 if !bytes.Equal(containerResolv, []byte(expected)) { 1538 c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv)) 1539 } 1540 1541 // 6. Test that replacing (as opposed to modifying) resolv.conf triggers an update 1542 // of containers' resolv.conf. 1543 1544 // Restore the original resolv.conf 1545 if err := os.WriteFile("/etc/resolv.conf", resolvConfSystem, 0o644); err != nil { 1546 c.Fatal(err) 1547 } 1548 1549 // Run the container so it picks up the old settings 1550 cli.DockerCmd(c, "run", "--name=third", "busybox", "true") 1551 containerID3 := getIDByName(c, "third") 1552 1553 // Create a modified resolv.conf.aside and override resolv.conf with it 1554 if err := os.WriteFile("/etc/resolv.conf.aside", tmpResolvConf, 0o644); err != nil { 1555 c.Fatal(err) 1556 } 1557 1558 err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf") 1559 if err != nil { 1560 c.Fatal(err) 1561 } 1562 1563 // start the container again to pickup changes 1564 cli.DockerCmd(c, "start", "third") 1565 1566 // check for update in container 1567 containerResolv = readContainerFile(c, containerID3, "resolv.conf") 1568 if !bytes.Equal(containerResolv, tmpResolvConf) { 1569 c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv)) 1570 } 1571 1572 // cleanup, restore original resolv.conf happens in defer func() 1573 } 1574 1575 func (s *DockerCLIRunSuite) TestRunAddHost(c *testing.T) { 1576 // Not applicable on Windows as it does not support --add-host 1577 testRequires(c, DaemonIsLinux) 1578 out := cli.DockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts").Combined() 1579 1580 actual := strings.Trim(out, "\r\n") 1581 if actual != "86.75.30.9\textra" { 1582 c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual) 1583 } 1584 } 1585 1586 // Regression test for #6983 1587 func (s *DockerCLIRunSuite) TestRunAttachStdErrOnlyTTYMode(c *testing.T) { 1588 exitCode := cli.DockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true").ExitCode 1589 if exitCode != 0 { 1590 c.Fatalf("Container should have exited with error code 0") 1591 } 1592 } 1593 1594 // Regression test for #6983 1595 func (s *DockerCLIRunSuite) TestRunAttachStdOutOnlyTTYMode(c *testing.T) { 1596 exitCode := cli.DockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true").ExitCode 1597 if exitCode != 0 { 1598 c.Fatalf("Container should have exited with error code 0") 1599 } 1600 } 1601 1602 // Regression test for #6983 1603 func (s *DockerCLIRunSuite) TestRunAttachStdOutAndErrTTYMode(c *testing.T) { 1604 exitCode := cli.DockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true").ExitCode 1605 if exitCode != 0 { 1606 c.Fatalf("Container should have exited with error code 0") 1607 } 1608 } 1609 1610 // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode 1611 // but using --attach instead of -a to make sure we read the flag correctly 1612 func (s *DockerCLIRunSuite) TestRunAttachWithDetach(c *testing.T) { 1613 icmd.RunCommand(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true").Assert(c, icmd.Expected{ 1614 ExitCode: 1, 1615 Error: "exit status 1", 1616 Err: "Conflicting options: -a and -d", 1617 }) 1618 } 1619 1620 func (s *DockerCLIRunSuite) TestRunState(c *testing.T) { 1621 // TODO Windows: This needs some rework as Windows busybox does not support top 1622 testRequires(c, DaemonIsLinux) 1623 id := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() 1624 id = strings.TrimSpace(id) 1625 1626 state := inspectField(c, id, "State.Running") 1627 if state != "true" { 1628 c.Fatal("Container state is 'not running'") 1629 } 1630 pid1 := inspectField(c, id, "State.Pid") 1631 if pid1 == "0" { 1632 c.Fatal("Container state Pid 0") 1633 } 1634 1635 cli.DockerCmd(c, "stop", id) 1636 state = inspectField(c, id, "State.Running") 1637 if state != "false" { 1638 c.Fatal("Container state is 'running'") 1639 } 1640 pid2 := inspectField(c, id, "State.Pid") 1641 if pid2 == pid1 { 1642 c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) 1643 } 1644 1645 cli.DockerCmd(c, "start", id) 1646 state = inspectField(c, id, "State.Running") 1647 if state != "true" { 1648 c.Fatal("Container state is 'not running'") 1649 } 1650 pid3 := inspectField(c, id, "State.Pid") 1651 if pid3 == pid1 { 1652 c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) 1653 } 1654 } 1655 1656 // Test for #1737 1657 func (s *DockerCLIRunSuite) TestRunCopyVolumeUIDGID(c *testing.T) { 1658 // Not applicable on Windows as it does not support uid or gid in this way 1659 testRequires(c, DaemonIsLinux) 1660 name := "testrunvolumesuidgid" 1661 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 1662 RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd 1663 RUN echo 'dockerio:x:1001:' >> /etc/group 1664 RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`)) 1665 1666 // Test that the uid and gid is copied from the image to the volume 1667 out := cli.DockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", `ls -l / | grep hello | awk '{print $3":"$4}'`).Combined() 1668 out = strings.TrimSpace(out) 1669 if out != "dockerio:dockerio" { 1670 c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out) 1671 } 1672 } 1673 1674 // Test for #1582 1675 func (s *DockerCLIRunSuite) TestRunCopyVolumeContent(c *testing.T) { 1676 // TODO Windows, post RS1. Windows does not yet support volume functionality 1677 // that copies from the image to the volume. 1678 testRequires(c, DaemonIsLinux) 1679 name := "testruncopyvolumecontent" 1680 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 1681 RUN mkdir -p /hello/local && echo hello > /hello/local/world`)) 1682 1683 // Test that the content is copied from the image to the volume 1684 out := cli.DockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello").Combined() 1685 if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) { 1686 c.Fatal("Container failed to transfer content to volume") 1687 } 1688 } 1689 1690 func (s *DockerCLIRunSuite) TestRunCleanupCmdOnEntrypoint(c *testing.T) { 1691 name := "testrunmdcleanuponentrypoint" 1692 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 1693 ENTRYPOINT ["echo"] 1694 CMD ["testingpoint"]`)) 1695 1696 result := cli.DockerCmd(c, "run", "--entrypoint", "whoami", name) 1697 out := strings.TrimSpace(result.Combined()) 1698 if result.ExitCode != 0 { 1699 c.Fatalf("expected exit code 0 received %d, out: %q", result.ExitCode, out) 1700 } 1701 expected := "root" 1702 if testEnv.DaemonInfo.OSType == "windows" { 1703 if strings.Contains(testEnv.PlatformDefaults.BaseImage, "servercore") { 1704 expected = `user manager\containeradministrator` 1705 } else { 1706 expected = `ContainerAdministrator` // nanoserver 1707 } 1708 } 1709 if out != expected { 1710 c.Fatalf("Expected output %s, got %q. %s", expected, out, testEnv.PlatformDefaults.BaseImage) 1711 } 1712 } 1713 1714 // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected 1715 func (s *DockerCLIRunSuite) TestRunWorkdirExistsAndIsFile(c *testing.T) { 1716 existingFile := "/bin/cat" 1717 expected := "not a directory" 1718 if testEnv.DaemonInfo.OSType == "windows" { 1719 existingFile = `\windows\system32\ntdll.dll` 1720 expected = `The directory name is invalid.` 1721 } 1722 1723 out, exitCode, err := dockerCmdWithError("run", "-w", existingFile, "busybox") 1724 if !(err != nil && exitCode == 125 && strings.Contains(out, expected)) { 1725 c.Fatalf("Existing binary as a directory should error out with exitCode 125; we got: %s, exitCode: %d", out, exitCode) 1726 } 1727 } 1728 1729 func (s *DockerCLIRunSuite) TestRunExitOnStdinClose(c *testing.T) { 1730 name := "testrunexitonstdinclose" 1731 1732 meow := "/bin/cat" 1733 delay := 60 1734 if testEnv.DaemonInfo.OSType == "windows" { 1735 meow = "cat" 1736 } 1737 runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow) 1738 1739 stdin, err := runCmd.StdinPipe() 1740 if err != nil { 1741 c.Fatal(err) 1742 } 1743 stdout, err := runCmd.StdoutPipe() 1744 if err != nil { 1745 c.Fatal(err) 1746 } 1747 1748 if err := runCmd.Start(); err != nil { 1749 c.Fatal(err) 1750 } 1751 if _, err := stdin.Write([]byte("hello\n")); err != nil { 1752 c.Fatal(err) 1753 } 1754 1755 r := bufio.NewReader(stdout) 1756 line, err := r.ReadString('\n') 1757 if err != nil { 1758 c.Fatal(err) 1759 } 1760 line = strings.TrimSpace(line) 1761 if line != "hello" { 1762 c.Fatalf("Output should be 'hello', got '%q'", line) 1763 } 1764 if err := stdin.Close(); err != nil { 1765 c.Fatal(err) 1766 } 1767 finish := make(chan error, 1) 1768 go func() { 1769 finish <- runCmd.Wait() 1770 close(finish) 1771 }() 1772 select { 1773 case err := <-finish: 1774 assert.NilError(c, err) 1775 case <-time.After(time.Duration(delay) * time.Second): 1776 c.Fatal("docker run failed to exit on stdin close") 1777 } 1778 state := inspectField(c, name, "State.Running") 1779 1780 if state != "false" { 1781 c.Fatal("Container must be stopped after stdin closing") 1782 } 1783 } 1784 1785 // Test run -i --restart xxx doesn't hang 1786 func (s *DockerCLIRunSuite) TestRunInteractiveWithRestartPolicy(c *testing.T) { 1787 name := "test-inter-restart" 1788 1789 result := icmd.RunCmd(icmd.Cmd{ 1790 Command: []string{dockerBinary, "run", "-i", "--name", name, "--restart=always", "busybox", "sh"}, 1791 Stdin: bytes.NewBufferString("exit 11"), 1792 }) 1793 defer func() { 1794 cli.Docker(cli.Args("stop", name)).Assert(c, icmd.Success) 1795 }() 1796 1797 result.Assert(c, icmd.Expected{ExitCode: 11}) 1798 } 1799 1800 // Test for #2267 1801 func (s *DockerCLIRunSuite) TestRunWriteSpecialFilesAndNotCommit(c *testing.T) { 1802 // Cannot run on Windows as this files are not present in Windows 1803 testRequires(c, DaemonIsLinux) 1804 1805 testRunWriteSpecialFilesAndNotCommit(c, "writehosts", "/etc/hosts") 1806 testRunWriteSpecialFilesAndNotCommit(c, "writehostname", "/etc/hostname") 1807 testRunWriteSpecialFilesAndNotCommit(c, "writeresolv", "/etc/resolv.conf") 1808 } 1809 1810 func testRunWriteSpecialFilesAndNotCommit(c *testing.T, name, path string) { 1811 command := fmt.Sprintf("echo test2267 >> %s && cat %s", path, path) 1812 out := cli.DockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", command).Combined() 1813 if !strings.Contains(out, "test2267") { 1814 c.Fatalf("%s should contain 'test2267'", path) 1815 } 1816 1817 out = cli.DockerCmd(c, "diff", name).Combined() 1818 if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { 1819 c.Fatal("diff should be empty") 1820 } 1821 } 1822 1823 func eqToBaseDiff(out string, c *testing.T) bool { 1824 name := "eqToBaseDiff" + testutil.GenerateRandomAlphaOnlyString(32) 1825 cli.DockerCmd(c, "run", "--name", name, "busybox", "echo", "hello") 1826 cID := getIDByName(c, name) 1827 baseDiff := cli.DockerCmd(c, "diff", cID).Combined() 1828 baseArr := strings.Split(baseDiff, "\n") 1829 sort.Strings(baseArr) 1830 outArr := strings.Split(out, "\n") 1831 sort.Strings(outArr) 1832 return sliceEq(baseArr, outArr) 1833 } 1834 1835 func sliceEq(a, b []string) bool { 1836 if len(a) != len(b) { 1837 return false 1838 } 1839 1840 for i := range a { 1841 if a[i] != b[i] { 1842 return false 1843 } 1844 } 1845 1846 return true 1847 } 1848 1849 func (s *DockerCLIRunSuite) TestRunWithBadDevice(c *testing.T) { 1850 // Cannot run on Windows as Windows does not support --device 1851 testRequires(c, DaemonIsLinux) 1852 name := "baddevice" 1853 out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true") 1854 1855 if err == nil { 1856 c.Fatal("Run should fail with bad device") 1857 } 1858 expected := `"/etc": not a device node` 1859 if !strings.Contains(out, expected) { 1860 c.Fatalf("Output should contain %q, actual out: %q", expected, out) 1861 } 1862 } 1863 1864 func (s *DockerCLIRunSuite) TestRunEntrypoint(c *testing.T) { 1865 const name = "entrypoint" 1866 const expected = "foobar" 1867 1868 out := cli.DockerCmd(c, "run", "--name", name, "--entrypoint", "echo", "busybox", "-n", "foobar").Combined() 1869 if out != expected { 1870 c.Fatalf("Output should be %q, actual out: %q", expected, out) 1871 } 1872 } 1873 1874 func (s *DockerCLIRunSuite) TestRunBindMounts(c *testing.T) { 1875 testRequires(c, testEnv.IsLocalDaemon) 1876 if testEnv.DaemonInfo.OSType == "linux" { 1877 testRequires(c, DaemonIsLinux, NotUserNamespace) 1878 } 1879 1880 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 1881 1882 tmpDir, err := os.MkdirTemp("", "docker-test-container") 1883 if err != nil { 1884 c.Fatal(err) 1885 } 1886 1887 defer os.RemoveAll(tmpDir) 1888 writeFile(path.Join(tmpDir, "touch-me"), "", c) 1889 1890 // Test reading from a read-only bind mount 1891 out := cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:%s/tmpx:ro", tmpDir, prefix), "busybox", "ls", prefix+"/tmpx").Combined() 1892 if !strings.Contains(out, "touch-me") { 1893 c.Fatal("Container failed to read from bind mount") 1894 } 1895 1896 // test writing to bind mount 1897 if testEnv.DaemonInfo.OSType == "windows" { 1898 cli.DockerCmd(c, "run", "-v", fmt.Sprintf(`%s:c:\tmp:rw`, tmpDir), "busybox", "touch", "c:/tmp/holla") 1899 } else { 1900 cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla") 1901 } 1902 1903 readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist 1904 1905 // test mounting to an illegal destination directory 1906 _, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".") 1907 if err == nil { 1908 c.Fatal("Container bind mounted illegal directory") 1909 } 1910 1911 // Windows does not (and likely never will) support mounting a single file 1912 if testEnv.DaemonInfo.OSType != "windows" { 1913 // test mount a file 1914 cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla") 1915 content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist 1916 expected := "yotta" 1917 if content != expected { 1918 c.Fatalf("Output should be %q, actual out: %q", expected, content) 1919 } 1920 } 1921 } 1922 1923 // Ensure that CIDFile gets deleted if it's empty 1924 // Perform this test by making `docker run` fail 1925 func (s *DockerCLIRunSuite) TestRunCidFileCleanupIfEmpty(c *testing.T) { 1926 // Skip on Windows. Base image on Windows has a CMD set in the image. 1927 testRequires(c, DaemonIsLinux) 1928 1929 tmpDir, err := os.MkdirTemp("", "TestRunCidFile") 1930 if err != nil { 1931 c.Fatal(err) 1932 } 1933 defer os.RemoveAll(tmpDir) 1934 tmpCidFile := path.Join(tmpDir, "cid") 1935 1936 // This must be an image that has no CMD or ENTRYPOINT set 1937 imgRef := loadSpecialImage(c, specialimage.EmptyFS) 1938 1939 out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, imgRef) 1940 if err == nil { 1941 c.Fatalf("Run without command must fail. out=%s", out) 1942 } else if !strings.Contains(out, "no command specified") { 1943 c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err) 1944 } 1945 1946 if _, err := os.Stat(tmpCidFile); err == nil { 1947 c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile) 1948 } 1949 } 1950 1951 // #2098 - Docker cidFiles only contain short version of the containerId 1952 // sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test" 1953 // TestRunCidFile tests that run --cidfile returns the longid 1954 func (s *DockerCLIRunSuite) TestRunCidFileCheckIDLength(c *testing.T) { 1955 tmpDir, err := os.MkdirTemp("", "TestRunCidFile") 1956 if err != nil { 1957 c.Fatal(err) 1958 } 1959 tmpCidFile := path.Join(tmpDir, "cid") 1960 defer os.RemoveAll(tmpDir) 1961 1962 id := cli.DockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true").Stdout() 1963 id = strings.TrimSpace(id) 1964 buffer, err := os.ReadFile(tmpCidFile) 1965 if err != nil { 1966 c.Fatal(err) 1967 } 1968 cid := string(buffer) 1969 if len(cid) != 64 { 1970 c.Fatalf("--cidfile should be a long id, not %q", id) 1971 } 1972 if cid != id { 1973 c.Fatalf("cid must be equal to %s, got %s", id, cid) 1974 } 1975 } 1976 1977 func (s *DockerCLIRunSuite) TestRunSetMacAddress(c *testing.T) { 1978 skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination") 1979 mac := "12:34:56:78:9a:bc" 1980 var out string 1981 if testEnv.DaemonInfo.OSType == "windows" { 1982 out = cli.DockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'").Combined() 1983 mac = strings.ReplaceAll(strings.ToUpper(mac), ":", "-") // To Windows-style MACs 1984 } else { 1985 out = cli.DockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'").Combined() 1986 } 1987 1988 actualMac := strings.TrimSpace(out) 1989 if actualMac != mac { 1990 c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac) 1991 } 1992 } 1993 1994 func (s *DockerCLIRunSuite) TestRunInspectMacAddress(c *testing.T) { 1995 // TODO Windows. Network settings are not propagated back to inspect. 1996 testRequires(c, DaemonIsLinux) 1997 const mac = "12:34:56:78:9a:bc" 1998 out := cli.DockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top").Combined() 1999 2000 id := strings.TrimSpace(out) 2001 inspectedMac := inspectField(c, id, "NetworkSettings.Networks.bridge.MacAddress") 2002 if inspectedMac != mac { 2003 c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac) 2004 } 2005 } 2006 2007 // test docker run use an invalid mac address 2008 func (s *DockerCLIRunSuite) TestRunWithInvalidMacAddress(c *testing.T) { 2009 out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox") 2010 // use an invalid mac address should with an error out 2011 if err == nil || !strings.Contains(out, "is not a valid mac address") { 2012 c.Fatalf("run with an invalid --mac-address should with error out") 2013 } 2014 } 2015 2016 func (s *DockerCLIRunSuite) TestRunDeallocatePortOnMissingIptablesRule(c *testing.T) { 2017 // TODO Windows. Network settings are not propagated back to inspect. 2018 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 2019 2020 out := cli.DockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top").Combined() 2021 2022 id := strings.TrimSpace(out) 2023 ip := inspectField(c, id, "NetworkSettings.Networks.bridge.IPAddress") 2024 icmd.RunCommand("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip), 2025 "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT").Assert(c, icmd.Success) 2026 2027 cli.DockerCmd(c, "rm", "-fv", id) 2028 2029 cli.DockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top") 2030 } 2031 2032 func (s *DockerCLIRunSuite) TestRunPortInUse(c *testing.T) { 2033 // TODO Windows. The duplicate NAT message returned by Windows will be 2034 // changing as is currently completely undecipherable. Does need modifying 2035 // to run sh rather than top though as top isn't in Windows busybox. 2036 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 2037 2038 port := "1234" 2039 cli.DockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top") 2040 2041 out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top") 2042 if err == nil { 2043 c.Fatalf("Binding on used port must fail") 2044 } 2045 if !strings.Contains(out, "port is already allocated") { 2046 c.Fatalf(`Out must be about "port is already allocated", got %s`, out) 2047 } 2048 } 2049 2050 // https://github.com/docker/docker/issues/12148 2051 func (s *DockerCLIRunSuite) TestRunAllocatePortInReservedRange(c *testing.T) { 2052 // TODO Windows. -P is not yet supported 2053 testRequires(c, DaemonIsLinux) 2054 // allocate a dynamic port to get the most recent 2055 id := cli.DockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top").Stdout() 2056 id = strings.TrimSpace(id) 2057 2058 out := cli.DockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, id).Stdout() 2059 out = strings.TrimSpace(out) 2060 port, err := strconv.ParseInt(out, 10, 64) 2061 if err != nil { 2062 c.Fatalf("invalid port, got: %s, error: %s", out, err) 2063 } 2064 2065 // allocate a static port and a dynamic port together, with static port 2066 // takes the next recent port in dynamic port range. 2067 cli.DockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top") 2068 } 2069 2070 // Regression test for #7792 2071 func (s *DockerCLIRunSuite) TestRunMountOrdering(c *testing.T) { 2072 // TODO Windows: Post RS1. Windows does not support nested mounts. 2073 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 2074 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2075 2076 tmpDir, err := os.MkdirTemp("", "docker_nested_mount_test") 2077 if err != nil { 2078 c.Fatal(err) 2079 } 2080 defer os.RemoveAll(tmpDir) 2081 2082 tmpDir2, err := os.MkdirTemp("", "docker_nested_mount_test2") 2083 if err != nil { 2084 c.Fatal(err) 2085 } 2086 defer os.RemoveAll(tmpDir2) 2087 2088 // Create a temporary tmpfs mounc. 2089 fooDir := filepath.Join(tmpDir, "foo") 2090 if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0o755); err != nil { 2091 c.Fatalf("failed to mkdir at %s - %s", fooDir, err) 2092 } 2093 2094 if err := os.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0o644); err != nil { 2095 c.Fatal(err) 2096 } 2097 2098 if err := os.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0o644); err != nil { 2099 c.Fatal(err) 2100 } 2101 2102 if err := os.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0o644); err != nil { 2103 c.Fatal(err) 2104 } 2105 2106 cli.DockerCmd(c, "run", 2107 "-v", fmt.Sprintf("%s:"+prefix+"/tmp", tmpDir), 2108 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/foo", fooDir), 2109 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2", tmpDir2), 2110 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2/foo", fooDir), 2111 "busybox:latest", "sh", "-c", 2112 "ls "+prefix+"/tmp/touch-me && ls "+prefix+"/tmp/foo/touch-me && ls "+prefix+"/tmp/tmp2/touch-me && ls "+prefix+"/tmp/tmp2/foo/touch-me") 2113 } 2114 2115 // Regression test for https://github.com/docker/docker/issues/8259 2116 func (s *DockerCLIRunSuite) TestRunReuseBindVolumeThatIsSymlink(c *testing.T) { 2117 // Not applicable on Windows as Windows does not support volumes 2118 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 2119 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2120 2121 tmpDir, err := os.MkdirTemp(os.TempDir(), "testlink") 2122 if err != nil { 2123 c.Fatal(err) 2124 } 2125 defer os.RemoveAll(tmpDir) 2126 2127 linkPath := os.TempDir() + "/testlink2" 2128 if err := os.Symlink(tmpDir, linkPath); err != nil { 2129 c.Fatal(err) 2130 } 2131 defer os.RemoveAll(linkPath) 2132 2133 // Create first container 2134 cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") 2135 2136 // Create second container with same symlinked path 2137 // This will fail if the referenced issue is hit with a "Volume exists" error 2138 cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") 2139 } 2140 2141 // GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container 2142 func (s *DockerCLIRunSuite) TestRunCreateVolumeEtc(c *testing.T) { 2143 // While Windows supports volumes, it does not support --add-host hence 2144 // this test is not applicable on Windows. 2145 testRequires(c, DaemonIsLinux) 2146 out := cli.DockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf").Stdout() 2147 if !strings.Contains(out, "nameserver 127.0.0.1") { 2148 c.Fatal("/etc volume mount hides /etc/resolv.conf") 2149 } 2150 2151 out = cli.DockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname").Stdout() 2152 if !strings.Contains(out, "test123") { 2153 c.Fatal("/etc volume mount hides /etc/hostname") 2154 } 2155 2156 out = cli.DockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts").Stdout() 2157 out = strings.ReplaceAll(out, "\n", " ") 2158 if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") { 2159 c.Fatal("/etc volume mount hides /etc/hosts") 2160 } 2161 } 2162 2163 func (s *DockerCLIRunSuite) TestVolumesNoCopyData(c *testing.T) { 2164 // TODO Windows (Post RS1). Windows does not support volumes which 2165 // are pre-populated such as is built in the dockerfile used in this test. 2166 testRequires(c, DaemonIsLinux) 2167 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 2168 buildImageSuccessfully(c, "dataimage", build.WithDockerfile(`FROM busybox 2169 RUN ["mkdir", "-p", "/foo"] 2170 RUN ["touch", "/foo/bar"]`)) 2171 cli.DockerCmd(c, "run", "--name", "test", "-v", prefix+slash+"foo", "busybox") 2172 2173 if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { 2174 c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out) 2175 } 2176 2177 tmpDir := RandomTmpDirPath("docker_test_bind_mount_copy_data", testEnv.DaemonInfo.OSType) 2178 if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { 2179 c.Fatalf("Data was copied on bind mount but shouldn't be:\n%q", out) 2180 } 2181 } 2182 2183 func (s *DockerCLIRunSuite) TestRunNoOutputFromPullInStdout(c *testing.T) { 2184 // just run with unknown image 2185 cmd := exec.Command(dockerBinary, "run", "asdfsg") 2186 stdout := bytes.NewBuffer(nil) 2187 cmd.Stdout = stdout 2188 if err := cmd.Run(); err == nil { 2189 c.Fatal("Run with unknown image should fail") 2190 } 2191 if stdout.Len() != 0 { 2192 c.Fatalf("Stdout contains output from pull: %s", stdout) 2193 } 2194 } 2195 2196 func (s *DockerCLIRunSuite) TestRunVolumesCleanPaths(c *testing.T) { 2197 testRequires(c, testEnv.IsLocalDaemon) 2198 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 2199 buildImageSuccessfully(c, "run_volumes_clean_paths", build.WithDockerfile(`FROM busybox 2200 VOLUME `+prefix+`/foo/`)) 2201 cli.DockerCmd(c, "run", "-v", prefix+"/foo", "-v", prefix+"/bar/", "--name", "dark_helmet", "run_volumes_clean_paths") 2202 2203 out, err := inspectMountSourceField("dark_helmet", prefix+slash+"foo"+slash) 2204 if err != errMountNotFound { 2205 c.Fatalf("Found unexpected volume entry for '%s/foo/' in volumes\n%q", prefix, out) 2206 } 2207 2208 out, err = inspectMountSourceField("dark_helmet", prefix+slash+`foo`) 2209 assert.NilError(c, err) 2210 if !strings.Contains(strings.ToLower(out), strings.ToLower(testEnv.PlatformDefaults.VolumesConfigPath)) { 2211 c.Fatalf("Volume was not defined for %s/foo\n%q", prefix, out) 2212 } 2213 2214 out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar"+slash) 2215 if err != errMountNotFound { 2216 c.Fatalf("Found unexpected volume entry for '%s/bar/' in volumes\n%q", prefix, out) 2217 } 2218 2219 out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar") 2220 assert.NilError(c, err) 2221 if !strings.Contains(strings.ToLower(out), strings.ToLower(testEnv.PlatformDefaults.VolumesConfigPath)) { 2222 c.Fatalf("Volume was not defined for %s/bar\n%q", prefix, out) 2223 } 2224 } 2225 2226 // Regression test for #3631 2227 func (s *DockerCLIRunSuite) TestRunSlowStdoutConsumer(c *testing.T) { 2228 // TODO Windows: This should be able to run on Windows if can find an 2229 // alternate to /dev/zero and /dev/stdout. 2230 testRequires(c, DaemonIsLinux) 2231 2232 args := []string{"run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | cat -v"} 2233 cont := exec.Command(dockerBinary, args...) 2234 2235 stdout, err := cont.StdoutPipe() 2236 if err != nil { 2237 c.Fatal(err) 2238 } 2239 2240 if err := cont.Start(); err != nil { 2241 c.Fatal(err) 2242 } 2243 defer func() { go cont.Wait() }() 2244 n, err := ConsumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil) 2245 if err != nil { 2246 c.Fatal(err) 2247 } 2248 2249 expected := 2 * 1024 * 2000 2250 if n != expected { 2251 c.Fatalf("Expected %d, got %d", expected, n) 2252 } 2253 } 2254 2255 func (s *DockerCLIRunSuite) TestRunAllowPortRangeThroughExpose(c *testing.T) { 2256 // TODO Windows: -P is not currently supported. Also network 2257 // settings are not propagated back. 2258 testRequires(c, DaemonIsLinux) 2259 id := cli.DockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top").Stdout() 2260 id = strings.TrimSpace(id) 2261 2262 portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports") 2263 var ports nat.PortMap 2264 if err := json.Unmarshal([]byte(portstr), &ports); err != nil { 2265 c.Fatal(err) 2266 } 2267 for port, binding := range ports { 2268 portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) 2269 if portnum < 3000 || portnum > 3003 { 2270 c.Fatalf("Port %d is out of range ", portnum) 2271 } 2272 if len(binding) == 0 || len(binding[0].HostPort) == 0 { 2273 c.Fatalf("Port is not mapped for the port %s", port) 2274 } 2275 } 2276 } 2277 2278 func (s *DockerCLIRunSuite) TestRunExposePort(c *testing.T) { 2279 out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox") 2280 assert.Assert(c, err != nil, "--expose with an invalid port should error out") 2281 assert.Assert(c, strings.Contains(out, "invalid range format for --expose")) 2282 } 2283 2284 func (s *DockerCLIRunSuite) TestRunModeIpcHost(c *testing.T) { 2285 // Not applicable on Windows as uses Unix-specific capabilities 2286 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 2287 2288 hostIpc, err := os.Readlink("/proc/1/ns/ipc") 2289 if err != nil { 2290 c.Fatal(err) 2291 } 2292 2293 out := cli.DockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc").Combined() 2294 out = strings.Trim(out, "\n") 2295 if hostIpc != out { 2296 c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out) 2297 } 2298 2299 out = cli.DockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc").Combined() 2300 out = strings.Trim(out, "\n") 2301 if hostIpc == out { 2302 c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out) 2303 } 2304 } 2305 2306 func (s *DockerCLIRunSuite) TestRunModeIpcContainerNotExists(c *testing.T) { 2307 // Not applicable on Windows as uses Unix-specific capabilities 2308 testRequires(c, DaemonIsLinux) 2309 out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top") 2310 if !strings.Contains(out, "abcd1234") || err == nil { 2311 c.Fatalf("run IPC from a non exists container should with correct error out") 2312 } 2313 } 2314 2315 func (s *DockerCLIRunSuite) TestRunModeIpcContainerNotRunning(c *testing.T) { 2316 // Not applicable on Windows as uses Unix-specific capabilities 2317 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 2318 2319 id := cli.DockerCmd(c, "create", "busybox").Stdout() 2320 id = strings.TrimSpace(id) 2321 2322 out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox") 2323 if err == nil { 2324 c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err) 2325 } 2326 } 2327 2328 func (s *DockerCLIRunSuite) TestRunModePIDContainer(c *testing.T) { 2329 // Not applicable on Windows as uses Unix-specific capabilities 2330 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 2331 2332 id := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", "top").Stdout() 2333 id = strings.TrimSpace(id) 2334 2335 state := inspectField(c, id, "State.Running") 2336 if state != "true" { 2337 c.Fatal("Container state is 'not running'") 2338 } 2339 pid1 := inspectField(c, id, "State.Pid") 2340 2341 parentContainerPid, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/pid", pid1)) 2342 if err != nil { 2343 c.Fatal(err) 2344 } 2345 2346 out := cli.DockerCmd(c, "run", fmt.Sprintf("--pid=container:%s", id), "busybox", "readlink", "/proc/self/ns/pid").Combined() 2347 out = strings.Trim(out, "\n") 2348 if parentContainerPid != out { 2349 c.Fatalf("PID different with --pid=container:%s %s != %s\n", id, parentContainerPid, out) 2350 } 2351 } 2352 2353 func (s *DockerCLIRunSuite) TestRunModePIDContainerNotExists(c *testing.T) { 2354 // Not applicable on Windows as uses Unix-specific capabilities 2355 testRequires(c, DaemonIsLinux) 2356 out, _, err := dockerCmdWithError("run", "-d", "--pid", "container:abcd1234", "busybox", "top") 2357 if !strings.Contains(out, "abcd1234") || err == nil { 2358 c.Fatalf("run PID from a non exists container should with correct error out") 2359 } 2360 } 2361 2362 func (s *DockerCLIRunSuite) TestRunModePIDContainerNotRunning(c *testing.T) { 2363 // Not applicable on Windows as uses Unix-specific capabilities 2364 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 2365 2366 id := cli.DockerCmd(c, "create", "busybox").Stdout() 2367 id = strings.TrimSpace(id) 2368 2369 out, _, err := dockerCmdWithError("run", fmt.Sprintf("--pid=container:%s", id), "busybox") 2370 if err == nil { 2371 c.Fatalf("Run container with pid mode container should fail with non running container: %s\n%s", out, err) 2372 } 2373 } 2374 2375 func (s *DockerCLIRunSuite) TestRunMountShmMqueueFromHost(c *testing.T) { 2376 // Not applicable on Windows as uses Unix-specific capabilities 2377 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 2378 2379 cli.DockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "-v", "/dev/mqueue:/dev/mqueue", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top") 2380 defer os.Remove("/dev/mqueue/toto") 2381 defer os.Remove("/dev/shm/test") 2382 volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm") 2383 assert.NilError(c, err) 2384 if volPath != "/dev/shm" { 2385 c.Fatalf("volumePath should have been /dev/shm, was %s", volPath) 2386 } 2387 2388 out := cli.DockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test").Combined() 2389 if out != "test" { 2390 c.Fatalf("Output of /dev/shm/test expected test but found: %s", out) 2391 } 2392 2393 // Check that the mq was created 2394 if _, err := os.Stat("/dev/mqueue/toto"); err != nil { 2395 c.Fatalf("Failed to confirm '/dev/mqueue/toto' presence on host: %s", err.Error()) 2396 } 2397 } 2398 2399 func (s *DockerCLIRunSuite) TestContainerNetworkMode(c *testing.T) { 2400 // Not applicable on Windows as uses Unix-specific capabilities 2401 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 2402 2403 id := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() 2404 id = strings.TrimSpace(id) 2405 cli.WaitRun(c, id) 2406 pid1 := inspectField(c, id, "State.Pid") 2407 2408 parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) 2409 if err != nil { 2410 c.Fatal(err) 2411 } 2412 2413 out := cli.DockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net").Combined() 2414 out = strings.Trim(out, "\n") 2415 if parentContainerNet != out { 2416 c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out) 2417 } 2418 } 2419 2420 func (s *DockerCLIRunSuite) TestRunModeUTSHost(c *testing.T) { 2421 // Not applicable on Windows as uses Unix-specific capabilities 2422 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 2423 2424 hostUTS, err := os.Readlink("/proc/1/ns/uts") 2425 if err != nil { 2426 c.Fatal(err) 2427 } 2428 2429 out := cli.DockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts").Combined() 2430 out = strings.Trim(out, "\n") 2431 if hostUTS != out { 2432 c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out) 2433 } 2434 2435 out = cli.DockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts").Combined() 2436 out = strings.Trim(out, "\n") 2437 if hostUTS == out { 2438 c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out) 2439 } 2440 2441 out = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps") 2442 assert.Assert(c, strings.Contains(out, runconfig.ErrConflictUTSHostname.Error())) 2443 } 2444 2445 func (s *DockerCLIRunSuite) TestRunTLSVerify(c *testing.T) { 2446 // Remote daemons use TLS and this test is not applicable when TLS is required. 2447 testRequires(c, testEnv.IsLocalDaemon) 2448 if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 { 2449 c.Fatalf("Should have worked: %v:\n%v", err, out) 2450 } 2451 2452 // Regardless of whether we specify true or false we need to 2453 // test to make sure tls is turned on if --tlsverify is specified at all 2454 result := dockerCmdWithResult("--tlsverify=false", "ps") 2455 result.Assert(c, icmd.Expected{ExitCode: 1, Err: "error during connect"}) 2456 2457 result = dockerCmdWithResult("--tlsverify=true", "ps") 2458 result.Assert(c, icmd.Expected{ExitCode: 1, Err: "cert"}) 2459 } 2460 2461 func (s *DockerCLIRunSuite) TestRunPortFromDockerRangeInUse(c *testing.T) { 2462 // TODO Windows. Once moved to libnetwork/CNM, this may be able to be 2463 // re-instated. 2464 testRequires(c, DaemonIsLinux) 2465 // first find allocator current position 2466 id := cli.DockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top").Stdout() 2467 id = strings.TrimSpace(id) 2468 2469 out := cli.DockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, id).Stdout() 2470 out = strings.TrimSpace(out) 2471 if out == "" { 2472 c.Fatal("docker port command output is empty") 2473 } 2474 lastPort, err := strconv.Atoi(out) 2475 if err != nil { 2476 c.Fatal(err) 2477 } 2478 port := lastPort + 1 2479 l, err := net.Listen("tcp", ":"+strconv.Itoa(port)) 2480 if err != nil { 2481 c.Fatal(err) 2482 } 2483 defer l.Close() 2484 2485 id = cli.DockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top").Stdout() 2486 id = strings.TrimSpace(id) 2487 cli.DockerCmd(c, "port", id) 2488 } 2489 2490 func (s *DockerCLIRunSuite) TestRunTTYWithPipe(c *testing.T) { 2491 errChan := make(chan error, 1) 2492 go func() { 2493 defer close(errChan) 2494 2495 cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true") 2496 if _, err := cmd.StdinPipe(); err != nil { 2497 errChan <- err 2498 return 2499 } 2500 2501 expected := "the input device is not a TTY" 2502 if runtime.GOOS == "windows" { 2503 expected += ". If you are using mintty, try prefixing the command with 'winpty'" 2504 } 2505 if out, _, err := runCommandWithOutput(cmd); err == nil { 2506 errChan <- fmt.Errorf("run should have failed") 2507 return 2508 } else if !strings.Contains(out, expected) { 2509 errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected) 2510 return 2511 } 2512 }() 2513 2514 select { 2515 case err := <-errChan: 2516 assert.NilError(c, err) 2517 case <-time.After(30 * time.Second): 2518 c.Fatal("container is running but should have failed") 2519 } 2520 } 2521 2522 func (s *DockerCLIRunSuite) TestRunNonLocalMacAddress(c *testing.T) { 2523 addr := "00:16:3E:08:00:50" 2524 args := []string{"run", "--mac-address", addr} 2525 expected := addr 2526 2527 if testEnv.DaemonInfo.OSType != "windows" { 2528 args = append(args, "busybox", "ifconfig") 2529 } else { 2530 args = append(args, testEnv.PlatformDefaults.BaseImage, "ipconfig", "/all") 2531 expected = strings.ReplaceAll(strings.ToUpper(addr), ":", "-") 2532 } 2533 2534 if out := cli.DockerCmd(c, args...).Combined(); !strings.Contains(out, expected) { 2535 c.Fatalf("Output should have contained %q: %s", expected, out) 2536 } 2537 } 2538 2539 func (s *DockerCLIRunSuite) TestRunNetHost(c *testing.T) { 2540 // Not applicable on Windows as uses Unix-specific capabilities 2541 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 2542 2543 hostNet, err := os.Readlink("/proc/1/ns/net") 2544 if err != nil { 2545 c.Fatal(err) 2546 } 2547 2548 out := cli.DockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net").Combined() 2549 out = strings.Trim(out, "\n") 2550 if hostNet != out { 2551 c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out) 2552 } 2553 2554 out = cli.DockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net").Combined() 2555 out = strings.Trim(out, "\n") 2556 if hostNet == out { 2557 c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out) 2558 } 2559 } 2560 2561 func (s *DockerCLIRunSuite) TestRunNetHostTwiceSameName(c *testing.T) { 2562 // TODO Windows. As Windows networking evolves and converges towards 2563 // CNM, this test may be possible to enable on Windows. 2564 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 2565 2566 cli.DockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") 2567 cli.DockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") 2568 } 2569 2570 func (s *DockerCLIRunSuite) TestRunNetContainerWhichHost(c *testing.T) { 2571 // Not applicable on Windows as uses Unix-specific capabilities 2572 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 2573 2574 hostNet, err := os.Readlink("/proc/1/ns/net") 2575 if err != nil { 2576 c.Fatal(err) 2577 } 2578 2579 cli.DockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top") 2580 2581 out := cli.DockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net").Combined() 2582 out = strings.Trim(out, "\n") 2583 if hostNet != out { 2584 c.Fatalf("Container should have host network namespace") 2585 } 2586 } 2587 2588 func (s *DockerCLIRunSuite) TestRunAllowPortRangeThroughPublish(c *testing.T) { 2589 // TODO Windows. This may be possible to enable in the future. However, 2590 // Windows does not currently support --expose, or populate the network 2591 // settings seen through inspect. 2592 testRequires(c, DaemonIsLinux) 2593 id := cli.DockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top").Stdout() 2594 id = strings.TrimSpace(id) 2595 portStr := inspectFieldJSON(c, id, "NetworkSettings.Ports") 2596 2597 var ports nat.PortMap 2598 err := json.Unmarshal([]byte(portStr), &ports) 2599 assert.NilError(c, err, "failed to unmarshal: %v", portStr) 2600 for port, binding := range ports { 2601 portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) 2602 if portnum < 3000 || portnum > 3003 { 2603 c.Fatalf("Port %d is out of range ", portnum) 2604 } 2605 if len(binding) == 0 || len(binding[0].HostPort) == 0 { 2606 c.Fatal("Port is not mapped for the port "+port, id) 2607 } 2608 } 2609 } 2610 2611 func (s *DockerCLIRunSuite) TestRunSetDefaultRestartPolicy(c *testing.T) { 2612 runSleepingContainer(c, "--name=testrunsetdefaultrestartpolicy") 2613 out := inspectField(c, "testrunsetdefaultrestartpolicy", "HostConfig.RestartPolicy.Name") 2614 if out != "no" { 2615 c.Fatalf("Set default restart policy failed") 2616 } 2617 } 2618 2619 func (s *DockerCLIRunSuite) TestRunRestartMaxRetries(c *testing.T) { 2620 id := cli.DockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false").Stdout() 2621 id = strings.TrimSpace(id) 2622 timeout := 10 * time.Second 2623 if testEnv.DaemonInfo.OSType == "windows" { 2624 timeout = 120 * time.Second 2625 } 2626 2627 if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil { 2628 c.Fatal(err) 2629 } 2630 2631 count := inspectField(c, id, "RestartCount") 2632 if count != "3" { 2633 c.Fatalf("Container was restarted %s times, expected %d", count, 3) 2634 } 2635 2636 MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") 2637 if MaximumRetryCount != "3" { 2638 c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3") 2639 } 2640 } 2641 2642 func (s *DockerCLIRunSuite) TestRunContainerWithWritableRootfs(c *testing.T) { 2643 cli.DockerCmd(c, "run", "--rm", "busybox", "touch", "/file") 2644 } 2645 2646 func (s *DockerCLIRunSuite) TestRunContainerWithReadonlyRootfs(c *testing.T) { 2647 // Not applicable on Windows which does not support --read-only 2648 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2649 2650 testPriv := true 2651 // don't test privileged mode subtest if user namespaces enabled 2652 if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" { 2653 testPriv = false 2654 } 2655 testReadOnlyFile(c, testPriv, "/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname") 2656 } 2657 2658 func (s *DockerCLIRunSuite) TestPermissionsPtsReadonlyRootfs(c *testing.T) { 2659 // Not applicable on Windows due to use of Unix specific functionality, plus 2660 // the use of --read-only which is not supported. 2661 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2662 2663 // Ensure we have not broken writing /dev/pts 2664 result := cli.DockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount") 2665 if result.ExitCode != 0 { 2666 c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.") 2667 } 2668 out := result.Combined() 2669 expected := "type devpts (rw," 2670 if !strings.Contains(out, expected) { 2671 c.Fatalf("expected output to contain %s but contains %s", expected, out) 2672 } 2673 } 2674 2675 func testReadOnlyFile(c *testing.T, testPriv bool, filenames ...string) { 2676 touch := "touch " + strings.Join(filenames, " ") 2677 out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "sh", "-c", touch) 2678 assert.ErrorContains(c, err, "") 2679 2680 for _, f := range filenames { 2681 expected := "touch: " + f + ": Read-only file system" 2682 assert.Assert(c, strings.Contains(out, expected)) 2683 } 2684 2685 if !testPriv { 2686 return 2687 } 2688 2689 out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "sh", "-c", touch) 2690 assert.ErrorContains(c, err, "") 2691 2692 for _, f := range filenames { 2693 expected := "touch: " + f + ": Read-only file system" 2694 assert.Assert(c, strings.Contains(out, expected)) 2695 } 2696 } 2697 2698 func (s *DockerCLIRunSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *testing.T) { 2699 // Not applicable on Windows which does not support --link 2700 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2701 2702 cli.DockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top") 2703 2704 out := cli.DockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts").Stdout() 2705 if !strings.Contains(out, "testlinked") { 2706 c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled") 2707 } 2708 } 2709 2710 func (s *DockerCLIRunSuite) TestRunContainerWithReadonlyRootfsWithDNSFlag(c *testing.T) { 2711 // Not applicable on Windows which does not support either --read-only or --dns. 2712 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2713 2714 out := cli.DockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf").Stdout() 2715 if !strings.Contains(out, "1.1.1.1") { 2716 c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used") 2717 } 2718 } 2719 2720 func (s *DockerCLIRunSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *testing.T) { 2721 // Not applicable on Windows which does not support --read-only 2722 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2723 2724 out := cli.DockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts").Stdout() 2725 if !strings.Contains(out, "testreadonly") { 2726 c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used") 2727 } 2728 } 2729 2730 func (s *DockerCLIRunSuite) TestRunVolumesFromRestartAfterRemoved(c *testing.T) { 2731 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2732 runSleepingContainer(c, "--name=voltest", "-v", prefix+"/foo") 2733 runSleepingContainer(c, "--name=restarter", "--volumes-from", "voltest") 2734 2735 // Remove the main volume container and restart the consuming container 2736 cli.DockerCmd(c, "rm", "-f", "voltest") 2737 2738 // This should not fail since the volumes-from were already applied 2739 cli.DockerCmd(c, "restart", "restarter") 2740 } 2741 2742 // run container with --rm should remove container if exit code != 0 2743 func (s *DockerCLIRunSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *testing.T) { 2744 name := "flowers" 2745 cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "ls", "/notexists")).Assert(c, icmd.Expected{ 2746 ExitCode: 1, 2747 }) 2748 2749 poll.WaitOn(c, containerRemoved(name)) 2750 } 2751 2752 func (s *DockerCLIRunSuite) TestRunContainerWithRmFlagCannotStartContainer(c *testing.T) { 2753 name := "sparkles" 2754 cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "commandNotFound")).Assert(c, icmd.Expected{ 2755 ExitCode: 127, 2756 }) 2757 2758 poll.WaitOn(c, containerRemoved(name)) 2759 } 2760 2761 func containerRemoved(name string) poll.Check { 2762 return func(l poll.LogT) poll.Result { 2763 err := cli.Docker(cli.Args("container", "inspect", "--format='{{.ID}}'", name)).Compare(icmd.Expected{ 2764 ExitCode: 1, 2765 Out: "", 2766 Err: "o such container", // (N|n)o such container 2767 }) 2768 if err != nil { 2769 return poll.Continue("waiting for container '%s' to be removed", name) 2770 } 2771 return poll.Success() 2772 } 2773 } 2774 2775 func (s *DockerCLIRunSuite) TestRunPIDHostWithChildIsKillable(c *testing.T) { 2776 // Not applicable on Windows as uses Unix specific functionality 2777 testRequires(c, DaemonIsLinux, NotUserNamespace) 2778 name := "ibuildthecloud" 2779 cli.DockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi") 2780 cli.WaitRun(c, name) 2781 2782 errchan := make(chan error, 1) 2783 go func() { 2784 if out, _, err := dockerCmdWithError("kill", name); err != nil { 2785 errchan <- fmt.Errorf("%v:\n%s", err, out) 2786 } 2787 close(errchan) 2788 }() 2789 select { 2790 case err := <-errchan: 2791 assert.NilError(c, err) 2792 case <-time.After(5 * time.Second): 2793 c.Fatal("Kill container timed out") 2794 } 2795 } 2796 2797 func (s *DockerCLIRunSuite) TestRunWithTooSmallMemoryLimit(c *testing.T) { 2798 // TODO Windows. This may be possible to enable once Windows supports memory limits on containers 2799 testRequires(c, DaemonIsLinux) 2800 // this memory limit is 1 byte less than the min (daemon.linuxMinMemory), which is 6MB (6291456 bytes) 2801 out, _, err := dockerCmdWithError("create", "-m", "6291455", "busybox") 2802 if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 6MB") { 2803 c.Fatalf("expected run to fail when using too low a memory limit: %q", out) 2804 } 2805 } 2806 2807 func (s *DockerCLIRunSuite) TestRunWriteToProcAsound(c *testing.T) { 2808 // Not applicable on Windows as uses Unix specific functionality 2809 testRequires(c, DaemonIsLinux) 2810 _, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version") 2811 if err == nil || code == 0 { 2812 c.Fatal("standard container should not be able to write to /proc/asound") 2813 } 2814 } 2815 2816 func (s *DockerCLIRunSuite) TestRunReadProcTimer(c *testing.T) { 2817 // Not applicable on Windows as uses Unix specific functionality 2818 testRequires(c, DaemonIsLinux) 2819 out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats") 2820 if code != 0 { 2821 return 2822 } 2823 if err != nil { 2824 c.Fatal(err) 2825 } 2826 if strings.Trim(out, "\n ") != "" { 2827 c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out) 2828 } 2829 } 2830 2831 func (s *DockerCLIRunSuite) TestRunReadProcLatency(c *testing.T) { 2832 // Not applicable on Windows as uses Unix specific functionality 2833 testRequires(c, DaemonIsLinux) 2834 // some kernels don't have this configured so skip the test if this file is not found 2835 // on the host running the tests. 2836 if _, err := os.Stat("/proc/latency_stats"); err != nil { 2837 c.Skip("kernel doesn't have latency_stats configured") 2838 return 2839 } 2840 out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats") 2841 if code != 0 { 2842 return 2843 } 2844 if err != nil { 2845 c.Fatal(err) 2846 } 2847 if strings.Trim(out, "\n ") != "" { 2848 c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out) 2849 } 2850 } 2851 2852 func (s *DockerCLIRunSuite) TestRunReadFilteredProc(c *testing.T) { 2853 // Not applicable on Windows as uses Unix specific functionality 2854 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 2855 2856 testReadPaths := []string{ 2857 "/proc/latency_stats", 2858 "/proc/timer_stats", 2859 "/proc/kcore", 2860 } 2861 for i, filePath := range testReadPaths { 2862 name := fmt.Sprintf("procsieve-%d", i) 2863 shellCmd := fmt.Sprintf("exec 3<%s", filePath) 2864 2865 out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) 2866 if exitCode != 0 { 2867 return 2868 } 2869 if err != nil { 2870 c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err) 2871 } 2872 } 2873 } 2874 2875 func (s *DockerCLIRunSuite) TestMountIntoProc(c *testing.T) { 2876 // Not applicable on Windows as uses Unix specific functionality 2877 testRequires(c, DaemonIsLinux) 2878 _, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true") 2879 if err == nil || code == 0 { 2880 c.Fatal("container should not be able to mount into /proc") 2881 } 2882 } 2883 2884 func (s *DockerCLIRunSuite) TestMountIntoSys(c *testing.T) { 2885 // Not applicable on Windows as uses Unix specific functionality 2886 testRequires(c, DaemonIsLinux) 2887 testRequires(c, NotUserNamespace) 2888 cli.DockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true") 2889 } 2890 2891 func (s *DockerCLIRunSuite) TestRunUnshareProc(c *testing.T) { 2892 // Not applicable on Windows as uses Unix specific functionality 2893 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 2894 2895 // In this test goroutines are used to run test cases in parallel to prevent the test from taking a long time to run. 2896 errChan := make(chan error) 2897 2898 go func() { 2899 name := "acidburn" 2900 out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:bookworm-slim", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount") 2901 if err == nil || 2902 !(strings.Contains(strings.ToLower(out), "permission denied") || 2903 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2904 errChan <- fmt.Errorf("unshare with --mount-proc should have failed with 'permission denied' or 'operation not permitted', got: %s, %v", out, err) 2905 } else { 2906 errChan <- nil 2907 } 2908 }() 2909 2910 go func() { 2911 name := "cereal" 2912 out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:bookworm-slim", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 2913 if err == nil || 2914 !(strings.Contains(strings.ToLower(out), "mount: cannot mount none") || 2915 strings.Contains(strings.ToLower(out), "permission denied") || 2916 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2917 errChan <- fmt.Errorf("unshare and mount of /proc should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err) 2918 } else { 2919 errChan <- nil 2920 } 2921 }() 2922 2923 /* Ensure still fails if running privileged with the default policy */ 2924 go func() { 2925 name := "crashoverride" 2926 out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "seccomp=unconfined", "--security-opt", "apparmor=docker-default", "--name", name, "debian:bookworm-slim", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 2927 if err == nil || 2928 !(strings.Contains(strings.ToLower(out), "mount: cannot mount none") || 2929 strings.Contains(strings.ToLower(out), "permission denied") || 2930 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2931 errChan <- fmt.Errorf("privileged unshare with apparmor should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err) 2932 } else { 2933 errChan <- nil 2934 } 2935 }() 2936 2937 var retErr error 2938 for i := 0; i < 3; i++ { 2939 err := <-errChan 2940 if retErr == nil && err != nil { 2941 retErr = err 2942 } 2943 } 2944 if retErr != nil { 2945 c.Fatal(retErr) 2946 } 2947 } 2948 2949 func (s *DockerCLIRunSuite) TestRunPublishPort(c *testing.T) { 2950 // TODO Windows: This may be possible once Windows moves to libnetwork and CNM 2951 testRequires(c, DaemonIsLinux) 2952 cli.DockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top") 2953 out := cli.DockerCmd(c, "port", "test").Stdout() 2954 out = strings.Trim(out, "\r\n") 2955 if out != "" { 2956 c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out) 2957 } 2958 } 2959 2960 // Issue #10184. 2961 func (s *DockerCLIRunSuite) TestDevicePermissions(c *testing.T) { 2962 // Not applicable on Windows as uses Unix specific functionality 2963 testRequires(c, DaemonIsLinux) 2964 const permissions = "crw-rw-rw-" 2965 result := cli.DockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse") 2966 if result.ExitCode != 0 { 2967 c.Fatalf("expected status 0, got %d", result.ExitCode) 2968 } 2969 out := result.Combined() 2970 if !strings.HasPrefix(out, permissions) { 2971 c.Fatalf("output should begin with %q, got %q", permissions, out) 2972 } 2973 } 2974 2975 func (s *DockerCLIRunSuite) TestRunCapAddCHOWN(c *testing.T) { 2976 // Not applicable on Windows as uses Unix specific functionality 2977 testRequires(c, DaemonIsLinux) 2978 out := cli.DockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok").Combined() 2979 2980 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 2981 c.Fatalf("expected output ok received %s", actual) 2982 } 2983 } 2984 2985 // https://github.com/docker/docker/pull/14498 2986 func (s *DockerCLIRunSuite) TestVolumeFromMixedRWOptions(c *testing.T) { 2987 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 2988 2989 cli.DockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true") 2990 2991 cli.DockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") 2992 cli.DockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") 2993 2994 if testEnv.DaemonInfo.OSType != "windows" { 2995 mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test") 2996 assert.NilError(c, err, "failed to inspect mount point") 2997 if mRO.RW { 2998 c.Fatalf("Expected RO volume was RW") 2999 } 3000 } 3001 3002 mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test") 3003 assert.NilError(c, err, "failed to inspect mount point") 3004 if !mRW.RW { 3005 c.Fatalf("Expected RW volume was RO") 3006 } 3007 } 3008 3009 func (s *DockerCLIRunSuite) TestRunWriteFilteredProc(c *testing.T) { 3010 // Not applicable on Windows as uses Unix specific functionality 3011 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 3012 3013 testWritePaths := []string{ 3014 /* modprobe and core_pattern should both be denied by generic 3015 * policy of denials for /proc/sys/kernel. These files have been 3016 * picked to be checked as they are particularly sensitive to writes */ 3017 "/proc/sys/kernel/modprobe", 3018 "/proc/sys/kernel/core_pattern", 3019 "/proc/sysrq-trigger", 3020 "/proc/kcore", 3021 } 3022 for i, filePath := range testWritePaths { 3023 name := fmt.Sprintf("writeprocsieve-%d", i) 3024 3025 shellCmd := fmt.Sprintf("exec 3>%s", filePath) 3026 out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) 3027 if code != 0 { 3028 return 3029 } 3030 if err != nil { 3031 c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err) 3032 } 3033 } 3034 } 3035 3036 func (s *DockerCLIRunSuite) TestRunNetworkFilesBindMount(c *testing.T) { 3037 // Not applicable on Windows as uses Unix specific functionality 3038 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 3039 3040 expected := "test123" 3041 3042 filename := createTmpFile(c, expected) 3043 defer os.Remove(filename) 3044 3045 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3046 if err := os.Chmod(filename, 0o646); err != nil { 3047 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3048 } 3049 3050 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3051 3052 for i := range nwfiles { 3053 actual := cli.DockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i]).Combined() 3054 if actual != expected { 3055 c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual) 3056 } 3057 } 3058 } 3059 3060 func (s *DockerCLIRunSuite) TestRunNetworkFilesBindMountRO(c *testing.T) { 3061 // Not applicable on Windows as uses Unix specific functionality 3062 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 3063 3064 filename := createTmpFile(c, "test123") 3065 defer os.Remove(filename) 3066 3067 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3068 if err := os.Chmod(filename, 0o646); err != nil { 3069 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3070 } 3071 3072 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3073 3074 for i := range nwfiles { 3075 _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i]) 3076 if err == nil || exitCode == 0 { 3077 c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode) 3078 } 3079 } 3080 } 3081 3082 func (s *DockerCLIRunSuite) TestRunNetworkFilesBindMountROFilesystem(c *testing.T) { 3083 // Not applicable on Windows as uses Unix specific functionality 3084 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, UserNamespaceROMount) 3085 3086 filename := createTmpFile(c, "test123") 3087 defer os.Remove(filename) 3088 3089 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3090 if err := os.Chmod(filename, 0o646); err != nil { 3091 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3092 } 3093 3094 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3095 3096 for i := range nwfiles { 3097 exitCode := cli.DockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i]).ExitCode 3098 if exitCode != 0 { 3099 c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode) 3100 } 3101 } 3102 3103 for i := range nwfiles { 3104 _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i]) 3105 if err == nil || exitCode == 0 { 3106 c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode) 3107 } 3108 } 3109 } 3110 3111 func (s *DockerCLIRunSuite) TestPtraceContainerProcsFromHost(c *testing.T) { 3112 // Not applicable on Windows as uses Unix specific functionality 3113 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 3114 3115 id := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() 3116 id = strings.TrimSpace(id) 3117 cli.WaitRun(c, id) 3118 pid1 := inspectField(c, id, "State.Pid") 3119 3120 _, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) 3121 if err != nil { 3122 c.Fatal(err) 3123 } 3124 } 3125 3126 func (s *DockerCLIRunSuite) TestAppArmorDeniesPtrace(c *testing.T) { 3127 // Not applicable on Windows as uses Unix specific functionality 3128 testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux) 3129 3130 // Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace 3131 // itself, but pid>1 should not be able to trace pid1. 3132 _, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "sh -c readlink /proc/1/ns/net") 3133 if exitCode == 0 { 3134 c.Fatal("ptrace was not successfully restricted by AppArmor") 3135 } 3136 } 3137 3138 func (s *DockerCLIRunSuite) TestAppArmorTraceSelf(c *testing.T) { 3139 // Not applicable on Windows as uses Unix specific functionality 3140 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, Apparmor) 3141 3142 _, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net") 3143 if exitCode != 0 { 3144 c.Fatal("ptrace of self failed.") 3145 } 3146 } 3147 3148 func (s *DockerCLIRunSuite) TestAppArmorDeniesChmodProc(c *testing.T) { 3149 // Not applicable on Windows as uses Unix specific functionality 3150 testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux, NotUserNamespace) 3151 _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo") 3152 if exitCode == 0 { 3153 // If our test failed, attempt to repair the host system... 3154 _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo") 3155 if exitCode == 0 { 3156 c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.") 3157 } 3158 } 3159 } 3160 3161 func (s *DockerCLIRunSuite) TestRunCapAddSYSTIME(c *testing.T) { 3162 // Not applicable on Windows as uses Unix specific functionality 3163 testRequires(c, DaemonIsLinux) 3164 3165 cli.DockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$") 3166 } 3167 3168 // run create container failed should clean up the container 3169 func (s *DockerCLIRunSuite) TestRunCreateContainerFailedCleanUp(c *testing.T) { 3170 // TODO Windows. This may be possible to enable once link is supported 3171 testRequires(c, DaemonIsLinux) 3172 name := "unique_name" 3173 _, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox") 3174 assert.Assert(c, err != nil, "Expected docker run to fail!") 3175 3176 containerID, err := inspectFieldWithError(name, "Id") 3177 assert.Assert(c, err != nil, "Expected not to have this container: %s!", containerID) 3178 assert.Equal(c, containerID, "", fmt.Sprintf("Expected not to have this container: %s!", containerID)) 3179 } 3180 3181 func (s *DockerCLIRunSuite) TestRunNamedVolume(c *testing.T) { 3182 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3183 testRequires(c, DaemonIsLinux) 3184 cli.DockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar") 3185 3186 out := cli.DockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar").Combined() 3187 assert.Equal(c, strings.TrimSpace(out), "hello") 3188 3189 out = cli.DockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar").Combined() 3190 assert.Equal(c, strings.TrimSpace(out), "hello") 3191 } 3192 3193 func (s *DockerCLIRunSuite) TestRunWithUlimits(c *testing.T) { 3194 // Not applicable on Windows as uses Unix specific functionality 3195 testRequires(c, DaemonIsLinux) 3196 3197 out := cli.DockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n").Combined() 3198 ul := strings.TrimSpace(out) 3199 if ul != "42" { 3200 c.Fatalf("expected `ulimit -n` to be 42, got %s", ul) 3201 } 3202 } 3203 3204 func (s *DockerCLIRunSuite) TestRunContainerWithCgroupParent(c *testing.T) { 3205 // Not applicable on Windows as uses Unix specific functionality 3206 testRequires(c, DaemonIsLinux) 3207 3208 // cgroup-parent relative path 3209 testRunContainerWithCgroupParent(c, "test", "cgroup-test") 3210 3211 // cgroup-parent absolute path 3212 testRunContainerWithCgroupParent(c, "/cgroup-parent/test", "cgroup-test-absolute") 3213 } 3214 3215 func testRunContainerWithCgroupParent(c *testing.T, cgroupParent, name string) { 3216 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3217 if err != nil { 3218 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err) 3219 } 3220 cgroupPaths := ParseCgroupPaths(out) 3221 if len(cgroupPaths) == 0 { 3222 c.Fatalf("unexpected output - %q", out) 3223 } 3224 id := getIDByName(c, name) 3225 expectedCgroup := path.Join(cgroupParent, id) 3226 found := false 3227 for _, p := range cgroupPaths { 3228 if strings.HasSuffix(p, expectedCgroup) { 3229 found = true 3230 break 3231 } 3232 } 3233 if !found { 3234 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3235 } 3236 } 3237 3238 // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /. 3239 func (s *DockerCLIRunSuite) TestRunInvalidCgroupParent(c *testing.T) { 3240 // Not applicable on Windows as uses Unix specific functionality 3241 testRequires(c, DaemonIsLinux) 3242 3243 testRunInvalidCgroupParent(c, "../../../../../../../../SHOULD_NOT_EXIST", "SHOULD_NOT_EXIST", "cgroup-invalid-test") 3244 3245 testRunInvalidCgroupParent(c, "/../../../../../../../../SHOULD_NOT_EXIST", "/SHOULD_NOT_EXIST", "cgroup-absolute-invalid-test") 3246 } 3247 3248 func testRunInvalidCgroupParent(c *testing.T, cgroupParent, cleanCgroupParent, name string) { 3249 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3250 if err != nil { 3251 // XXX: This may include a daemon crash. 3252 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err) 3253 } 3254 3255 // We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue. 3256 if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) { 3257 c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!") 3258 } 3259 3260 cgroupPaths := ParseCgroupPaths(out) 3261 if len(cgroupPaths) == 0 { 3262 c.Fatalf("unexpected output - %q", out) 3263 } 3264 id := getIDByName(c, name) 3265 expectedCgroup := path.Join(cleanCgroupParent, id) 3266 found := false 3267 for _, p := range cgroupPaths { 3268 if strings.HasSuffix(p, expectedCgroup) { 3269 found = true 3270 break 3271 } 3272 } 3273 if !found { 3274 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3275 } 3276 } 3277 3278 func (s *DockerCLIRunSuite) TestRunContainerWithCgroupMountRO(c *testing.T) { 3279 // Not applicable on Windows as uses Unix specific functionality 3280 // --read-only + userns has remount issues 3281 testRequires(c, DaemonIsLinux, NotUserNamespace) 3282 3283 filename := "/sys/fs/cgroup/devices/test123" 3284 out, _, err := dockerCmdWithError("run", "busybox", "touch", filename) 3285 if err == nil { 3286 c.Fatal("expected cgroup mount point to be read-only, touch file should fail") 3287 } 3288 expected := "Read-only file system" 3289 if !strings.Contains(out, expected) { 3290 c.Fatalf("expected output from failure to contain %s but contains %s", expected, out) 3291 } 3292 } 3293 3294 func (s *DockerCLIRunSuite) TestRunContainerNetworkModeToSelf(c *testing.T) { 3295 // Not applicable on Windows which does not support --net=container 3296 testRequires(c, DaemonIsLinux) 3297 out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true") 3298 if err == nil || !strings.Contains(out, "cannot join own network") { 3299 c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out) 3300 } 3301 } 3302 3303 func (s *DockerCLIRunSuite) TestRunContainerNetModeWithDNSMacHosts(c *testing.T) { 3304 // Not applicable on Windows which does not support --net=container 3305 testRequires(c, DaemonIsLinux) 3306 out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top") 3307 if err != nil { 3308 c.Fatalf("failed to run container: %v, output: %q", err, out) 3309 } 3310 3311 out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox") 3312 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error()) { 3313 c.Fatalf("run --net=container with --dns should error out") 3314 } 3315 3316 out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox") 3317 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error()) { 3318 c.Fatalf("run --net=container with --add-host should error out") 3319 } 3320 } 3321 3322 func (s *DockerCLIRunSuite) TestRunContainerNetModeWithExposePort(c *testing.T) { 3323 // Not applicable on Windows which does not support --net=container 3324 testRequires(c, DaemonIsLinux) 3325 cli.DockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") 3326 3327 out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox") 3328 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { 3329 c.Fatalf("run --net=container with -p should error out") 3330 } 3331 3332 out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox") 3333 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { 3334 c.Fatalf("run --net=container with -P should error out") 3335 } 3336 3337 out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox") 3338 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error()) { 3339 c.Fatalf("run --net=container with --expose should error out") 3340 } 3341 } 3342 3343 func (s *DockerCLIRunSuite) TestRunLinkToContainerNetMode(c *testing.T) { 3344 // Not applicable on Windows which does not support --net=container or --link 3345 testRequires(c, DaemonIsLinux) 3346 cli.DockerCmd(c, "run", "--name", "test", "-d", "busybox", "top") 3347 cli.DockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top") 3348 cli.DockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top") 3349 cli.DockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top") 3350 cli.DockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top") 3351 } 3352 3353 func (s *DockerCLIRunSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *testing.T) { 3354 // TODO Windows: This may be possible to convert. 3355 testRequires(c, DaemonIsLinux) 3356 out := cli.DockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up").Combined() 3357 3358 var ( 3359 count = 0 3360 parts = strings.Split(out, "\n") 3361 ) 3362 3363 for _, l := range parts { 3364 if l != "" { 3365 count++ 3366 } 3367 } 3368 3369 if count != 1 { 3370 c.Fatalf("Wrong interface count in container %d", count) 3371 } 3372 3373 if !strings.HasPrefix(out, "1: lo") { 3374 c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out) 3375 } 3376 } 3377 3378 // Issue #4681 3379 func (s *DockerCLIRunSuite) TestRunLoopbackWhenNetworkDisabled(c *testing.T) { 3380 if testEnv.DaemonInfo.OSType == "windows" { 3381 cli.DockerCmd(c, "run", "--net=none", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") 3382 } else { 3383 cli.DockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1") 3384 } 3385 } 3386 3387 func (s *DockerCLIRunSuite) TestRunModeNetContainerHostname(c *testing.T) { 3388 // Windows does not support --net=container 3389 testRequires(c, DaemonIsLinux) 3390 3391 cli.DockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top") 3392 out := cli.DockerCmd(c, "exec", "parent", "cat", "/etc/hostname").Combined() 3393 out1 := cli.DockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname").Combined() 3394 3395 if out1 != out { 3396 c.Fatal("containers with shared net namespace should have same hostname") 3397 } 3398 } 3399 3400 func (s *DockerCLIRunSuite) TestRunNetworkNotInitializedNoneMode(c *testing.T) { 3401 // TODO Windows: Network settings are not currently propagated. This may 3402 // be resolved in the future with the move to libnetwork and CNM. 3403 testRequires(c, DaemonIsLinux) 3404 id := cli.DockerCmd(c, "run", "-d", "--net=none", "busybox", "top").Stdout() 3405 id = strings.TrimSpace(id) 3406 res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress") 3407 if res != "" { 3408 c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res) 3409 } 3410 } 3411 3412 func (s *DockerCLIRunSuite) TestTwoContainersInNetHost(c *testing.T) { 3413 // Not applicable as Windows does not support --net=host 3414 testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace) 3415 cli.DockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") 3416 cli.DockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top") 3417 cli.DockerCmd(c, "stop", "first") 3418 cli.DockerCmd(c, "stop", "second") 3419 } 3420 3421 func (s *DockerCLIRunSuite) TestContainersInUserDefinedNetwork(c *testing.T) { 3422 testRequires(c, DaemonIsLinux, NotUserNamespace) 3423 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork") 3424 cli.DockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top") 3425 cli.WaitRun(c, "first") 3426 cli.DockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first") 3427 } 3428 3429 func (s *DockerCLIRunSuite) TestContainersInMultipleNetworks(c *testing.T) { 3430 testRequires(c, DaemonIsLinux, NotUserNamespace) 3431 // Create 2 networks using bridge driver 3432 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3433 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3434 // Run and connect containers to testnetwork1 3435 cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3436 cli.WaitRun(c, "first") 3437 cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3438 cli.WaitRun(c, "second") 3439 // Check connectivity between containers in testnetwork2 3440 cli.DockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3441 // Connect containers to testnetwork2 3442 cli.DockerCmd(c, "network", "connect", "testnetwork2", "first") 3443 cli.DockerCmd(c, "network", "connect", "testnetwork2", "second") 3444 // Check connectivity between containers 3445 cli.DockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3446 } 3447 3448 func (s *DockerCLIRunSuite) TestContainersNetworkIsolation(c *testing.T) { 3449 testRequires(c, DaemonIsLinux, NotUserNamespace) 3450 // Create 2 networks using bridge driver 3451 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3452 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3453 // Run 1 container in testnetwork1 and another in testnetwork2 3454 cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3455 cli.WaitRun(c, "first") 3456 cli.DockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top") 3457 cli.WaitRun(c, "second") 3458 3459 // Check Isolation between containers : ping must fail 3460 _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3461 assert.ErrorContains(c, err, "") 3462 // Connect first container to testnetwork2 3463 cli.DockerCmd(c, "network", "connect", "testnetwork2", "first") 3464 // ping must succeed now 3465 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3466 assert.NilError(c, err) 3467 3468 // Disconnect first container from testnetwork2 3469 cli.DockerCmd(c, "network", "disconnect", "testnetwork2", "first") 3470 // ping must fail again 3471 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3472 assert.ErrorContains(c, err, "") 3473 } 3474 3475 func (s *DockerCLIRunSuite) TestNetworkRmWithActiveContainers(c *testing.T) { 3476 testRequires(c, DaemonIsLinux, NotUserNamespace) 3477 // Create 2 networks using bridge driver 3478 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3479 // Run and connect containers to testnetwork1 3480 cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3481 cli.WaitRun(c, "first") 3482 cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3483 cli.WaitRun(c, "second") 3484 // Network delete with active containers must fail 3485 _, _, err := dockerCmdWithError("network", "rm", "testnetwork1") 3486 assert.ErrorContains(c, err, "") 3487 3488 cli.DockerCmd(c, "stop", "first") 3489 _, _, err = dockerCmdWithError("network", "rm", "testnetwork1") 3490 assert.ErrorContains(c, err, "") 3491 } 3492 3493 func (s *DockerCLIRunSuite) TestContainerRestartInMultipleNetworks(c *testing.T) { 3494 testRequires(c, DaemonIsLinux, NotUserNamespace) 3495 // Create 2 networks using bridge driver 3496 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3497 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3498 3499 // Run and connect containers to testnetwork1 3500 cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3501 cli.WaitRun(c, "first") 3502 cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3503 cli.WaitRun(c, "second") 3504 // Check connectivity between containers in testnetwork2 3505 cli.DockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3506 // Connect containers to testnetwork2 3507 cli.DockerCmd(c, "network", "connect", "testnetwork2", "first") 3508 cli.DockerCmd(c, "network", "connect", "testnetwork2", "second") 3509 // Check connectivity between containers 3510 cli.DockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3511 3512 // Stop second container and test ping failures on both networks 3513 cli.DockerCmd(c, "stop", "second") 3514 _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1") 3515 assert.ErrorContains(c, err, "") 3516 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2") 3517 assert.ErrorContains(c, err, "") 3518 3519 // Start second container and connectivity must be restored on both networks 3520 cli.DockerCmd(c, "start", "second") 3521 cli.DockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3522 cli.DockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3523 } 3524 3525 func (s *DockerCLIRunSuite) TestContainerWithConflictingHostNetworks(c *testing.T) { 3526 testRequires(c, DaemonIsLinux, NotUserNamespace) 3527 // Run a container with --net=host 3528 cli.DockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") 3529 cli.WaitRun(c, "first") 3530 3531 // Create a network using bridge driver 3532 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3533 3534 // Connecting to the user defined network must fail 3535 _, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") 3536 assert.ErrorContains(c, err, "") 3537 } 3538 3539 func (s *DockerCLIRunSuite) TestContainerWithConflictingSharedNetwork(c *testing.T) { 3540 testRequires(c, DaemonIsLinux) 3541 cli.DockerCmd(c, "run", "-d", "--name=first", "busybox", "top") 3542 cli.WaitRun(c, "first") 3543 // Run second container in first container's network namespace 3544 cli.DockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top") 3545 cli.WaitRun(c, "second") 3546 3547 // Create a network using bridge driver 3548 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3549 3550 // Connecting to the user defined network must fail 3551 out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second") 3552 assert.ErrorContains(c, err, "") 3553 assert.Assert(c, strings.Contains(out, runconfig.ErrConflictSharedNetwork.Error())) 3554 } 3555 3556 func (s *DockerCLIRunSuite) TestContainerWithConflictingNoneNetwork(c *testing.T) { 3557 testRequires(c, DaemonIsLinux) 3558 cli.DockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top") 3559 cli.WaitRun(c, "first") 3560 3561 // Create a network using bridge driver 3562 cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3563 3564 // Connecting to the user defined network must fail 3565 out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") 3566 assert.ErrorContains(c, err, "") 3567 assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNoNetwork.Error())) 3568 // create a container connected to testnetwork1 3569 cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3570 cli.WaitRun(c, "second") 3571 3572 // Connect second container to none network. it must fail as well 3573 _, _, err = dockerCmdWithError("network", "connect", "none", "second") 3574 assert.ErrorContains(c, err, "") 3575 } 3576 3577 // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited 3578 func (s *DockerCLIRunSuite) TestRunStdinBlockedAfterContainerExit(c *testing.T) { 3579 cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true") 3580 in, err := cmd.StdinPipe() 3581 assert.NilError(c, err) 3582 defer in.Close() 3583 stdout := bytes.NewBuffer(nil) 3584 cmd.Stdout = stdout 3585 cmd.Stderr = stdout 3586 assert.Assert(c, cmd.Start() == nil) 3587 3588 waitChan := make(chan error, 1) 3589 go func() { 3590 waitChan <- cmd.Wait() 3591 }() 3592 3593 select { 3594 case err := <-waitChan: 3595 assert.Assert(c, err == nil, stdout.String()) 3596 case <-time.After(30 * time.Second): 3597 c.Fatal("timeout waiting for command to exit") 3598 } 3599 } 3600 3601 func (s *DockerCLIRunSuite) TestRunWrongCpusetCpusFlagValue(c *testing.T) { 3602 // TODO Windows: This needs validation (error out) in the daemon. 3603 testRequires(c, DaemonIsLinux) 3604 out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true") 3605 assert.ErrorContains(c, err, "") 3606 expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n" 3607 if !(strings.Contains(out, expected) || exitCode == 125) { 3608 c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) 3609 } 3610 } 3611 3612 func (s *DockerCLIRunSuite) TestRunWrongCpusetMemsFlagValue(c *testing.T) { 3613 // TODO Windows: This needs validation (error out) in the daemon. 3614 testRequires(c, DaemonIsLinux) 3615 out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true") 3616 assert.ErrorContains(c, err, "") 3617 expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n" 3618 if !(strings.Contains(out, expected) || exitCode == 125) { 3619 c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) 3620 } 3621 } 3622 3623 // TestRunNonExecutableCmd checks that 'docker run busybox foo' exits with error code 127' 3624 func (s *DockerCLIRunSuite) TestRunNonExecutableCmd(c *testing.T) { 3625 name := "testNonExecutableCmd" 3626 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "foo").Assert(c, icmd.Expected{ 3627 ExitCode: 127, 3628 Error: "exit status 127", 3629 }) 3630 } 3631 3632 // TestRunNonExistingCmd checks that 'docker run busybox /bin/foo' exits with code 127. 3633 func (s *DockerCLIRunSuite) TestRunNonExistingCmd(c *testing.T) { 3634 name := "testNonExistingCmd" 3635 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/bin/foo").Assert(c, icmd.Expected{ 3636 ExitCode: 127, 3637 Error: "exit status 127", 3638 }) 3639 } 3640 3641 // TestCmdCannotBeInvoked checks that 'docker run busybox /etc' exits with 126, or 3642 // 127 on Windows. The difference is that in Windows, the container must be started 3643 // as that's when the check is made (and yes, by its design...) 3644 func (s *DockerCLIRunSuite) TestCmdCannotBeInvoked(c *testing.T) { 3645 expected := 126 3646 if testEnv.DaemonInfo.OSType == "windows" { 3647 expected = 127 3648 } 3649 name := "testCmdCannotBeInvoked" 3650 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/etc").Assert(c, icmd.Expected{ 3651 ExitCode: expected, 3652 Error: fmt.Sprintf("exit status %d", expected), 3653 }) 3654 } 3655 3656 // TestRunNonExistingImage checks that 'docker run foo' exits with error msg 125 and contains 'Unable to find image' 3657 // FIXME(vdemeester) should be a unit test 3658 func (s *DockerCLIRunSuite) TestRunNonExistingImage(c *testing.T) { 3659 icmd.RunCommand(dockerBinary, "run", "foo").Assert(c, icmd.Expected{ 3660 ExitCode: 125, 3661 Err: "Unable to find image", 3662 }) 3663 } 3664 3665 // TestDockerFails checks that 'docker run -foo busybox' exits with 125 to signal docker run failed 3666 // FIXME(vdemeester) should be a unit test 3667 func (s *DockerCLIRunSuite) TestDockerFails(c *testing.T) { 3668 icmd.RunCommand(dockerBinary, "run", "-foo", "busybox").Assert(c, icmd.Expected{ 3669 ExitCode: 125, 3670 Error: "exit status 125", 3671 }) 3672 } 3673 3674 // TestRunInvalidReference invokes docker run with a bad reference. 3675 func (s *DockerCLIRunSuite) TestRunInvalidReference(c *testing.T) { 3676 out, exit, _ := dockerCmdWithError("run", "busybox@foo") 3677 if exit == 0 { 3678 c.Fatalf("expected non-zero exist code; received %d", exit) 3679 } 3680 3681 if !strings.Contains(out, "invalid reference format") { 3682 c.Fatalf(`Expected "invalid reference format" in output; got: %s`, out) 3683 } 3684 } 3685 3686 // Test fix for issue #17854 3687 func (s *DockerCLIRunSuite) TestRunInitLayerPathOwnership(c *testing.T) { 3688 // Not applicable on Windows as it does not support Linux uid/gid ownership 3689 testRequires(c, DaemonIsLinux) 3690 name := "testetcfileownership" 3691 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 3692 RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd 3693 RUN echo 'dockerio:x:1001:' >> /etc/group 3694 RUN chown dockerio:dockerio /etc`)) 3695 3696 // Test that dockerio ownership of /etc is retained at runtime 3697 out := cli.DockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc").Combined() 3698 out = strings.TrimSpace(out) 3699 if out != "dockerio:dockerio" { 3700 c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out) 3701 } 3702 } 3703 3704 func (s *DockerCLIRunSuite) TestRunWithOomScoreAdj(c *testing.T) { 3705 testRequires(c, DaemonIsLinux) 3706 3707 const expected = "642" 3708 out := cli.DockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj").Combined() 3709 oomScoreAdj := strings.TrimSpace(out) 3710 if oomScoreAdj != expected { 3711 c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj) 3712 } 3713 } 3714 3715 func (s *DockerCLIRunSuite) TestRunWithOomScoreAdjInvalidRange(c *testing.T) { 3716 testRequires(c, DaemonIsLinux) 3717 3718 out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true") 3719 assert.ErrorContains(c, err, "") 3720 expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]." 3721 if !strings.Contains(out, expected) { 3722 c.Fatalf("Expected output to contain %q, got %q instead", expected, out) 3723 } 3724 out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true") 3725 assert.ErrorContains(c, err, "") 3726 expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]." 3727 if !strings.Contains(out, expected) { 3728 c.Fatalf("Expected output to contain %q, got %q instead", expected, out) 3729 } 3730 } 3731 3732 func (s *DockerCLIRunSuite) TestRunNamedVolumesMountedAsShared(c *testing.T) { 3733 testRequires(c, DaemonIsLinux, NotUserNamespace) 3734 out, exitCode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile") 3735 assert.Assert(c, exitCode != 0) 3736 assert.Assert(c, strings.Contains(out, "invalid mount config")) 3737 } 3738 3739 func (s *DockerCLIRunSuite) TestRunNamedVolumeCopyImageData(c *testing.T) { 3740 testRequires(c, DaemonIsLinux) 3741 3742 testImg := "testvolumecopy" 3743 buildImageSuccessfully(c, testImg, build.WithDockerfile(` 3744 FROM busybox 3745 RUN mkdir -p /foo && echo hello > /foo/hello 3746 `)) 3747 3748 cli.DockerCmd(c, "run", "-v", "foo:/foo", testImg) 3749 out := cli.DockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello").Stdout() 3750 assert.Equal(c, strings.TrimSpace(out), "hello") 3751 } 3752 3753 func (s *DockerCLIRunSuite) TestRunNamedVolumeNotRemoved(c *testing.T) { 3754 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3755 3756 cli.DockerCmd(c, "volume", "create", "test") 3757 3758 cli.DockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 3759 cli.DockerCmd(c, "volume", "inspect", "test") 3760 out := cli.DockerCmd(c, "volume", "ls", "-q").Combined() 3761 assert.Assert(c, strings.Contains(out, "test")) 3762 3763 cli.DockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 3764 cli.DockerCmd(c, "rm", "-fv", "test") 3765 cli.DockerCmd(c, "volume", "inspect", "test") 3766 out = cli.DockerCmd(c, "volume", "ls", "-q").Combined() 3767 assert.Assert(c, strings.Contains(out, "test")) 3768 } 3769 3770 func (s *DockerCLIRunSuite) TestRunNamedVolumesFromNotRemoved(c *testing.T) { 3771 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3772 3773 cli.DockerCmd(c, "volume", "create", "test") 3774 cid := cli.DockerCmd(c, "run", "-d", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true").Stdout() 3775 cli.DockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true") 3776 3777 apiClient, err := client.NewClientWithOpts(client.FromEnv) 3778 assert.NilError(c, err) 3779 defer apiClient.Close() 3780 3781 container, err := apiClient.ContainerInspect(testutil.GetContext(c), strings.TrimSpace(cid)) 3782 assert.NilError(c, err) 3783 var vname string 3784 for _, v := range container.Mounts { 3785 if v.Name != "test" { 3786 vname = v.Name 3787 } 3788 } 3789 assert.Assert(c, vname != "") 3790 3791 // Remove the parent so there are not other references to the volumes 3792 cli.DockerCmd(c, "rm", "-f", "parent") 3793 // now remove the child and ensure the named volume (and only the named volume) still exists 3794 cli.DockerCmd(c, "rm", "-fv", "child") 3795 cli.DockerCmd(c, "volume", "inspect", "test") 3796 out := cli.DockerCmd(c, "volume", "ls", "-q").Combined() 3797 assert.Assert(c, strings.Contains(out, "test")) 3798 assert.Assert(c, !strings.Contains(strings.TrimSpace(out), vname)) 3799 } 3800 3801 func (s *DockerCLIRunSuite) TestRunAttachFailedNoLeak(c *testing.T) { 3802 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 3803 ctx := testutil.GetContext(c) 3804 d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvVars("OTEL_SDK_DISABLED=1")) 3805 defer func() { 3806 if c.Failed() { 3807 d.Daemon.DumpStackAndQuit() 3808 } else { 3809 d.Stop(c) 3810 } 3811 d.Cleanup(c) 3812 }() 3813 d.StartWithBusybox(ctx, c) 3814 3815 // Run a dummy container to ensure all goroutines are up and running before we get a count 3816 _, err := d.Cmd("run", "--rm", "busybox", "true") 3817 assert.NilError(c, err) 3818 3819 client := d.NewClientT(c) 3820 3821 nroutines := waitForStableGourtineCount(ctx, c, client) 3822 3823 out, err := d.Cmd(append([]string{"run", "-d", "--name=test", "-p", "8000:8000", "busybox"}, sleepCommandForDaemonPlatform()...)...) 3824 assert.NilError(c, err, out) 3825 3826 // Wait until container is fully up and running 3827 assert.NilError(c, d.WaitRun("test")) 3828 3829 out, err = d.Cmd("run", "--name=fail", "-p", "8000:8000", "busybox", "true") 3830 3831 // We will need the following `inspect` to diagnose the issue if test fails (#21247) 3832 out1, err1 := d.Cmd("inspect", "--format", "{{json .State}}", "test") 3833 out2, err2 := d.Cmd("inspect", "--format", "{{json .State}}", "fail") 3834 assert.Assert(c, err != nil, "Command should have failed but succeeded with: %s\nContainer 'test' [%+v]: %s\nContainer 'fail' [%+v]: %s", out, err1, out1, err2, out2) 3835 3836 // check for windows error as well 3837 // TODO Windows Post TP5. Fix the error message string 3838 outLowerCase := strings.ToLower(out) 3839 assert.Assert(c, strings.Contains(outLowerCase, "port is already allocated") || 3840 strings.Contains(outLowerCase, "were not connected because a duplicate name exists") || 3841 strings.Contains(outLowerCase, "the specified port already exists") || 3842 strings.Contains(outLowerCase, "hns failed with error : failed to create endpoint") || 3843 strings.Contains(outLowerCase, "hns failed with error : the object already exists"), fmt.Sprintf("Output: %s", out)) 3844 3845 out, err = d.Cmd("rm", "-f", "test") 3846 assert.NilError(c, err, out) 3847 3848 // NGoroutines is not updated right away, so we need to wait before failing 3849 waitForGoroutines(ctx, c, client, nroutines) 3850 } 3851 3852 // Test for one character directory name case (#20122) 3853 func (s *DockerCLIRunSuite) TestRunVolumeWithOneCharacter(c *testing.T) { 3854 testRequires(c, DaemonIsLinux) 3855 3856 out := cli.DockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo").Combined() 3857 assert.Equal(c, strings.TrimSpace(out), "/foo") 3858 } 3859 3860 func (s *DockerCLIRunSuite) TestRunVolumeCopyFlag(c *testing.T) { 3861 testRequires(c, DaemonIsLinux) // Windows does not support copying data from image to the volume 3862 buildImageSuccessfully(c, "volumecopy", build.WithDockerfile(`FROM busybox 3863 RUN mkdir /foo && echo hello > /foo/bar 3864 CMD cat /foo/bar`)) 3865 cli.DockerCmd(c, "volume", "create", "test") 3866 3867 // test with the nocopy flag 3868 out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy") 3869 assert.ErrorContains(c, err, "", out) 3870 // test default behavior which is to copy for non-binds 3871 out = cli.DockerCmd(c, "run", "-v", "test:/foo", "volumecopy").Combined() 3872 assert.Equal(c, strings.TrimSpace(out), "hello") 3873 // error out when the volume is already populated 3874 out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy") 3875 assert.ErrorContains(c, err, "", out) 3876 // do not error out when copy isn't explicitly set even though it's already populated 3877 out = cli.DockerCmd(c, "run", "-v", "test:/foo", "volumecopy").Combined() 3878 assert.Equal(c, strings.TrimSpace(out), "hello") 3879 3880 // do not allow copy modes on volumes-from 3881 cli.DockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true") 3882 out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true") 3883 assert.ErrorContains(c, err, "", out) 3884 out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true") 3885 assert.ErrorContains(c, err, "", out) 3886 3887 // do not allow copy modes on binds 3888 out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true") 3889 assert.ErrorContains(c, err, "", out) 3890 out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true") 3891 assert.ErrorContains(c, err, "", out) 3892 } 3893 3894 // Test case for #21976 3895 func (s *DockerCLIRunSuite) TestRunDNSInHostMode(c *testing.T) { 3896 testRequires(c, DaemonIsLinux, NotUserNamespace) 3897 3898 expectedOutput := "nameserver 127.0.0.1" 3899 expectedWarning := "Localhost DNS setting" 3900 cli.DockerCmd(c, "run", "--dns=127.0.0.1", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 3901 Out: expectedOutput, 3902 Err: expectedWarning, 3903 }) 3904 3905 expectedOutput = "nameserver 1.2.3.4" 3906 cli.DockerCmd(c, "run", "--dns=1.2.3.4", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 3907 Out: expectedOutput, 3908 }) 3909 3910 expectedOutput = "search example.com" 3911 cli.DockerCmd(c, "run", "--dns-search=example.com", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 3912 Out: expectedOutput, 3913 }) 3914 3915 expectedOutput = "options timeout:3" 3916 cli.DockerCmd(c, "run", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 3917 Out: expectedOutput, 3918 }) 3919 3920 expectedOutput1 := "nameserver 1.2.3.4" 3921 expectedOutput2 := "search example.com" 3922 expectedOutput3 := "options timeout:3" 3923 out := cli.DockerCmd(c, "run", "--dns=1.2.3.4", "--dns-search=example.com", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf").Combined() 3924 assert.Assert(c, strings.Contains(out, expectedOutput1), "Expected '%s', but got %q", expectedOutput1, out) 3925 assert.Assert(c, strings.Contains(out, expectedOutput2), "Expected '%s', but got %q", expectedOutput2, out) 3926 assert.Assert(c, strings.Contains(out, expectedOutput3), "Expected '%s', but got %q", expectedOutput3, out) 3927 } 3928 3929 // Test case for #21976 3930 func (s *DockerCLIRunSuite) TestRunAddHostInHostMode(c *testing.T) { 3931 testRequires(c, DaemonIsLinux, NotUserNamespace) 3932 3933 expectedOutput := "1.2.3.4\textra" 3934 out := cli.DockerCmd(c, "run", "--add-host=extra:1.2.3.4", "--net=host", "busybox", "cat", "/etc/hosts").Combined() 3935 assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out) 3936 } 3937 3938 func (s *DockerCLIRunSuite) TestRunRmAndWait(c *testing.T) { 3939 cli.DockerCmd(c, "run", "--name=test", "--rm", "-d", "busybox", "sh", "-c", "sleep 3;exit 2") 3940 3941 out, code, err := dockerCmdWithError("wait", "test") 3942 assert.Assert(c, err == nil, "out: %s; exit code: %d", out, code) 3943 assert.Equal(c, out, "2\n", "exit code: %d", code) 3944 assert.Equal(c, code, 0) 3945 } 3946 3947 // Test that auto-remove is performed by the daemon (API 1.25 and above) 3948 func (s *DockerCLIRunSuite) TestRunRm(c *testing.T) { 3949 name := "miss-me-when-im-gone" 3950 cli.DockerCmd(c, "run", "--name="+name, "--rm", "busybox") 3951 3952 cli.Docker(cli.Args("inspect", name), cli.Format(".name")).Assert(c, icmd.Expected{ 3953 ExitCode: 1, 3954 Err: "No such object: " + name, 3955 }) 3956 } 3957 3958 // Test that auto-remove is performed by the client on API versions that do not support daemon-side api-remove (API < 1.25) 3959 func (s *DockerCLIRunSuite) TestRunRmPre125Api(c *testing.T) { 3960 name := "miss-me-when-im-gone" 3961 envs := appendBaseEnv(os.Getenv("DOCKER_TLS_VERIFY") != "", "DOCKER_API_VERSION=1.24") 3962 cli.Docker(cli.Args("run", "--name="+name, "--rm", "busybox"), cli.WithEnvironmentVariables(envs...)).Assert(c, icmd.Success) 3963 3964 cli.Docker(cli.Args("inspect", name), cli.Format(".name")).Assert(c, icmd.Expected{ 3965 ExitCode: 1, 3966 Err: "No such object: " + name, 3967 }) 3968 } 3969 3970 // Test case for #23498 3971 func (s *DockerCLIRunSuite) TestRunUnsetEntrypoint(c *testing.T) { 3972 testRequires(c, DaemonIsLinux) 3973 name := "test-entrypoint" 3974 dockerfile := `FROM busybox 3975 ADD entrypoint.sh /entrypoint.sh 3976 RUN chmod 755 /entrypoint.sh 3977 ENTRYPOINT ["/entrypoint.sh"] 3978 CMD echo foobar` 3979 3980 ctx := fakecontext.New(c, "", 3981 fakecontext.WithDockerfile(dockerfile), 3982 fakecontext.WithFiles(map[string]string{ 3983 "entrypoint.sh": `#!/bin/sh 3984 echo "I am an entrypoint" 3985 exec "$@"`, 3986 })) 3987 defer ctx.Close() 3988 3989 cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) 3990 3991 out := cli.DockerCmd(c, "run", "--entrypoint=", "-t", name, "echo", "foo").Combined() 3992 assert.Equal(c, strings.TrimSpace(out), "foo") 3993 3994 // CMD will be reset as well (the same as setting a custom entrypoint) 3995 cli.Docker(cli.Args("run", "--entrypoint=", "-t", name)).Assert(c, icmd.Expected{ 3996 ExitCode: 125, 3997 Err: "no command specified", 3998 }) 3999 } 4000 4001 func (s *DockerDaemonSuite) TestRunWithUlimitAndDaemonDefault(c *testing.T) { 4002 ctx := testutil.GetContext(c) 4003 d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvVars("OTEL_SDK_DISABLED=1")) 4004 defer func() { 4005 d.Stop(c) 4006 d.Cleanup(c) 4007 }() 4008 d.StartWithBusybox(ctx, c, "--debug", "--default-ulimit=nofile=65535") 4009 4010 name := "test-A" 4011 _, err := d.Cmd("run", "--name", name, "-d", "busybox", "top") 4012 assert.NilError(c, err) 4013 assert.NilError(c, d.WaitRun(name)) 4014 4015 out, err := d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name) 4016 assert.NilError(c, err) 4017 assert.Assert(c, strings.Contains(out, "[nofile=65535:65535]")) 4018 name = "test-B" 4019 _, err = d.Cmd("run", "--name", name, "--ulimit=nofile=42", "-d", "busybox", "top") 4020 assert.NilError(c, err) 4021 assert.NilError(c, d.WaitRun(name)) 4022 4023 out, err = d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name) 4024 assert.NilError(c, err) 4025 assert.Assert(c, strings.Contains(out, "[nofile=42:42]")) 4026 } 4027 4028 func (s *DockerCLIRunSuite) TestRunStoppedLoggingDriverNoLeak(c *testing.T) { 4029 client := testEnv.APIClient() 4030 ctx := testutil.GetContext(c) 4031 nroutines, err := getGoroutineNumber(ctx, client) 4032 assert.NilError(c, err) 4033 4034 out, _, err := dockerCmdWithError("run", "--name=fail", "--log-driver=splunk", "busybox", "true") 4035 assert.ErrorContains(c, err, "") 4036 assert.Assert(c, strings.Contains(out, "failed to initialize logging driver"), "error should be about logging driver, got output %s", out) 4037 4038 // NGoroutines is not updated right away, so we need to wait before failing 4039 waitForGoroutines(ctx, c, client, nroutines) 4040 } 4041 4042 // Handles error conditions for --credentialspec. Validating E2E success cases 4043 // requires additional infrastructure (AD for example) on CI servers. 4044 func (s *DockerCLIRunSuite) TestRunCredentialSpecFailures(c *testing.T) { 4045 testRequires(c, DaemonIsWindows) 4046 4047 attempts := []struct{ value, expectedError string }{ 4048 {"rubbish", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"}, 4049 {"rubbish://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"}, 4050 {"file://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"}, 4051 {"registry://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"}, 4052 {`file://c:\blah.txt`, "path cannot be absolute"}, 4053 {`file://doesnotexist.txt`, "The system cannot find the file specified"}, 4054 } 4055 for _, attempt := range attempts { 4056 _, _, err := dockerCmdWithError("run", "--security-opt=credentialspec="+attempt.value, "busybox", "true") 4057 assert.Assert(c, err != nil, "%s expected non-nil err", attempt.value) 4058 assert.Assert(c, strings.Contains(err.Error(), attempt.expectedError), "%s expected %s got %s", attempt.value, attempt.expectedError, err) 4059 } 4060 } 4061 4062 // Windows specific test to validate credential specs with a well-formed spec. 4063 func (s *DockerCLIRunSuite) TestRunCredentialSpecWellFormed(c *testing.T) { 4064 testRequires(c, DaemonIsWindows, testEnv.IsLocalDaemon) 4065 4066 validCredSpecs := readFile(`fixtures\credentialspecs\valid.json`, c) 4067 writeFile(filepath.Join(testEnv.DaemonInfo.DockerRootDir, `credentialspecs\valid.json`), validCredSpecs, c) 4068 4069 for _, value := range []string{"file://valid.json", "raw://" + validCredSpecs} { 4070 // `nltest /PARENTDOMAIN` simply reads the local config, and does not require having an AD 4071 // controller handy 4072 out := cli.DockerCmd(c, "run", "--rm", "--security-opt=credentialspec="+value, minimalBaseImage(), "nltest", "/PARENTDOMAIN").Combined() 4073 4074 assert.Assert(c, strings.Contains(out, "hyperv.local.")) 4075 assert.Assert(c, strings.Contains(out, "The command completed successfully")) 4076 } 4077 } 4078 4079 func (s *DockerCLIRunSuite) TestRunDuplicateMount(c *testing.T) { 4080 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 4081 4082 tmpFile, err := os.CreateTemp("", "touch-me") 4083 assert.NilError(c, err) 4084 defer tmpFile.Close() 4085 4086 data := "touch-me-foo-bar\n" 4087 if _, err := tmpFile.Write([]byte(data)); err != nil { 4088 c.Fatal(err) 4089 } 4090 4091 name := "test" 4092 out := cli.DockerCmd(c, "run", "--name", name, "-v", "/tmp:/tmp", "-v", "/tmp:/tmp", "busybox", "sh", "-c", "cat "+tmpFile.Name()+" && ls /").Combined() 4093 assert.Assert(c, !strings.Contains(out, "tmp:")) 4094 assert.Assert(c, strings.Contains(out, data)) 4095 out = inspectFieldJSON(c, name, "Config.Volumes") 4096 assert.Assert(c, strings.Contains(out, "null")) 4097 } 4098 4099 func (s *DockerCLIRunSuite) TestRunWindowsWithCPUCount(c *testing.T) { 4100 testRequires(c, DaemonIsWindows) 4101 4102 out := cli.DockerCmd(c, "run", "--cpu-count=1", "--name", "test", "busybox", "echo", "testing").Combined() 4103 assert.Equal(c, strings.TrimSpace(out), "testing") 4104 4105 out = inspectField(c, "test", "HostConfig.CPUCount") 4106 assert.Equal(c, out, "1") 4107 } 4108 4109 func (s *DockerCLIRunSuite) TestRunWindowsWithCPUShares(c *testing.T) { 4110 testRequires(c, DaemonIsWindows) 4111 4112 out := cli.DockerCmd(c, "run", "--cpu-shares=1000", "--name", "test", "busybox", "echo", "testing").Combined() 4113 assert.Equal(c, strings.TrimSpace(out), "testing") 4114 4115 out = inspectField(c, "test", "HostConfig.CPUShares") 4116 assert.Equal(c, out, "1000") 4117 } 4118 4119 func (s *DockerCLIRunSuite) TestRunWindowsWithCPUPercent(c *testing.T) { 4120 testRequires(c, DaemonIsWindows) 4121 4122 out := cli.DockerCmd(c, "run", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing").Combined() 4123 assert.Equal(c, strings.TrimSpace(out), "testing") 4124 4125 out = inspectField(c, "test", "HostConfig.CPUPercent") 4126 assert.Equal(c, out, "80") 4127 } 4128 4129 func (s *DockerCLIRunSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) { 4130 testRequires(c, DaemonIsWindows, testEnv.DaemonInfo.Isolation.IsProcess) 4131 4132 out := cli.DockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing").Combined() 4133 assert.Assert(c, strings.Contains(strings.TrimSpace(out), "WARNING: Conflicting options: CPU count takes priority over CPU shares on Windows Server Containers. CPU shares discarded")) 4134 assert.Assert(c, strings.Contains(strings.TrimSpace(out), "WARNING: Conflicting options: CPU count takes priority over CPU percent on Windows Server Containers. CPU percent discarded")) 4135 assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing")) 4136 out = inspectField(c, "test", "HostConfig.CPUCount") 4137 assert.Equal(c, out, "1") 4138 4139 out = inspectField(c, "test", "HostConfig.CPUShares") 4140 assert.Equal(c, out, "0") 4141 4142 out = inspectField(c, "test", "HostConfig.CPUPercent") 4143 assert.Equal(c, out, "0") 4144 } 4145 4146 func (s *DockerCLIRunSuite) TestRunHypervIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) { 4147 testRequires(c, DaemonIsWindows, testEnv.DaemonInfo.Isolation.IsHyperV) 4148 4149 out := cli.DockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing").Combined() 4150 assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing")) 4151 out = inspectField(c, "test", "HostConfig.CPUCount") 4152 assert.Equal(c, out, "1") 4153 4154 out = inspectField(c, "test", "HostConfig.CPUShares") 4155 assert.Equal(c, out, "1000") 4156 4157 out = inspectField(c, "test", "HostConfig.CPUPercent") 4158 assert.Equal(c, out, "80") 4159 } 4160 4161 // Test for #25099 4162 func (s *DockerCLIRunSuite) TestRunEmptyEnv(c *testing.T) { 4163 testRequires(c, DaemonIsLinux) 4164 4165 expectedOutput := "invalid environment variable:" 4166 4167 out, _, err := dockerCmdWithError("run", "-e", "", "busybox", "true") 4168 assert.ErrorContains(c, err, "") 4169 assert.Assert(c, strings.Contains(out, expectedOutput)) 4170 4171 out, _, err = dockerCmdWithError("run", "-e", "=", "busybox", "true") 4172 assert.ErrorContains(c, err, "") 4173 assert.Assert(c, strings.Contains(out, expectedOutput)) 4174 4175 out, _, err = dockerCmdWithError("run", "-e", "=foo", "busybox", "true") 4176 assert.ErrorContains(c, err, "") 4177 assert.Assert(c, strings.Contains(out, expectedOutput)) 4178 } 4179 4180 // #28658 4181 func (s *DockerCLIRunSuite) TestSlowStdinClosing(c *testing.T) { 4182 if DaemonIsWindows() { 4183 skip.If(c, testEnv.GitHubActions()) 4184 } 4185 const repeat = 3 // regression happened 50% of the time 4186 for i := 0; i < repeat; i++ { 4187 c.Run(strconv.Itoa(i), func(c *testing.T) { 4188 cmd := icmd.Cmd{ 4189 Command: []string{dockerBinary, "run", "--rm", "-i", "busybox", "cat"}, 4190 Stdin: &delayedReader{}, 4191 } 4192 done := make(chan error, 1) 4193 go func() { 4194 result := icmd.RunCmd(cmd) 4195 if out := result.Combined(); out != "" { 4196 c.Log(out) 4197 } 4198 done <- result.Error 4199 }() 4200 4201 select { 4202 case <-time.After(30 * time.Second): 4203 c.Fatal("running container timed out") // cleanup in teardown 4204 case err := <-done: 4205 assert.NilError(c, err) 4206 } 4207 }) 4208 } 4209 } 4210 4211 type delayedReader struct{} 4212 4213 func (s *delayedReader) Read([]byte) (int, error) { 4214 time.Sleep(500 * time.Millisecond) 4215 return 0, io.EOF 4216 } 4217 4218 // #28823 (originally #28639) 4219 func (s *DockerCLIRunSuite) TestRunMountReadOnlyDevShm(c *testing.T) { 4220 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 4221 emptyDir, err := os.MkdirTemp("", "test-read-only-dev-shm") 4222 assert.NilError(c, err) 4223 defer os.RemoveAll(emptyDir) 4224 out, _, err := dockerCmdWithError("run", "--rm", "--read-only", 4225 "-v", fmt.Sprintf("%s:/dev/shm:ro", emptyDir), 4226 "busybox", "touch", "/dev/shm/foo") 4227 assert.ErrorContains(c, err, "", out) 4228 assert.Assert(c, strings.Contains(out, "Read-only file system")) 4229 } 4230 4231 func (s *DockerCLIRunSuite) TestRunMount(c *testing.T) { 4232 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace) 4233 4234 // mnt1, mnt2, and testCatFooBar are commonly used in multiple test cases 4235 tmpDir, err := os.MkdirTemp("", "mount") 4236 if err != nil { 4237 c.Fatal(err) 4238 } 4239 defer os.RemoveAll(tmpDir) 4240 mnt1, mnt2 := path.Join(tmpDir, "mnt1"), path.Join(tmpDir, "mnt2") 4241 if err := os.Mkdir(mnt1, 0o755); err != nil { 4242 c.Fatal(err) 4243 } 4244 if err := os.Mkdir(mnt2, 0o755); err != nil { 4245 c.Fatal(err) 4246 } 4247 if err := os.WriteFile(path.Join(mnt1, "test1"), []byte("test1"), 0o644); err != nil { 4248 c.Fatal(err) 4249 } 4250 if err := os.WriteFile(path.Join(mnt2, "test2"), []byte("test2"), 0o644); err != nil { 4251 c.Fatal(err) 4252 } 4253 testCatFooBar := func(cName string) error { 4254 out := cli.DockerCmd(c, "exec", cName, "cat", "/foo/test1").Stdout() 4255 if out != "test1" { 4256 return fmt.Errorf("%s not mounted on /foo", mnt1) 4257 } 4258 out = cli.DockerCmd(c, "exec", cName, "cat", "/bar/test2").Stdout() 4259 if out != "test2" { 4260 return fmt.Errorf("%s not mounted on /bar", mnt2) 4261 } 4262 return nil 4263 } 4264 4265 type testCase struct { 4266 equivalents [][]string 4267 valid bool 4268 // fn should be nil if valid==false 4269 fn func(cName string) error 4270 } 4271 cases := []testCase{ 4272 { 4273 equivalents: [][]string{ 4274 { 4275 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4276 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/bar", mnt2), 4277 }, 4278 { 4279 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4280 "--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2), 4281 }, 4282 { 4283 "--volume", mnt1 + ":/foo", 4284 "--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2), 4285 }, 4286 }, 4287 valid: true, 4288 fn: testCatFooBar, 4289 }, 4290 { 4291 equivalents: [][]string{ 4292 { 4293 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1), 4294 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2), 4295 }, 4296 { 4297 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1), 4298 "--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2), 4299 }, 4300 }, 4301 valid: false, 4302 }, 4303 { 4304 equivalents: [][]string{ 4305 { 4306 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4307 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2), 4308 }, 4309 { 4310 "--volume", mnt1 + ":/foo", 4311 "--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2), 4312 }, 4313 }, 4314 valid: false, 4315 fn: testCatFooBar, 4316 }, 4317 { 4318 equivalents: [][]string{ 4319 { 4320 "--read-only", 4321 "--mount", "type=volume,dst=/bar", 4322 }, 4323 }, 4324 valid: true, 4325 fn: func(cName string) error { 4326 _, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere") 4327 return err 4328 }, 4329 }, 4330 { 4331 equivalents: [][]string{ 4332 { 4333 "--read-only", 4334 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4335 "--mount", "type=volume,dst=/bar", 4336 }, 4337 { 4338 "--read-only", 4339 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4340 "--mount", "type=volume,dst=/bar", 4341 }, 4342 }, 4343 valid: true, 4344 fn: func(cName string) error { 4345 out := cli.DockerCmd(c, "exec", cName, "cat", "/foo/test1").Combined() 4346 if out != "test1" { 4347 return fmt.Errorf("%s not mounted on /foo", mnt1) 4348 } 4349 _, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere") 4350 return err 4351 }, 4352 }, 4353 { 4354 equivalents: [][]string{ 4355 { 4356 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4357 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt2), 4358 }, 4359 { 4360 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4361 "--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2), 4362 }, 4363 { 4364 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4365 "--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2), 4366 }, 4367 }, 4368 valid: false, 4369 }, 4370 { 4371 equivalents: [][]string{ 4372 { 4373 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4374 "--mount", fmt.Sprintf("type=volume,src=%s,target=/foo", mnt2), 4375 }, 4376 }, 4377 valid: false, 4378 }, 4379 { 4380 equivalents: [][]string{ 4381 { 4382 "--mount", "type=volume,target=/foo", 4383 "--mount", "type=volume,target=/foo", 4384 }, 4385 }, 4386 valid: false, 4387 }, 4388 } 4389 4390 for i, testCase := range cases { 4391 for j, opts := range testCase.equivalents { 4392 cName := fmt.Sprintf("mount-%d-%d", i, j) 4393 _, _, err := dockerCmdWithError(append([]string{"run", "-i", "-d", "--name", cName}, 4394 append(opts, []string{"busybox", "top"}...)...)...) 4395 if testCase.valid { 4396 assert.Assert(c, err == nil, "got error while creating a container with %v (%s)", opts, cName) 4397 assert.Assert(c, testCase.fn(cName) == nil, "got error while executing test for %v (%s)", opts, cName) 4398 cli.DockerCmd(c, "rm", "-f", cName) 4399 } else { 4400 assert.Assert(c, err != nil, "got nil while creating a container with %v (%s)", opts, cName) 4401 } 4402 } 4403 } 4404 } 4405 4406 // Test that passing a FQDN as hostname properly sets hostname, and 4407 // /etc/hostname. Test case for 29100 4408 func (s *DockerCLIRunSuite) TestRunHostnameFQDN(c *testing.T) { 4409 testRequires(c, DaemonIsLinux) 4410 4411 expectedOutput := "foobar.example.com\nfoobar.example.com\nfoobar\nexample.com\nfoobar.example.com" 4412 out := cli.DockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`).Combined() 4413 assert.Equal(c, strings.TrimSpace(out), expectedOutput) 4414 4415 out = cli.DockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`).Combined() 4416 expectedOutput = "foobar.example.com foobar" 4417 assert.Assert(c, strings.Contains(strings.TrimSpace(out), expectedOutput)) 4418 } 4419 4420 // Test case for 29129 4421 func (s *DockerCLIRunSuite) TestRunHostnameInHostMode(c *testing.T) { 4422 testRequires(c, DaemonIsLinux, NotUserNamespace) 4423 4424 const expectedOutput = "foobar\nfoobar" 4425 out := cli.DockerCmd(c, "run", "--net=host", "--hostname=foobar", "busybox", "sh", "-c", `echo $HOSTNAME && hostname`).Combined() 4426 assert.Equal(c, strings.TrimSpace(out), expectedOutput) 4427 } 4428 4429 func (s *DockerCLIRunSuite) TestRunAddDeviceCgroupRule(c *testing.T) { 4430 testRequires(c, DaemonIsLinux) 4431 4432 const deviceRule = "c 7:128 rwm" 4433 4434 out := cli.DockerCmd(c, "run", "--rm", "busybox", "cat", "/sys/fs/cgroup/devices/devices.list").Combined() 4435 if strings.Contains(out, deviceRule) { 4436 c.Fatalf("%s shouldn't been in the device.list", deviceRule) 4437 } 4438 4439 out = cli.DockerCmd(c, "run", "--rm", fmt.Sprintf("--device-cgroup-rule=%s", deviceRule), "busybox", "grep", deviceRule, "/sys/fs/cgroup/devices/devices.list").Combined() 4440 assert.Equal(c, strings.TrimSpace(out), deviceRule) 4441 } 4442 4443 // Verifies that running as local system is operating correctly on Windows 4444 func (s *DockerCLIRunSuite) TestWindowsRunAsSystem(c *testing.T) { 4445 testRequires(c, DaemonIsWindows) 4446 out := cli.DockerCmd(c, "run", "--net=none", `--user=nt authority\system`, "--hostname=XYZZY", minimalBaseImage(), "cmd", "/c", `@echo %USERNAME%`).Combined() 4447 assert.Equal(c, strings.TrimSpace(out), "XYZZY$") 4448 }