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