docker_cli_run_test.go 167 KB

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