docker_cli_build_test.go 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "os"
  9. "path/filepath"
  10. "reflect"
  11. "regexp"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "testing"
  16. "text/template"
  17. "time"
  18. "github.com/docker/docker/api/types/versions"
  19. "github.com/docker/docker/integration-cli/cli"
  20. "github.com/docker/docker/integration-cli/cli/build"
  21. "github.com/docker/docker/pkg/archive"
  22. "github.com/docker/docker/testutil"
  23. "github.com/docker/docker/testutil/fakecontext"
  24. "github.com/docker/docker/testutil/fakegit"
  25. "github.com/docker/docker/testutil/fakestorage"
  26. "github.com/moby/buildkit/frontend/dockerfile/command"
  27. "github.com/opencontainers/go-digest"
  28. "gotest.tools/v3/assert"
  29. is "gotest.tools/v3/assert/cmp"
  30. "gotest.tools/v3/icmd"
  31. "gotest.tools/v3/skip"
  32. )
  33. type DockerCLIBuildSuite struct {
  34. ds *DockerSuite
  35. }
  36. func (s *DockerCLIBuildSuite) TearDownTest(ctx context.Context, c *testing.T) {
  37. s.ds.TearDownTest(ctx, c)
  38. }
  39. func (s *DockerCLIBuildSuite) OnTimeout(c *testing.T) {
  40. s.ds.OnTimeout(c)
  41. }
  42. func (s *DockerCLIBuildSuite) TestBuildJSONEmptyRun(c *testing.T) {
  43. cli.BuildCmd(c, "testbuildjsonemptyrun", build.WithDockerfile(`
  44. FROM busybox
  45. RUN []
  46. `))
  47. }
  48. func (s *DockerCLIBuildSuite) TestBuildShCmdJSONEntrypoint(c *testing.T) {
  49. const name = "testbuildshcmdjsonentrypoint"
  50. expected := "/bin/sh -c echo test"
  51. if testEnv.DaemonInfo.OSType == "windows" {
  52. expected = "cmd /S /C echo test"
  53. }
  54. buildImageSuccessfully(c, name, build.WithDockerfile(`
  55. FROM busybox
  56. ENTRYPOINT ["echo"]
  57. CMD echo test
  58. `))
  59. out := cli.DockerCmd(c, "run", "--rm", name).Combined()
  60. if strings.TrimSpace(out) != expected {
  61. c.Fatalf("CMD did not contain %q : %q", expected, out)
  62. }
  63. }
  64. func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementUser(c *testing.T) {
  65. // Windows does not support FROM scratch or the USER command
  66. testRequires(c, DaemonIsLinux)
  67. const name = "testbuildenvironmentreplacement"
  68. buildImageSuccessfully(c, name, build.WithDockerfile(`
  69. FROM scratch
  70. ENV user foo
  71. USER ${user}
  72. `))
  73. res := inspectFieldJSON(c, name, "Config.User")
  74. if res != `"foo"` {
  75. c.Fatal("User foo from environment not in Config.User on image")
  76. }
  77. }
  78. func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementVolume(c *testing.T) {
  79. const name = "testbuildenvironmentreplacement"
  80. var volumePath string
  81. if testEnv.DaemonInfo.OSType == "windows" {
  82. volumePath = "c:/quux"
  83. } else {
  84. volumePath = "/quux"
  85. }
  86. buildImageSuccessfully(c, name, build.WithDockerfile(`
  87. FROM `+minimalBaseImage()+`
  88. ENV volume `+volumePath+`
  89. VOLUME ${volume}
  90. `))
  91. var volumes map[string]interface{}
  92. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &volumes)
  93. if _, ok := volumes[volumePath]; !ok {
  94. c.Fatal("Volume " + volumePath + " from environment not in Config.Volumes on image")
  95. }
  96. }
  97. func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementExpose(c *testing.T) {
  98. // Windows does not support FROM scratch or the EXPOSE command
  99. testRequires(c, DaemonIsLinux)
  100. const name = "testbuildenvironmentreplacement"
  101. buildImageSuccessfully(c, name, build.WithDockerfile(`
  102. FROM scratch
  103. ENV port 80
  104. EXPOSE ${port}
  105. ENV ports " 99 100 "
  106. EXPOSE ${ports}
  107. `))
  108. var exposedPorts map[string]interface{}
  109. inspectFieldAndUnmarshall(c, name, "Config.ExposedPorts", &exposedPorts)
  110. exp := []int{80, 99, 100}
  111. for _, p := range exp {
  112. tmp := fmt.Sprintf("%d/tcp", p)
  113. if _, ok := exposedPorts[tmp]; !ok {
  114. c.Fatalf("Exposed port %d from environment not in Config.ExposedPorts on image", p)
  115. }
  116. }
  117. }
  118. func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementWorkdir(c *testing.T) {
  119. const name = "testbuildenvironmentreplacement"
  120. buildImageSuccessfully(c, name, build.WithDockerfile(`
  121. FROM busybox
  122. ENV MYWORKDIR /work
  123. RUN mkdir ${MYWORKDIR}
  124. WORKDIR ${MYWORKDIR}
  125. `))
  126. res := inspectFieldJSON(c, name, "Config.WorkingDir")
  127. expected := `"/work"`
  128. if testEnv.DaemonInfo.OSType == "windows" {
  129. expected = `"C:\\work"`
  130. }
  131. if res != expected {
  132. c.Fatalf("Workdir /workdir from environment not in Config.WorkingDir on image: %s", res)
  133. }
  134. }
  135. func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementAddCopy(c *testing.T) {
  136. const name = "testbuildenvironmentreplacement"
  137. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  138. build.WithFile("Dockerfile", `
  139. FROM `+minimalBaseImage()+`
  140. ENV baz foo
  141. ENV quux bar
  142. ENV dot .
  143. ENV fee fff
  144. ENV gee ggg
  145. ADD ${baz} ${dot}
  146. COPY ${quux} ${dot}
  147. ADD ${zzz:-${fee}} ${dot}
  148. COPY ${zzz:-${gee}} ${dot}
  149. `),
  150. build.WithFile("foo", "test1"),
  151. build.WithFile("bar", "test2"),
  152. build.WithFile("fff", "test3"),
  153. build.WithFile("ggg", "test4"),
  154. ))
  155. }
  156. func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementEnv(c *testing.T) {
  157. // ENV expansions work differently in Windows
  158. testRequires(c, DaemonIsLinux)
  159. const name = "testbuildenvironmentreplacement"
  160. buildImageSuccessfully(c, name, build.WithDockerfile(`
  161. FROM busybox
  162. ENV foo zzz
  163. ENV bar ${foo}
  164. ENV abc1='$foo'
  165. ENV env1=$foo env2=${foo} env3="$foo" env4="${foo}"
  166. RUN [ "$abc1" = '$foo' ] && (echo "$abc1" | grep -q foo)
  167. ENV abc2="\$foo"
  168. RUN [ "$abc2" = '$foo' ] && (echo "$abc2" | grep -q foo)
  169. ENV abc3 '$foo'
  170. RUN [ "$abc3" = '$foo' ] && (echo "$abc3" | grep -q foo)
  171. ENV abc4 "\$foo"
  172. RUN [ "$abc4" = '$foo' ] && (echo "$abc4" | grep -q foo)
  173. ENV foo2="abc\def"
  174. RUN [ "$foo2" = 'abc\def' ]
  175. ENV foo3="abc\\def"
  176. RUN [ "$foo3" = 'abc\def' ]
  177. ENV foo4='abc\\def'
  178. RUN [ "$foo4" = 'abc\\def' ]
  179. ENV foo5='abc\def'
  180. RUN [ "$foo5" = 'abc\def' ]
  181. `))
  182. var envResult []string
  183. inspectFieldAndUnmarshall(c, name, "Config.Env", &envResult)
  184. found := false
  185. envCount := 0
  186. for _, env := range envResult {
  187. k, v, _ := strings.Cut(env, "=")
  188. if k == "bar" {
  189. found = true
  190. if v != "zzz" {
  191. c.Fatalf("Could not find replaced var for env `bar`: got %q instead of `zzz`", v)
  192. }
  193. } else if strings.HasPrefix(k, "env") {
  194. envCount++
  195. if v != "zzz" {
  196. c.Fatalf("%s should be 'zzz' but instead its %q", k, v)
  197. }
  198. } else if strings.HasPrefix(k, "env") {
  199. envCount++
  200. if v != "foo" {
  201. c.Fatalf("%s should be 'foo' but instead its %q", k, v)
  202. }
  203. }
  204. }
  205. if !found {
  206. c.Fatal("Never found the `bar` env variable")
  207. }
  208. if envCount != 4 {
  209. c.Fatalf("Didn't find all env vars - only saw %d\n%s", envCount, envResult)
  210. }
  211. }
  212. func (s *DockerCLIBuildSuite) TestBuildHandleEscapesInVolume(c *testing.T) {
  213. // The volume paths used in this test are invalid on Windows
  214. testRequires(c, DaemonIsLinux)
  215. const name = "testbuildhandleescapes"
  216. testCases := []struct {
  217. volumeValue string
  218. expected string
  219. }{
  220. {
  221. volumeValue: "${FOO}",
  222. expected: "bar",
  223. },
  224. {
  225. volumeValue: `\${FOO}`,
  226. expected: "${FOO}",
  227. },
  228. // this test in particular provides *7* backslashes and expects 6 to come back.
  229. // Like above, the first escape is swallowed and the rest are treated as
  230. // literals, this one is just less obvious because of all the character noise.
  231. {
  232. volumeValue: `\\\\\\\${FOO}`,
  233. expected: `\\\${FOO}`,
  234. },
  235. }
  236. for _, tc := range testCases {
  237. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`
  238. FROM scratch
  239. ENV FOO bar
  240. VOLUME %s
  241. `, tc.volumeValue)))
  242. var result map[string]map[string]struct{}
  243. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &result)
  244. if _, ok := result[tc.expected]; !ok {
  245. c.Fatalf("Could not find volume %s set from env foo in volumes table, got %q", tc.expected, result)
  246. }
  247. // Remove the image for the next iteration
  248. cli.DockerCmd(c, "rmi", name)
  249. }
  250. }
  251. func (s *DockerCLIBuildSuite) TestBuildOnBuildLowercase(c *testing.T) {
  252. const name = "testbuildonbuildlowercase"
  253. const name2 = "testbuildonbuildlowercase2"
  254. buildImageSuccessfully(c, name, build.WithDockerfile(`
  255. FROM busybox
  256. onbuild run echo quux
  257. `))
  258. result := buildImage(name2, build.WithDockerfile(fmt.Sprintf(`
  259. FROM %s
  260. `, name)))
  261. result.Assert(c, icmd.Success)
  262. if !strings.Contains(result.Combined(), "quux") {
  263. c.Fatalf("Did not receive the expected echo text, got %s", result.Combined())
  264. }
  265. if strings.Contains(result.Combined(), "ONBUILD ONBUILD") {
  266. c.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", result.Combined())
  267. }
  268. }
  269. func (s *DockerCLIBuildSuite) TestBuildEnvEscapes(c *testing.T) {
  270. // ENV expansions work differently in Windows
  271. testRequires(c, DaemonIsLinux)
  272. const name = "testbuildenvescapes"
  273. buildImageSuccessfully(c, name, build.WithDockerfile(`
  274. FROM busybox
  275. ENV TEST foo
  276. CMD echo \$
  277. `))
  278. out := cli.DockerCmd(c, "run", "-t", name).Combined()
  279. if strings.TrimSpace(out) != "$" {
  280. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  281. }
  282. }
  283. func (s *DockerCLIBuildSuite) TestBuildEnvOverwrite(c *testing.T) {
  284. // ENV expansions work differently in Windows
  285. testRequires(c, DaemonIsLinux)
  286. const name = "testbuildenvoverwrite"
  287. buildImageSuccessfully(c, name, build.WithDockerfile(`
  288. FROM busybox
  289. ENV TEST foo
  290. CMD echo ${TEST}
  291. `))
  292. out := cli.DockerCmd(c, "run", "-e", "TEST=bar", "-t", name).Combined()
  293. if strings.TrimSpace(out) != "bar" {
  294. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  295. }
  296. }
  297. // FIXME(vdemeester) why we disabled cache here ?
  298. func (s *DockerCLIBuildSuite) TestBuildOnBuildCmdEntrypointJSON(c *testing.T) {
  299. const name1 = "onbuildcmd"
  300. const name2 = "onbuildgenerated"
  301. cli.BuildCmd(c, name1, build.WithDockerfile(`
  302. FROM busybox
  303. ONBUILD CMD ["hello world"]
  304. ONBUILD ENTRYPOINT ["echo"]
  305. ONBUILD RUN ["true"]`))
  306. cli.BuildCmd(c, name2, build.WithDockerfile(fmt.Sprintf(`FROM %s`, name1)))
  307. result := cli.DockerCmd(c, "run", name2)
  308. result.Assert(c, icmd.Expected{Out: "hello world"})
  309. }
  310. // FIXME(vdemeester) why we disabled cache here ?
  311. func (s *DockerCLIBuildSuite) TestBuildOnBuildEntrypointJSON(c *testing.T) {
  312. const name1 = "onbuildcmd"
  313. const name2 = "onbuildgenerated"
  314. buildImageSuccessfully(c, name1, build.WithDockerfile(`
  315. FROM busybox
  316. ONBUILD ENTRYPOINT ["echo"]`))
  317. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1)))
  318. out := cli.DockerCmd(c, "run", name2).Combined()
  319. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  320. c.Fatal("got malformed output from onbuild", out)
  321. }
  322. }
  323. func (s *DockerCLIBuildSuite) TestBuildCacheAdd(c *testing.T) {
  324. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  325. const name = "testbuildtwoimageswithadd"
  326. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  327. "robots.txt": "hello",
  328. "index.html": "world",
  329. }))
  330. defer server.Close()
  331. cli.BuildCmd(c, name, build.WithDockerfile(fmt.Sprintf(`FROM scratch
  332. ADD %s/robots.txt /`, server.URL())))
  333. result := cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(fmt.Sprintf(`FROM scratch
  334. ADD %s/index.html /`, server.URL())))
  335. result.Assert(c, icmd.Success)
  336. if strings.Contains(result.Combined(), "Using cache") {
  337. c.Fatal("2nd build used cache on ADD, it shouldn't")
  338. }
  339. }
  340. func (s *DockerCLIBuildSuite) TestBuildLastModified(c *testing.T) {
  341. // Temporary fix for #30890. TODO: figure out what
  342. // has changed in the master busybox image.
  343. testRequires(c, DaemonIsLinux)
  344. const name = "testbuildlastmodified"
  345. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  346. "file": "hello",
  347. }))
  348. defer server.Close()
  349. var out, out2 string
  350. args := []string{"run", name, "ls", "-l", "--full-time", "/file"}
  351. dFmt := `FROM busybox
  352. ADD %s/file /`
  353. dockerfile := fmt.Sprintf(dFmt, server.URL())
  354. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  355. out = cli.DockerCmd(c, args...).Combined()
  356. // Build it again and make sure the mtime of the file didn't change.
  357. // Wait a few seconds to make sure the time changed enough to notice
  358. time.Sleep(2 * time.Second)
  359. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  360. out2 = cli.DockerCmd(c, args...).Combined()
  361. if out != out2 {
  362. c.Fatalf("MTime changed:\nOrigin:%s\nNew:%s", out, out2)
  363. }
  364. // Now 'touch' the file and make sure the timestamp DID change this time
  365. // Create a new fakeStorage instead of just using Add() to help windows
  366. server = fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  367. "file": "hello",
  368. }))
  369. defer server.Close()
  370. dockerfile = fmt.Sprintf(dFmt, server.URL())
  371. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  372. out2 = cli.DockerCmd(c, args...).Combined()
  373. if out == out2 {
  374. c.Fatalf("MTime didn't change:\nOrigin:%s\nNew:%s", out, out2)
  375. }
  376. }
  377. // Regression for https://github.com/docker/docker/pull/27805
  378. // Makes sure that we don't use the cache if the contents of
  379. // a file in a subfolder of the context is modified and we re-build.
  380. func (s *DockerCLIBuildSuite) TestBuildModifyFileInFolder(c *testing.T) {
  381. const name = "testbuildmodifyfileinfolder"
  382. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  383. RUN ["mkdir", "/test"]
  384. ADD folder/file /test/changetarget`))
  385. defer ctx.Close()
  386. if err := ctx.Add("folder/file", "first"); err != nil {
  387. c.Fatal(err)
  388. }
  389. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  390. id1 := getIDByName(c, name)
  391. if err := ctx.Add("folder/file", "second"); err != nil {
  392. c.Fatal(err)
  393. }
  394. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  395. id2 := getIDByName(c, name)
  396. if id1 == id2 {
  397. c.Fatal("cache was used even though file contents in folder was changed")
  398. }
  399. }
  400. func (s *DockerCLIBuildSuite) TestBuildAddSingleFileToRoot(c *testing.T) {
  401. testRequires(c, DaemonIsLinux) // Linux specific test
  402. buildImageSuccessfully(c, "testaddimg", build.WithBuildContext(c,
  403. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  404. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  405. RUN echo 'dockerio:x:1001:' >> /etc/group
  406. RUN touch /exists
  407. RUN chown dockerio.dockerio /exists
  408. ADD test_file /
  409. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  410. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  411. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  412. build.WithFile("test_file", "test1")))
  413. }
  414. // Issue #3960: "ADD src ." hangs
  415. func (s *DockerCLIBuildSuite) TestBuildAddSingleFileToWorkdir(c *testing.T) {
  416. const name = "testaddsinglefiletoworkdir"
  417. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(
  418. `FROM busybox
  419. ADD test_file .`),
  420. fakecontext.WithFiles(map[string]string{
  421. "test_file": "test1",
  422. }))
  423. defer ctx.Close()
  424. errChan := make(chan error, 1)
  425. go func() {
  426. errChan <- buildImage(name, build.WithExternalBuildContext(ctx)).Error
  427. close(errChan)
  428. }()
  429. select {
  430. case <-time.After(15 * time.Second):
  431. c.Fatal("Build with adding to workdir timed out")
  432. case err := <-errChan:
  433. assert.NilError(c, err)
  434. }
  435. }
  436. func (s *DockerCLIBuildSuite) TestBuildAddSingleFileToExistDir(c *testing.T) {
  437. testRequires(c, DaemonIsLinux) // Linux specific test
  438. cli.BuildCmd(c, "testaddsinglefiletoexistdir", build.WithBuildContext(c,
  439. build.WithFile("Dockerfile", `FROM busybox
  440. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  441. RUN echo 'dockerio:x:1001:' >> /etc/group
  442. RUN mkdir /exists
  443. RUN touch /exists/exists_file
  444. RUN chown -R dockerio.dockerio /exists
  445. ADD test_file /exists/
  446. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  447. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  448. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  449. build.WithFile("test_file", "test1")))
  450. }
  451. func (s *DockerCLIBuildSuite) TestBuildCopyAddMultipleFiles(c *testing.T) {
  452. testRequires(c, DaemonIsLinux) // Linux specific test
  453. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  454. "robots.txt": "hello",
  455. }))
  456. defer server.Close()
  457. cli.BuildCmd(c, "testcopymultiplefilestofile", build.WithBuildContext(c,
  458. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  459. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  460. RUN echo 'dockerio:x:1001:' >> /etc/group
  461. RUN mkdir /exists
  462. RUN touch /exists/exists_file
  463. RUN chown -R dockerio.dockerio /exists
  464. COPY test_file1 test_file2 /exists/
  465. ADD test_file3 test_file4 %s/robots.txt /exists/
  466. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  467. RUN [ $(ls -l /exists/test_file1 | awk '{print $3":"$4}') = 'root:root' ]
  468. RUN [ $(ls -l /exists/test_file2 | awk '{print $3":"$4}') = 'root:root' ]
  469. RUN [ $(ls -l /exists/test_file3 | awk '{print $3":"$4}') = 'root:root' ]
  470. RUN [ $(ls -l /exists/test_file4 | awk '{print $3":"$4}') = 'root:root' ]
  471. RUN [ $(ls -l /exists/robots.txt | awk '{print $3":"$4}') = 'root:root' ]
  472. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  473. `, server.URL())),
  474. build.WithFile("test_file1", "test1"),
  475. build.WithFile("test_file2", "test2"),
  476. build.WithFile("test_file3", "test3"),
  477. build.WithFile("test_file3", "test3"),
  478. build.WithFile("test_file4", "test4")))
  479. }
  480. // These tests are mainly for user namespaces to verify that new directories
  481. // are created as the remapped root uid/gid pair
  482. func (s *DockerCLIBuildSuite) TestBuildUsernamespaceValidateRemappedRoot(c *testing.T) {
  483. testRequires(c, DaemonIsLinux)
  484. testCases := []string{
  485. "ADD . /new_dir",
  486. "COPY test_dir /new_dir",
  487. "WORKDIR /new_dir",
  488. }
  489. const name = "testbuildusernamespacevalidateremappedroot"
  490. for _, tc := range testCases {
  491. cli.BuildCmd(c, name, build.WithBuildContext(c,
  492. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  493. %s
  494. RUN [ $(ls -l / | grep new_dir | awk '{print $3":"$4}') = 'root:root' ]`, tc)),
  495. build.WithFile("test_dir/test_file", "test file")))
  496. cli.DockerCmd(c, "rmi", name)
  497. }
  498. }
  499. func (s *DockerCLIBuildSuite) TestBuildAddAndCopyFileWithWhitespace(c *testing.T) {
  500. testRequires(c, DaemonIsLinux) // Not currently passing on Windows
  501. const name = "testaddfilewithwhitespace"
  502. for _, command := range []string{"ADD", "COPY"} {
  503. cli.BuildCmd(c, name, build.WithBuildContext(c,
  504. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  505. RUN mkdir "/test dir"
  506. RUN mkdir "/test_dir"
  507. %s [ "test file1", "/test_file1" ]
  508. %s [ "test_file2", "/test file2" ]
  509. %s [ "test file3", "/test file3" ]
  510. %s [ "test dir/test_file4", "/test_dir/test_file4" ]
  511. %s [ "test_dir/test_file5", "/test dir/test_file5" ]
  512. %s [ "test dir/test_file6", "/test dir/test_file6" ]
  513. RUN [ $(cat "/test_file1") = 'test1' ]
  514. RUN [ $(cat "/test file2") = 'test2' ]
  515. RUN [ $(cat "/test file3") = 'test3' ]
  516. RUN [ $(cat "/test_dir/test_file4") = 'test4' ]
  517. RUN [ $(cat "/test dir/test_file5") = 'test5' ]
  518. RUN [ $(cat "/test dir/test_file6") = 'test6' ]`, command, command, command, command, command, command)),
  519. build.WithFile("test file1", "test1"),
  520. build.WithFile("test_file2", "test2"),
  521. build.WithFile("test file3", "test3"),
  522. build.WithFile("test dir/test_file4", "test4"),
  523. build.WithFile("test_dir/test_file5", "test5"),
  524. build.WithFile("test dir/test_file6", "test6"),
  525. ))
  526. cli.DockerCmd(c, "rmi", name)
  527. }
  528. }
  529. func (s *DockerCLIBuildSuite) TestBuildCopyFileWithWhitespaceOnWindows(c *testing.T) {
  530. testRequires(c, DaemonIsWindows)
  531. dockerfile := `FROM ` + testEnv.PlatformDefaults.BaseImage + `
  532. RUN mkdir "C:/test dir"
  533. RUN mkdir "C:/test_dir"
  534. COPY [ "test file1", "/test_file1" ]
  535. COPY [ "test_file2", "/test file2" ]
  536. COPY [ "test file3", "/test file3" ]
  537. COPY [ "test dir/test_file4", "/test_dir/test_file4" ]
  538. COPY [ "test_dir/test_file5", "/test dir/test_file5" ]
  539. COPY [ "test dir/test_file6", "/test dir/test_file6" ]
  540. RUN find "test1" "C:/test_file1"
  541. RUN find "test2" "C:/test file2"
  542. RUN find "test3" "C:/test file3"
  543. RUN find "test4" "C:/test_dir/test_file4"
  544. RUN find "test5" "C:/test dir/test_file5"
  545. RUN find "test6" "C:/test dir/test_file6"`
  546. const name = "testcopyfilewithwhitespace"
  547. cli.BuildCmd(c, name, build.WithBuildContext(c,
  548. build.WithFile("Dockerfile", dockerfile),
  549. build.WithFile("test file1", "test1"),
  550. build.WithFile("test_file2", "test2"),
  551. build.WithFile("test file3", "test3"),
  552. build.WithFile("test dir/test_file4", "test4"),
  553. build.WithFile("test_dir/test_file5", "test5"),
  554. build.WithFile("test dir/test_file6", "test6"),
  555. ))
  556. }
  557. func (s *DockerCLIBuildSuite) TestBuildCopyWildcard(c *testing.T) {
  558. const name = "testcopywildcard"
  559. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  560. "robots.txt": "hello",
  561. "index.html": "world",
  562. }))
  563. defer server.Close()
  564. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM busybox
  565. COPY file*.txt /tmp/
  566. RUN ls /tmp/file1.txt /tmp/file2.txt
  567. RUN [ "mkdir", "/tmp1" ]
  568. COPY dir* /tmp1/
  569. RUN ls /tmp1/dirt /tmp1/nested_file /tmp1/nested_dir/nest_nest_file
  570. RUN [ "mkdir", "/tmp2" ]
  571. ADD dir/*dir %s/robots.txt /tmp2/
  572. RUN ls /tmp2/nest_nest_file /tmp2/robots.txt
  573. `, server.URL())),
  574. fakecontext.WithFiles(map[string]string{
  575. "file1.txt": "test1",
  576. "file2.txt": "test2",
  577. "dir/nested_file": "nested file",
  578. "dir/nested_dir/nest_nest_file": "2 times nested",
  579. "dirt": "dirty",
  580. }))
  581. defer ctx.Close()
  582. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  583. id1 := getIDByName(c, name)
  584. // Now make sure we use a cache the 2nd time
  585. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  586. id2 := getIDByName(c, name)
  587. if id1 != id2 {
  588. c.Fatal("didn't use the cache")
  589. }
  590. }
  591. func (s *DockerCLIBuildSuite) TestBuildCopyWildcardInName(c *testing.T) {
  592. // Run this only on Linux
  593. // Below is the original comment (that I don't agree with — vdemeester)
  594. // Normally we would do c.Fatal(err) here but given that
  595. // the odds of this failing are so rare, it must be because
  596. // the OS we're running the client on doesn't support * in
  597. // filenames (like windows). So, instead of failing the test
  598. // just let it pass. Then we don't need to explicitly
  599. // say which OSs this works on or not.
  600. testRequires(c, DaemonIsLinux, UnixCli)
  601. buildImageSuccessfully(c, "testcopywildcardinname", build.WithBuildContext(c,
  602. build.WithFile("Dockerfile", `FROM busybox
  603. COPY *.txt /tmp/
  604. RUN [ "$(cat /tmp/\*.txt)" = 'hi there' ]
  605. `),
  606. build.WithFile("*.txt", "hi there"),
  607. ))
  608. }
  609. func (s *DockerCLIBuildSuite) TestBuildCopyWildcardCache(c *testing.T) {
  610. const name = "testcopywildcardcache"
  611. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  612. COPY file1.txt /tmp/`),
  613. fakecontext.WithFiles(map[string]string{
  614. "file1.txt": "test1",
  615. }))
  616. defer ctx.Close()
  617. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  618. id1 := getIDByName(c, name)
  619. // Now make sure we use a cache the 2nd time even with wild cards.
  620. // Use the same context so the file is the same and the checksum will match
  621. ctx.Add("Dockerfile", `FROM busybox
  622. COPY file*.txt /tmp/`)
  623. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  624. id2 := getIDByName(c, name)
  625. if id1 != id2 {
  626. c.Fatal("didn't use the cache")
  627. }
  628. }
  629. func (s *DockerCLIBuildSuite) TestBuildAddSingleFileToNonExistingDir(c *testing.T) {
  630. testRequires(c, DaemonIsLinux) // Linux specific test
  631. buildImageSuccessfully(c, "testaddsinglefiletononexistingdir", build.WithBuildContext(c,
  632. build.WithFile("Dockerfile", `FROM busybox
  633. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  634. RUN echo 'dockerio:x:1001:' >> /etc/group
  635. RUN touch /exists
  636. RUN chown dockerio.dockerio /exists
  637. ADD test_file /test_dir/
  638. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  639. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  640. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  641. build.WithFile("test_file", "test1")))
  642. }
  643. func (s *DockerCLIBuildSuite) TestBuildAddDirContentToRoot(c *testing.T) {
  644. testRequires(c, DaemonIsLinux) // Linux specific test
  645. buildImageSuccessfully(c, "testadddircontenttoroot", build.WithBuildContext(c,
  646. build.WithFile("Dockerfile", `FROM busybox
  647. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  648. RUN echo 'dockerio:x:1001:' >> /etc/group
  649. RUN touch /exists
  650. RUN chown dockerio.dockerio exists
  651. ADD test_dir /
  652. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  653. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  654. build.WithFile("test_dir/test_file", "test1")))
  655. }
  656. func (s *DockerCLIBuildSuite) TestBuildAddDirContentToExistingDir(c *testing.T) {
  657. testRequires(c, DaemonIsLinux) // Linux specific test
  658. buildImageSuccessfully(c, "testadddircontenttoexistingdir", build.WithBuildContext(c,
  659. build.WithFile("Dockerfile", `FROM busybox
  660. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  661. RUN echo 'dockerio:x:1001:' >> /etc/group
  662. RUN mkdir /exists
  663. RUN touch /exists/exists_file
  664. RUN chown -R dockerio.dockerio /exists
  665. ADD test_dir/ /exists/
  666. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  667. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  668. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`),
  669. build.WithFile("test_dir/test_file", "test1")))
  670. }
  671. func (s *DockerCLIBuildSuite) TestBuildAddWholeDirToRoot(c *testing.T) {
  672. testRequires(c, DaemonIsLinux) // Linux specific test
  673. buildImageSuccessfully(c, "testaddwholedirtoroot", build.WithBuildContext(c,
  674. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  675. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  676. RUN echo 'dockerio:x:1001:' >> /etc/group
  677. RUN touch /exists
  678. RUN chown dockerio.dockerio exists
  679. ADD test_dir /test_dir
  680. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  681. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  682. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  683. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  684. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  685. build.WithFile("test_dir/test_file", "test1")))
  686. }
  687. // Testing #5941 : Having an etc directory in context conflicts with the /etc/mtab
  688. func (s *DockerCLIBuildSuite) TestBuildAddOrCopyEtcToRootShouldNotConflict(c *testing.T) {
  689. buildImageSuccessfully(c, "testaddetctoroot", build.WithBuildContext(c,
  690. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  691. ADD . /`),
  692. build.WithFile("etc/test_file", "test1")))
  693. buildImageSuccessfully(c, "testcopyetctoroot", build.WithBuildContext(c,
  694. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  695. COPY . /`),
  696. build.WithFile("etc/test_file", "test1")))
  697. }
  698. // Testing #9401 : Losing setuid flag after a ADD
  699. func (s *DockerCLIBuildSuite) TestBuildAddPreservesFilesSpecialBits(c *testing.T) {
  700. testRequires(c, DaemonIsLinux) // Linux specific test
  701. buildImageSuccessfully(c, "testaddetctoroot", build.WithBuildContext(c,
  702. build.WithFile("Dockerfile", `FROM busybox
  703. ADD suidbin /usr/bin/suidbin
  704. RUN chmod 4755 /usr/bin/suidbin
  705. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
  706. ADD ./data/ /
  707. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`),
  708. build.WithFile("suidbin", "suidbin"),
  709. build.WithFile("/data/usr/test_file", "test1")))
  710. }
  711. func (s *DockerCLIBuildSuite) TestBuildCopySingleFileToRoot(c *testing.T) {
  712. testRequires(c, DaemonIsLinux) // Linux specific test
  713. buildImageSuccessfully(c, "testcopysinglefiletoroot", build.WithBuildContext(c,
  714. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  715. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  716. RUN echo 'dockerio:x:1001:' >> /etc/group
  717. RUN touch /exists
  718. RUN chown dockerio.dockerio /exists
  719. COPY test_file /
  720. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  721. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  722. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  723. build.WithFile("test_file", "test1")))
  724. }
  725. // Issue #3960: "ADD src ." hangs - adapted for COPY
  726. func (s *DockerCLIBuildSuite) TestBuildCopySingleFileToWorkdir(c *testing.T) {
  727. const name = "testcopysinglefiletoworkdir"
  728. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  729. COPY test_file .`),
  730. fakecontext.WithFiles(map[string]string{
  731. "test_file": "test1",
  732. }))
  733. defer ctx.Close()
  734. errChan := make(chan error, 1)
  735. go func() {
  736. errChan <- buildImage(name, build.WithExternalBuildContext(ctx)).Error
  737. close(errChan)
  738. }()
  739. select {
  740. case <-time.After(15 * time.Second):
  741. c.Fatal("Build with adding to workdir timed out")
  742. case err := <-errChan:
  743. assert.NilError(c, err)
  744. }
  745. }
  746. func (s *DockerCLIBuildSuite) TestBuildCopySingleFileToExistDir(c *testing.T) {
  747. testRequires(c, DaemonIsLinux) // Linux specific test
  748. buildImageSuccessfully(c, "testcopysinglefiletoexistdir", build.WithBuildContext(c,
  749. build.WithFile("Dockerfile", `FROM busybox
  750. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  751. RUN echo 'dockerio:x:1001:' >> /etc/group
  752. RUN mkdir /exists
  753. RUN touch /exists/exists_file
  754. RUN chown -R dockerio.dockerio /exists
  755. COPY test_file /exists/
  756. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  757. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  758. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  759. build.WithFile("test_file", "test1")))
  760. }
  761. func (s *DockerCLIBuildSuite) TestBuildCopySingleFileToNonExistDir(c *testing.T) {
  762. testRequires(c, DaemonIsLinux) // Linux specific
  763. buildImageSuccessfully(c, "testcopysinglefiletononexistdir", build.WithBuildContext(c,
  764. build.WithFile("Dockerfile", `FROM busybox
  765. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  766. RUN echo 'dockerio:x:1001:' >> /etc/group
  767. RUN touch /exists
  768. RUN chown dockerio.dockerio /exists
  769. COPY test_file /test_dir/
  770. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  771. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  772. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  773. build.WithFile("test_file", "test1")))
  774. }
  775. func (s *DockerCLIBuildSuite) TestBuildCopyDirContentToRoot(c *testing.T) {
  776. testRequires(c, DaemonIsLinux) // Linux specific test
  777. buildImageSuccessfully(c, "testcopydircontenttoroot", build.WithBuildContext(c,
  778. build.WithFile("Dockerfile", `FROM busybox
  779. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  780. RUN echo 'dockerio:x:1001:' >> /etc/group
  781. RUN touch /exists
  782. RUN chown dockerio.dockerio exists
  783. COPY test_dir /
  784. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  785. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  786. build.WithFile("test_dir/test_file", "test1")))
  787. }
  788. func (s *DockerCLIBuildSuite) TestBuildCopyDirContentToExistDir(c *testing.T) {
  789. testRequires(c, DaemonIsLinux) // Linux specific test
  790. buildImageSuccessfully(c, "testcopydircontenttoexistdir", build.WithBuildContext(c,
  791. build.WithFile("Dockerfile", `FROM busybox
  792. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  793. RUN echo 'dockerio:x:1001:' >> /etc/group
  794. RUN mkdir /exists
  795. RUN touch /exists/exists_file
  796. RUN chown -R dockerio.dockerio /exists
  797. COPY test_dir/ /exists/
  798. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  799. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  800. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`),
  801. build.WithFile("test_dir/test_file", "test1")))
  802. }
  803. func (s *DockerCLIBuildSuite) TestBuildCopyWholeDirToRoot(c *testing.T) {
  804. testRequires(c, DaemonIsLinux) // Linux specific test
  805. buildImageSuccessfully(c, "testcopywholedirtoroot", build.WithBuildContext(c,
  806. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  807. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  808. RUN echo 'dockerio:x:1001:' >> /etc/group
  809. RUN touch /exists
  810. RUN chown dockerio.dockerio exists
  811. COPY test_dir /test_dir
  812. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  813. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  814. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  815. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  816. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  817. build.WithFile("test_dir/test_file", "test1")))
  818. }
  819. func (s *DockerCLIBuildSuite) TestBuildAddBadLinks(c *testing.T) {
  820. testRequires(c, DaemonIsLinux) // Not currently working on Windows
  821. dockerfile := `
  822. FROM scratch
  823. ADD links.tar /
  824. ADD foo.txt /symlink/
  825. `
  826. targetFile := "foo.txt"
  827. const name = "test-link-absolute"
  828. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  829. defer ctx.Close()
  830. tempDir, err := os.MkdirTemp("", "test-link-absolute-temp-")
  831. if err != nil {
  832. c.Fatalf("failed to create temporary directory: %s", tempDir)
  833. }
  834. defer os.RemoveAll(tempDir)
  835. var symlinkTarget string
  836. if runtime.GOOS == "windows" {
  837. var driveLetter string
  838. if abs, err := filepath.Abs(tempDir); err != nil {
  839. c.Fatal(err)
  840. } else {
  841. driveLetter = abs[:1]
  842. }
  843. tempDirWithoutDrive := tempDir[2:]
  844. symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive)
  845. } else {
  846. symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
  847. }
  848. tarPath := filepath.Join(ctx.Dir, "links.tar")
  849. nonExistingFile := filepath.Join(tempDir, targetFile)
  850. fooPath := filepath.Join(ctx.Dir, targetFile)
  851. tarOut, err := os.Create(tarPath)
  852. if err != nil {
  853. c.Fatal(err)
  854. }
  855. tarWriter := tar.NewWriter(tarOut)
  856. header := &tar.Header{
  857. Name: "symlink",
  858. Typeflag: tar.TypeSymlink,
  859. Linkname: symlinkTarget,
  860. Mode: 0o755,
  861. Uid: 0,
  862. Gid: 0,
  863. }
  864. err = tarWriter.WriteHeader(header)
  865. if err != nil {
  866. c.Fatal(err)
  867. }
  868. tarWriter.Close()
  869. tarOut.Close()
  870. foo, err := os.Create(fooPath)
  871. if err != nil {
  872. c.Fatal(err)
  873. }
  874. defer foo.Close()
  875. if _, err := foo.WriteString("test"); err != nil {
  876. c.Fatal(err)
  877. }
  878. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  879. if _, err := os.Stat(nonExistingFile); err == nil || !os.IsNotExist(err) {
  880. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  881. }
  882. }
  883. func (s *DockerCLIBuildSuite) TestBuildAddBadLinksVolume(c *testing.T) {
  884. testRequires(c, DaemonIsLinux) // ln not implemented on Windows busybox
  885. const (
  886. dockerfileTemplate = `
  887. FROM busybox
  888. RUN ln -s /../../../../../../../../%s /x
  889. VOLUME /x
  890. ADD foo.txt /x/`
  891. targetFile = "foo.txt"
  892. )
  893. tempDir, err := os.MkdirTemp("", "test-link-absolute-volume-temp-")
  894. if err != nil {
  895. c.Fatalf("failed to create temporary directory: %s", tempDir)
  896. }
  897. defer os.RemoveAll(tempDir)
  898. dockerfile := fmt.Sprintf(dockerfileTemplate, tempDir)
  899. nonExistingFile := filepath.Join(tempDir, targetFile)
  900. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  901. defer ctx.Close()
  902. fooPath := filepath.Join(ctx.Dir, targetFile)
  903. foo, err := os.Create(fooPath)
  904. if err != nil {
  905. c.Fatal(err)
  906. }
  907. defer foo.Close()
  908. if _, err := foo.WriteString("test"); err != nil {
  909. c.Fatal(err)
  910. }
  911. buildImageSuccessfully(c, "test-link-absolute-volume", build.WithExternalBuildContext(ctx))
  912. if _, err := os.Stat(nonExistingFile); err == nil || !os.IsNotExist(err) {
  913. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  914. }
  915. }
  916. // Issue #5270 - ensure we throw a better error than "unexpected EOF"
  917. // when we can't access files in the context.
  918. func (s *DockerCLIBuildSuite) TestBuildWithInaccessibleFilesInContext(c *testing.T) {
  919. testRequires(c, DaemonIsLinux, UnixCli, testEnv.IsLocalDaemon) // test uses chown/chmod: not available on windows
  920. {
  921. const name = "testbuildinaccessiblefiles"
  922. ctx := fakecontext.New(c, "",
  923. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  924. fakecontext.WithFiles(map[string]string{"fileWithoutReadAccess": "foo"}),
  925. )
  926. defer ctx.Close()
  927. // This is used to ensure we detect inaccessible files early during build in the cli client
  928. pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess")
  929. if err := os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil {
  930. c.Fatalf("failed to chown file to root: %s", err)
  931. }
  932. if err := os.Chmod(pathToFileWithoutReadAccess, 0o700); err != nil {
  933. c.Fatalf("failed to chmod file to 700: %s", err)
  934. }
  935. result := icmd.RunCmd(icmd.Cmd{
  936. Command: []string{"su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  937. Dir: ctx.Dir,
  938. })
  939. if result.Error == nil {
  940. c.Fatalf("build should have failed: %s %s", result.Error, result.Combined())
  941. }
  942. // check if we've detected the failure before we started building
  943. if !strings.Contains(result.Combined(), "no permission to read from ") {
  944. c.Fatalf("output should've contained the string: no permission to read from but contained: %s", result.Combined())
  945. }
  946. if !strings.Contains(result.Combined(), "error checking context") {
  947. c.Fatalf("output should've contained the string: error checking context")
  948. }
  949. }
  950. {
  951. const name = "testbuildinaccessibledirectory"
  952. ctx := fakecontext.New(c, "",
  953. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  954. fakecontext.WithFiles(map[string]string{"directoryWeCantStat/bar": "foo"}),
  955. )
  956. defer ctx.Close()
  957. // This is used to ensure we detect inaccessible directories early during build in the cli client
  958. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  959. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  960. if err := os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  961. c.Fatalf("failed to chown directory to root: %s", err)
  962. }
  963. if err := os.Chmod(pathToDirectoryWithoutReadAccess, 0o444); err != nil {
  964. c.Fatalf("failed to chmod directory to 444: %s", err)
  965. }
  966. if err := os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0o700); err != nil {
  967. c.Fatalf("failed to chmod file to 700: %s", err)
  968. }
  969. result := icmd.RunCmd(icmd.Cmd{
  970. Command: []string{"su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  971. Dir: ctx.Dir,
  972. })
  973. if result.Error == nil {
  974. c.Fatalf("build should have failed: %s %s", result.Error, result.Combined())
  975. }
  976. // check if we've detected the failure before we started building
  977. if !strings.Contains(result.Combined(), "can't stat") {
  978. c.Fatalf("output should've contained the string: can't access %s", result.Combined())
  979. }
  980. if !strings.Contains(result.Combined(), "error checking context") {
  981. c.Fatalf("output should've contained the string: error checking context\ngot:%s", result.Combined())
  982. }
  983. }
  984. {
  985. const name = "testlinksok"
  986. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"))
  987. defer ctx.Close()
  988. target := "../../../../../../../../../../../../../../../../../../../azA"
  989. if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil {
  990. c.Fatal(err)
  991. }
  992. defer os.Remove(target)
  993. // This is used to ensure we don't follow links when checking if everything in the context is accessible
  994. // This test doesn't require that we run commands as an unprivileged user
  995. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  996. }
  997. {
  998. const name = "testbuildignoredinaccessible"
  999. ctx := fakecontext.New(c, "",
  1000. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  1001. fakecontext.WithFiles(map[string]string{
  1002. "directoryWeCantStat/bar": "foo",
  1003. ".dockerignore": "directoryWeCantStat",
  1004. }),
  1005. )
  1006. defer ctx.Close()
  1007. // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern
  1008. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1009. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1010. if err := os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1011. c.Fatalf("failed to chown directory to root: %s", err)
  1012. }
  1013. if err := os.Chmod(pathToDirectoryWithoutReadAccess, 0o444); err != nil {
  1014. c.Fatalf("failed to chmod directory to 444: %s", err)
  1015. }
  1016. if err := os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0o700); err != nil {
  1017. c.Fatalf("failed to chmod file to 700: %s", err)
  1018. }
  1019. result := icmd.RunCmd(icmd.Cmd{
  1020. Dir: ctx.Dir,
  1021. Command: []string{
  1022. "su", "unprivilegeduser", "-c",
  1023. fmt.Sprintf("%s build -t %s .", dockerBinary, name),
  1024. },
  1025. })
  1026. result.Assert(c, icmd.Expected{})
  1027. }
  1028. }
  1029. func (s *DockerCLIBuildSuite) TestBuildForceRm(c *testing.T) {
  1030. containerCountBefore := getContainerCount(c)
  1031. const name = "testbuildforcerm"
  1032. r := buildImage(name, cli.WithFlags("--force-rm"), build.WithBuildContext(c,
  1033. build.WithFile("Dockerfile", `FROM busybox
  1034. RUN true
  1035. RUN thiswillfail`)))
  1036. if r.ExitCode != 1 && r.ExitCode != 127 { // different on Linux / Windows
  1037. c.Fatalf("Wrong exit code")
  1038. }
  1039. containerCountAfter := getContainerCount(c)
  1040. if containerCountBefore != containerCountAfter {
  1041. c.Fatalf("--force-rm shouldn't have left containers behind")
  1042. }
  1043. }
  1044. func (s *DockerCLIBuildSuite) TestBuildRm(c *testing.T) {
  1045. const name = "testbuildrm"
  1046. testCases := []struct {
  1047. buildflags []string
  1048. shouldLeftContainerBehind bool
  1049. }{
  1050. // Default case (i.e. --rm=true)
  1051. {
  1052. buildflags: []string{},
  1053. shouldLeftContainerBehind: false,
  1054. },
  1055. {
  1056. buildflags: []string{"--rm"},
  1057. shouldLeftContainerBehind: false,
  1058. },
  1059. {
  1060. buildflags: []string{"--rm=false"},
  1061. shouldLeftContainerBehind: true,
  1062. },
  1063. }
  1064. for _, tc := range testCases {
  1065. containerCountBefore := getContainerCount(c)
  1066. buildImageSuccessfully(c, name, cli.WithFlags(tc.buildflags...), build.WithDockerfile(`FROM busybox
  1067. RUN echo hello world`))
  1068. containerCountAfter := getContainerCount(c)
  1069. if tc.shouldLeftContainerBehind {
  1070. if containerCountBefore == containerCountAfter {
  1071. c.Fatalf("flags %v should have left containers behind", tc.buildflags)
  1072. }
  1073. } else {
  1074. if containerCountBefore != containerCountAfter {
  1075. c.Fatalf("flags %v shouldn't have left containers behind", tc.buildflags)
  1076. }
  1077. }
  1078. cli.DockerCmd(c, "rmi", name)
  1079. }
  1080. }
  1081. func (s *DockerCLIBuildSuite) TestBuildWithVolumes(c *testing.T) {
  1082. testRequires(c, DaemonIsLinux) // Invalid volume paths on Windows
  1083. var (
  1084. result map[string]map[string]struct{}
  1085. name = "testbuildvolumes"
  1086. emptyMap = make(map[string]struct{})
  1087. expected = map[string]map[string]struct{}{
  1088. "/test1": emptyMap,
  1089. "/test2": emptyMap,
  1090. "/test3": emptyMap,
  1091. "/test4": emptyMap,
  1092. "/test5": emptyMap,
  1093. "/test6": emptyMap,
  1094. "[/test7": emptyMap,
  1095. "/test8]": emptyMap,
  1096. }
  1097. )
  1098. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1099. VOLUME /test1
  1100. VOLUME /test2
  1101. VOLUME /test3 /test4
  1102. VOLUME ["/test5", "/test6"]
  1103. VOLUME [/test7 /test8]
  1104. `))
  1105. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &result)
  1106. equal := reflect.DeepEqual(&result, &expected)
  1107. if !equal {
  1108. c.Fatalf("Volumes %s, expected %s", result, expected)
  1109. }
  1110. }
  1111. func (s *DockerCLIBuildSuite) TestBuildMaintainer(c *testing.T) {
  1112. const name = "testbuildmaintainer"
  1113. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1114. MAINTAINER dockerio`))
  1115. expected := "dockerio"
  1116. res := inspectField(c, name, "Author")
  1117. if res != expected {
  1118. c.Fatalf("Maintainer %s, expected %s", res, expected)
  1119. }
  1120. }
  1121. func (s *DockerCLIBuildSuite) TestBuildUser(c *testing.T) {
  1122. testRequires(c, DaemonIsLinux)
  1123. const name = "testbuilduser"
  1124. expected := "dockerio"
  1125. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1126. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1127. USER dockerio
  1128. RUN [ $(whoami) = 'dockerio' ]`))
  1129. res := inspectField(c, name, "Config.User")
  1130. if res != expected {
  1131. c.Fatalf("User %s, expected %s", res, expected)
  1132. }
  1133. }
  1134. func (s *DockerCLIBuildSuite) TestBuildRelativeWorkdir(c *testing.T) {
  1135. const name = "testbuildrelativeworkdir"
  1136. var (
  1137. expected1 string
  1138. expected2 string
  1139. expected3 string
  1140. expected4 string
  1141. expectedFinal string
  1142. )
  1143. if testEnv.DaemonInfo.OSType == "windows" {
  1144. expected1 = `C:/`
  1145. expected2 = `C:/test1`
  1146. expected3 = `C:/test2`
  1147. expected4 = `C:/test2/test3`
  1148. expectedFinal = `C:\test2\test3` // Note inspect is going to return Windows paths, as it's not in busybox
  1149. } else {
  1150. expected1 = `/`
  1151. expected2 = `/test1`
  1152. expected3 = `/test2`
  1153. expected4 = `/test2/test3`
  1154. expectedFinal = `/test2/test3`
  1155. }
  1156. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1157. RUN sh -c "[ "$PWD" = "`+expected1+`" ]"
  1158. WORKDIR test1
  1159. RUN sh -c "[ "$PWD" = "`+expected2+`" ]"
  1160. WORKDIR /test2
  1161. RUN sh -c "[ "$PWD" = "`+expected3+`" ]"
  1162. WORKDIR test3
  1163. RUN sh -c "[ "$PWD" = "`+expected4+`" ]"`))
  1164. res := inspectField(c, name, "Config.WorkingDir")
  1165. if res != expectedFinal {
  1166. c.Fatalf("Workdir %s, expected %s", res, expectedFinal)
  1167. }
  1168. }
  1169. // #22181 Regression test. Single end-to-end test of using
  1170. // Windows semantics. Most path handling verifications are in unit tests
  1171. func (s *DockerCLIBuildSuite) TestBuildWindowsWorkdirProcessing(c *testing.T) {
  1172. testRequires(c, DaemonIsWindows)
  1173. buildImageSuccessfully(c, "testbuildwindowsworkdirprocessing", build.WithDockerfile(`FROM busybox
  1174. WORKDIR C:\\foo
  1175. WORKDIR bar
  1176. RUN sh -c "[ "$PWD" = "C:/foo/bar" ]"
  1177. `))
  1178. }
  1179. // #22181 Regression test. Most paths handling verifications are in unit test.
  1180. // One functional test for end-to-end
  1181. func (s *DockerCLIBuildSuite) TestBuildWindowsAddCopyPathProcessing(c *testing.T) {
  1182. testRequires(c, DaemonIsWindows)
  1183. // TODO Windows. Needs a follow-up PR to 22181 to
  1184. // support backslash such as .\\ being equivalent to ./ and c:\\ being
  1185. // equivalent to c:/. This is not currently (nor ever has been) supported
  1186. // by docker on the Windows platform.
  1187. buildImageSuccessfully(c, "testbuildwindowsaddcopypathprocessing", build.WithBuildContext(c,
  1188. build.WithFile("Dockerfile", `FROM busybox
  1189. # No trailing slash on COPY/ADD
  1190. # Results in dir being changed to a file
  1191. WORKDIR /wc1
  1192. COPY wc1 c:/wc1
  1193. WORKDIR /wc2
  1194. ADD wc2 c:/wc2
  1195. WORKDIR c:/
  1196. RUN sh -c "[ $(cat c:/wc1/wc1) = 'hellowc1' ]"
  1197. RUN sh -c "[ $(cat c:/wc2/wc2) = 'worldwc2' ]"
  1198. # Trailing slash on COPY/ADD, Windows-style path.
  1199. WORKDIR /wd1
  1200. COPY wd1 c:/wd1/
  1201. WORKDIR /wd2
  1202. ADD wd2 c:/wd2/
  1203. RUN sh -c "[ $(cat c:/wd1/wd1) = 'hellowd1' ]"
  1204. RUN sh -c "[ $(cat c:/wd2/wd2) = 'worldwd2' ]"
  1205. `),
  1206. build.WithFile("wc1", "hellowc1"),
  1207. build.WithFile("wc2", "worldwc2"),
  1208. build.WithFile("wd1", "hellowd1"),
  1209. build.WithFile("wd2", "worldwd2"),
  1210. ))
  1211. }
  1212. func (s *DockerCLIBuildSuite) TestBuildWorkdirWithEnvVariables(c *testing.T) {
  1213. const name = "testbuildworkdirwithenvvariables"
  1214. var expected string
  1215. if testEnv.DaemonInfo.OSType == "windows" {
  1216. expected = `C:\test1\test2`
  1217. } else {
  1218. expected = `/test1/test2`
  1219. }
  1220. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1221. ENV DIRPATH /test1
  1222. ENV SUBDIRNAME test2
  1223. WORKDIR $DIRPATH
  1224. WORKDIR $SUBDIRNAME/$MISSING_VAR`))
  1225. res := inspectField(c, name, "Config.WorkingDir")
  1226. if res != expected {
  1227. c.Fatalf("Workdir %s, expected %s", res, expected)
  1228. }
  1229. }
  1230. func (s *DockerCLIBuildSuite) TestBuildRelativeCopy(c *testing.T) {
  1231. // cat /test1/test2/foo gets permission denied for the user
  1232. testRequires(c, NotUserNamespace)
  1233. var expected string
  1234. if testEnv.DaemonInfo.OSType == "windows" {
  1235. expected = `C:/test1/test2`
  1236. } else {
  1237. expected = `/test1/test2`
  1238. }
  1239. buildImageSuccessfully(c, "testbuildrelativecopy", build.WithBuildContext(c,
  1240. build.WithFile("Dockerfile", `FROM busybox
  1241. WORKDIR /test1
  1242. WORKDIR test2
  1243. RUN sh -c "[ "$PWD" = '`+expected+`' ]"
  1244. COPY foo ./
  1245. RUN sh -c "[ $(cat /test1/test2/foo) = 'hello' ]"
  1246. ADD foo ./bar/baz
  1247. RUN sh -c "[ $(cat /test1/test2/bar/baz) = 'hello' ]"
  1248. COPY foo ./bar/baz2
  1249. RUN sh -c "[ $(cat /test1/test2/bar/baz2) = 'hello' ]"
  1250. WORKDIR ..
  1251. COPY foo ./
  1252. RUN sh -c "[ $(cat /test1/foo) = 'hello' ]"
  1253. COPY foo /test3/
  1254. RUN sh -c "[ $(cat /test3/foo) = 'hello' ]"
  1255. WORKDIR /test4
  1256. COPY . .
  1257. RUN sh -c "[ $(cat /test4/foo) = 'hello' ]"
  1258. WORKDIR /test5/test6
  1259. COPY foo ../
  1260. RUN sh -c "[ $(cat /test5/foo) = 'hello' ]"
  1261. `),
  1262. build.WithFile("foo", "hello"),
  1263. ))
  1264. }
  1265. // FIXME(vdemeester) should be unit test
  1266. func (s *DockerCLIBuildSuite) TestBuildBlankName(c *testing.T) {
  1267. const name = "testbuildblankname"
  1268. testCases := []struct {
  1269. expression string
  1270. expectedStderr string
  1271. }{
  1272. {
  1273. expression: "ENV =",
  1274. expectedStderr: "ENV names can not be blank",
  1275. },
  1276. {
  1277. expression: "LABEL =",
  1278. expectedStderr: "LABEL names can not be blank",
  1279. },
  1280. {
  1281. expression: "ARG =foo",
  1282. expectedStderr: "ARG names can not be blank",
  1283. },
  1284. }
  1285. for _, tc := range testCases {
  1286. buildImage(name, build.WithDockerfile(fmt.Sprintf(`FROM busybox
  1287. %s`, tc.expression))).Assert(c, icmd.Expected{
  1288. ExitCode: 1,
  1289. Err: tc.expectedStderr,
  1290. })
  1291. }
  1292. }
  1293. func (s *DockerCLIBuildSuite) TestBuildEnv(c *testing.T) {
  1294. testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows
  1295. const name = "testbuildenv"
  1296. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  1297. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1298. ENV PATH /test:$PATH
  1299. ENV PORT 2375
  1300. RUN [ $(env | grep PORT) = 'PORT=2375' ]`))
  1301. res := inspectField(c, name, "Config.Env")
  1302. if res != expected {
  1303. c.Fatalf("Env %s, expected %s", res, expected)
  1304. }
  1305. }
  1306. func (s *DockerCLIBuildSuite) TestBuildPATH(c *testing.T) {
  1307. testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows
  1308. defPath := "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  1309. fn := func(dockerfile string, expected string) {
  1310. buildImageSuccessfully(c, "testbldpath", build.WithDockerfile(dockerfile))
  1311. res := inspectField(c, "testbldpath", "Config.Env")
  1312. if res != expected {
  1313. c.Fatalf("Env %q, expected %q for dockerfile:%q", res, expected, dockerfile)
  1314. }
  1315. }
  1316. tests := []struct{ dockerfile, exp string }{
  1317. {"FROM scratch\nMAINTAINER me", "[PATH=" + defPath + "]"},
  1318. {"FROM busybox\nMAINTAINER me", "[PATH=" + defPath + "]"},
  1319. {"FROM scratch\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
  1320. {"FROM busybox\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
  1321. {"FROM scratch\nENV PATH=/test", "[PATH=/test]"},
  1322. {"FROM busybox\nENV PATH=/test", "[PATH=/test]"},
  1323. {"FROM scratch\nENV PATH=''", "[PATH=]"},
  1324. {"FROM busybox\nENV PATH=''", "[PATH=]"},
  1325. }
  1326. for _, test := range tests {
  1327. fn(test.dockerfile, test.exp)
  1328. }
  1329. }
  1330. func (s *DockerCLIBuildSuite) TestBuildContextCleanup(c *testing.T) {
  1331. testRequires(c, testEnv.IsLocalDaemon)
  1332. const name = "testbuildcontextcleanup"
  1333. entries, err := os.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp"))
  1334. if err != nil {
  1335. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1336. }
  1337. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1338. ENTRYPOINT ["/bin/echo"]`))
  1339. entriesFinal, err := os.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp"))
  1340. if err != nil {
  1341. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1342. }
  1343. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1344. c.Fatalf("context should have been deleted, but wasn't")
  1345. }
  1346. }
  1347. func (s *DockerCLIBuildSuite) TestBuildContextCleanupFailedBuild(c *testing.T) {
  1348. testRequires(c, testEnv.IsLocalDaemon)
  1349. const name = "testbuildcontextcleanup"
  1350. entries, err := os.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp"))
  1351. if err != nil {
  1352. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1353. }
  1354. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1355. RUN /non/existing/command`)).Assert(c, icmd.Expected{
  1356. ExitCode: 1,
  1357. })
  1358. entriesFinal, err := os.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp"))
  1359. if err != nil {
  1360. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1361. }
  1362. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1363. c.Fatalf("context should have been deleted, but wasn't")
  1364. }
  1365. }
  1366. // compareDirectoryEntries compares two sets of DirEntry (usually taken from a directory)
  1367. // and returns an error if different.
  1368. func compareDirectoryEntries(e1 []os.DirEntry, e2 []os.DirEntry) error {
  1369. var (
  1370. e1Entries = make(map[string]struct{})
  1371. e2Entries = make(map[string]struct{})
  1372. )
  1373. for _, e := range e1 {
  1374. e1Entries[e.Name()] = struct{}{}
  1375. }
  1376. for _, e := range e2 {
  1377. e2Entries[e.Name()] = struct{}{}
  1378. }
  1379. if !reflect.DeepEqual(e1Entries, e2Entries) {
  1380. return fmt.Errorf("entries differ")
  1381. }
  1382. return nil
  1383. }
  1384. func (s *DockerCLIBuildSuite) TestBuildCmd(c *testing.T) {
  1385. const name = "testbuildcmd"
  1386. expected := "[/bin/echo Hello World]"
  1387. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1388. CMD ["/bin/echo", "Hello World"]`))
  1389. res := inspectField(c, name, "Config.Cmd")
  1390. if res != expected {
  1391. c.Fatalf("Cmd %s, expected %s", res, expected)
  1392. }
  1393. }
  1394. func (s *DockerCLIBuildSuite) TestBuildExpose(c *testing.T) {
  1395. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1396. const name = "testbuildexpose"
  1397. expected := "map[2375/tcp:{}]"
  1398. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1399. EXPOSE 2375`))
  1400. res := inspectField(c, name, "Config.ExposedPorts")
  1401. if res != expected {
  1402. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1403. }
  1404. }
  1405. func (s *DockerCLIBuildSuite) TestBuildExposeMorePorts(c *testing.T) {
  1406. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1407. // start building docker file with a large number of ports
  1408. portList := make([]string, 50)
  1409. line := make([]string, 100)
  1410. expectedPorts := make([]int, len(portList)*len(line))
  1411. for i := 0; i < len(portList); i++ {
  1412. for j := 0; j < len(line); j++ {
  1413. p := i*len(line) + j + 1
  1414. line[j] = strconv.Itoa(p)
  1415. expectedPorts[p-1] = p
  1416. }
  1417. if i == len(portList)-1 {
  1418. portList[i] = strings.Join(line, " ")
  1419. } else {
  1420. portList[i] = strings.Join(line, " ") + ` \`
  1421. }
  1422. }
  1423. dockerfile := `FROM scratch
  1424. EXPOSE {{range .}} {{.}}
  1425. {{end}}`
  1426. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  1427. buf := bytes.NewBuffer(nil)
  1428. tmpl.Execute(buf, portList)
  1429. const name = "testbuildexpose"
  1430. buildImageSuccessfully(c, name, build.WithDockerfile(buf.String()))
  1431. // check if all the ports are saved inside Config.ExposedPorts
  1432. res := inspectFieldJSON(c, name, "Config.ExposedPorts")
  1433. var exposedPorts map[string]interface{}
  1434. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  1435. c.Fatal(err)
  1436. }
  1437. for _, p := range expectedPorts {
  1438. ep := fmt.Sprintf("%d/tcp", p)
  1439. if _, ok := exposedPorts[ep]; !ok {
  1440. c.Errorf("Port(%s) is not exposed", ep)
  1441. } else {
  1442. delete(exposedPorts, ep)
  1443. }
  1444. }
  1445. if len(exposedPorts) != 0 {
  1446. c.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  1447. }
  1448. }
  1449. func (s *DockerCLIBuildSuite) TestBuildExposeOrder(c *testing.T) {
  1450. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1451. buildID := func(name, exposed string) string {
  1452. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM scratch
  1453. EXPOSE %s`, exposed)))
  1454. id := inspectField(c, name, "Id")
  1455. return id
  1456. }
  1457. id1 := buildID("testbuildexpose1", "80 2375")
  1458. id2 := buildID("testbuildexpose2", "2375 80")
  1459. if id1 != id2 {
  1460. c.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  1461. }
  1462. }
  1463. func (s *DockerCLIBuildSuite) TestBuildExposeUpperCaseProto(c *testing.T) {
  1464. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1465. const name = "testbuildexposeuppercaseproto"
  1466. expected := "map[5678/udp:{}]"
  1467. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1468. EXPOSE 5678/UDP`))
  1469. res := inspectField(c, name, "Config.ExposedPorts")
  1470. if res != expected {
  1471. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1472. }
  1473. }
  1474. func (s *DockerCLIBuildSuite) TestBuildEmptyEntrypointInheritance(c *testing.T) {
  1475. const name = "testbuildentrypointinheritance"
  1476. const name2 = "testbuildentrypointinheritance2"
  1477. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1478. ENTRYPOINT ["/bin/echo"]`))
  1479. res := inspectField(c, name, "Config.Entrypoint")
  1480. expected := "[/bin/echo]"
  1481. if res != expected {
  1482. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1483. }
  1484. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1485. ENTRYPOINT []`, name)))
  1486. res = inspectField(c, name2, "Config.Entrypoint")
  1487. expected = "[]"
  1488. if res != expected {
  1489. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1490. }
  1491. }
  1492. func (s *DockerCLIBuildSuite) TestBuildEmptyEntrypoint(c *testing.T) {
  1493. const name = "testbuildentrypoint"
  1494. expected := "[]"
  1495. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1496. ENTRYPOINT []`))
  1497. res := inspectField(c, name, "Config.Entrypoint")
  1498. if res != expected {
  1499. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1500. }
  1501. }
  1502. func (s *DockerCLIBuildSuite) TestBuildEntrypoint(c *testing.T) {
  1503. const name = "testbuildentrypoint"
  1504. expected := "[/bin/echo]"
  1505. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1506. ENTRYPOINT ["/bin/echo"]`))
  1507. res := inspectField(c, name, "Config.Entrypoint")
  1508. if res != expected {
  1509. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1510. }
  1511. }
  1512. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  1513. func (s *DockerCLIBuildSuite) TestBuildOnBuildLimitedInheritance(c *testing.T) {
  1514. buildImageSuccessfully(c, "testonbuildtrigger1", build.WithDockerfile(`
  1515. FROM busybox
  1516. RUN echo "GRANDPARENT"
  1517. ONBUILD RUN echo "ONBUILD PARENT"
  1518. `))
  1519. // ONBUILD should be run in second build.
  1520. buildImage("testonbuildtrigger2", build.WithDockerfile("FROM testonbuildtrigger1")).Assert(c, icmd.Expected{
  1521. Out: "ONBUILD PARENT",
  1522. })
  1523. // ONBUILD should *not* be run in third build.
  1524. result := buildImage("testonbuildtrigger3", build.WithDockerfile("FROM testonbuildtrigger2"))
  1525. result.Assert(c, icmd.Success)
  1526. if strings.Contains(result.Combined(), "ONBUILD PARENT") {
  1527. c.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  1528. }
  1529. }
  1530. func (s *DockerCLIBuildSuite) TestBuildSameDockerfileWithAndWithoutCache(c *testing.T) {
  1531. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1532. const name = "testbuildwithcache"
  1533. dockerfile := `FROM scratch
  1534. MAINTAINER dockerio
  1535. EXPOSE 5432
  1536. ENTRYPOINT ["/bin/echo"]`
  1537. buildImageSuccessfully(c, name, build.WithDockerfile(dockerfile))
  1538. id1 := getIDByName(c, name)
  1539. buildImageSuccessfully(c, name, build.WithDockerfile(dockerfile))
  1540. id2 := getIDByName(c, name)
  1541. buildImageSuccessfully(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  1542. id3 := getIDByName(c, name)
  1543. if id1 != id2 {
  1544. c.Fatal("The cache should have been used but hasn't.")
  1545. }
  1546. if id1 == id3 {
  1547. c.Fatal("The cache should have been invalided but hasn't.")
  1548. }
  1549. }
  1550. // Make sure that ADD/COPY still populate the cache even if they don't use it
  1551. func (s *DockerCLIBuildSuite) TestBuildConditionalCache(c *testing.T) {
  1552. const name = "testbuildconditionalcache"
  1553. dockerfile := `
  1554. FROM busybox
  1555. ADD foo /tmp/`
  1556. ctx := fakecontext.New(c, "",
  1557. fakecontext.WithDockerfile(dockerfile),
  1558. fakecontext.WithFiles(map[string]string{
  1559. "foo": "hello",
  1560. }))
  1561. defer ctx.Close()
  1562. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1563. id1 := getIDByName(c, name)
  1564. if err := ctx.Add("foo", "bye"); err != nil {
  1565. c.Fatalf("Error modifying foo: %s", err)
  1566. }
  1567. // Updating a file should invalidate the cache
  1568. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1569. id2 := getIDByName(c, name)
  1570. if id2 == id1 {
  1571. c.Fatal("Should not have used the cache")
  1572. }
  1573. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1574. id3 := getIDByName(c, name)
  1575. if id3 != id2 {
  1576. c.Fatal("Should have used the cache")
  1577. }
  1578. }
  1579. func (s *DockerCLIBuildSuite) TestBuildAddMultipleLocalFileWithAndWithoutCache(c *testing.T) {
  1580. const name = "testbuildaddmultiplelocalfilewithcache"
  1581. baseName := name + "-base"
  1582. cli.BuildCmd(c, baseName, build.WithDockerfile(`
  1583. FROM busybox
  1584. ENTRYPOINT ["/bin/sh"]
  1585. `))
  1586. dockerfile := `
  1587. FROM testbuildaddmultiplelocalfilewithcache-base
  1588. MAINTAINER dockerio
  1589. ADD foo Dockerfile /usr/lib/bla/
  1590. RUN sh -c "[ $(cat /usr/lib/bla/foo) = "hello" ]"`
  1591. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1592. "foo": "hello",
  1593. }))
  1594. defer ctx.Close()
  1595. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1596. id1 := getIDByName(c, name)
  1597. result2 := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1598. id2 := getIDByName(c, name)
  1599. result3 := cli.BuildCmd(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1600. id3 := getIDByName(c, name)
  1601. if id1 != id2 {
  1602. c.Fatalf("The cache should have been used but hasn't: %s", result2.Stdout())
  1603. }
  1604. if id1 == id3 {
  1605. c.Fatalf("The cache should have been invalided but hasn't: %s", result3.Stdout())
  1606. }
  1607. }
  1608. func (s *DockerCLIBuildSuite) TestBuildCopyDirButNotFile(c *testing.T) {
  1609. const name = "testbuildcopydirbutnotfile"
  1610. const name2 = "testbuildcopydirbutnotfile2"
  1611. dockerfile := `
  1612. FROM ` + minimalBaseImage() + `
  1613. COPY dir /tmp/`
  1614. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1615. "dir/foo": "hello",
  1616. }))
  1617. defer ctx.Close()
  1618. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1619. id1 := getIDByName(c, name)
  1620. // Check that adding file with similar name doesn't mess with cache
  1621. if err := ctx.Add("dir_file", "hello2"); err != nil {
  1622. c.Fatal(err)
  1623. }
  1624. cli.BuildCmd(c, name2, build.WithExternalBuildContext(ctx))
  1625. id2 := getIDByName(c, name2)
  1626. if id1 != id2 {
  1627. c.Fatal("The cache should have been used but wasn't")
  1628. }
  1629. }
  1630. func (s *DockerCLIBuildSuite) TestBuildAddCurrentDirWithCache(c *testing.T) {
  1631. const name = "testbuildaddcurrentdirwithcache"
  1632. const name2 = name + "2"
  1633. const name3 = name + "3"
  1634. const name4 = name + "4"
  1635. dockerfile := `
  1636. FROM ` + minimalBaseImage() + `
  1637. MAINTAINER dockerio
  1638. ADD . /usr/lib/bla`
  1639. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1640. "foo": "hello",
  1641. }))
  1642. defer ctx.Close()
  1643. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1644. id1 := getIDByName(c, name)
  1645. // Check that adding file invalidate cache of "ADD ."
  1646. if err := ctx.Add("bar", "hello2"); err != nil {
  1647. c.Fatal(err)
  1648. }
  1649. buildImageSuccessfully(c, name2, build.WithExternalBuildContext(ctx))
  1650. id2 := getIDByName(c, name2)
  1651. if id1 == id2 {
  1652. c.Fatal("The cache should have been invalided but hasn't.")
  1653. }
  1654. // Check that changing file invalidate cache of "ADD ."
  1655. if err := ctx.Add("foo", "hello1"); err != nil {
  1656. c.Fatal(err)
  1657. }
  1658. buildImageSuccessfully(c, name3, build.WithExternalBuildContext(ctx))
  1659. id3 := getIDByName(c, name3)
  1660. if id2 == id3 {
  1661. c.Fatal("The cache should have been invalided but hasn't.")
  1662. }
  1663. // Check that changing file to same content with different mtime does not
  1664. // invalidate cache of "ADD ."
  1665. time.Sleep(1 * time.Second) // wait second because of mtime precision
  1666. if err := ctx.Add("foo", "hello1"); err != nil {
  1667. c.Fatal(err)
  1668. }
  1669. buildImageSuccessfully(c, name4, build.WithExternalBuildContext(ctx))
  1670. id4 := getIDByName(c, name4)
  1671. if id3 != id4 {
  1672. c.Fatal("The cache should have been used but hasn't.")
  1673. }
  1674. }
  1675. // FIXME(vdemeester) this really seems to test the same thing as before (TestBuildAddMultipleLocalFileWithAndWithoutCache)
  1676. func (s *DockerCLIBuildSuite) TestBuildAddCurrentDirWithoutCache(c *testing.T) {
  1677. const name = "testbuildaddcurrentdirwithoutcache"
  1678. dockerfile := `
  1679. FROM ` + minimalBaseImage() + `
  1680. MAINTAINER dockerio
  1681. ADD . /usr/lib/bla`
  1682. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1683. "foo": "hello",
  1684. }))
  1685. defer ctx.Close()
  1686. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1687. id1 := getIDByName(c, name)
  1688. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1689. id2 := getIDByName(c, name)
  1690. if id1 == id2 {
  1691. c.Fatal("The cache should have been invalided but hasn't.")
  1692. }
  1693. }
  1694. func (s *DockerCLIBuildSuite) TestBuildAddRemoteFileWithAndWithoutCache(c *testing.T) {
  1695. const name = "testbuildaddremotefilewithcache"
  1696. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  1697. "baz": "hello",
  1698. }))
  1699. defer server.Close()
  1700. dockerfile := fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1701. MAINTAINER dockerio
  1702. ADD %s/baz /usr/lib/baz/quux`, server.URL())
  1703. cli.BuildCmd(c, name, build.WithDockerfile(dockerfile))
  1704. id1 := getIDByName(c, name)
  1705. cli.BuildCmd(c, name, build.WithDockerfile(dockerfile))
  1706. id2 := getIDByName(c, name)
  1707. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  1708. id3 := getIDByName(c, name)
  1709. if id1 != id2 {
  1710. c.Fatal("The cache should have been used but hasn't.")
  1711. }
  1712. if id1 == id3 {
  1713. c.Fatal("The cache should have been invalided but hasn't.")
  1714. }
  1715. }
  1716. func (s *DockerCLIBuildSuite) TestBuildAddRemoteFileMTime(c *testing.T) {
  1717. const name = "testbuildaddremotefilemtime"
  1718. const name2 = name + "2"
  1719. const name3 = name + "3"
  1720. files := map[string]string{"baz": "hello"}
  1721. server := fakestorage.New(c, "", fakecontext.WithFiles(files))
  1722. defer server.Close()
  1723. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1724. MAINTAINER dockerio
  1725. ADD %s/baz /usr/lib/baz/quux`, server.URL())))
  1726. defer ctx.Close()
  1727. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1728. id1 := getIDByName(c, name)
  1729. cli.BuildCmd(c, name2, build.WithExternalBuildContext(ctx))
  1730. id2 := getIDByName(c, name2)
  1731. if id1 != id2 {
  1732. c.Fatal("The cache should have been used but wasn't - #1")
  1733. }
  1734. // Now create a different server with same contents (causes different mtime)
  1735. // The cache should still be used
  1736. // allow some time for clock to pass as mtime precision is only 1s
  1737. time.Sleep(2 * time.Second)
  1738. server2 := fakestorage.New(c, "", fakecontext.WithFiles(files))
  1739. defer server2.Close()
  1740. ctx2 := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1741. MAINTAINER dockerio
  1742. ADD %s/baz /usr/lib/baz/quux`, server2.URL())))
  1743. defer ctx2.Close()
  1744. cli.BuildCmd(c, name3, build.WithExternalBuildContext(ctx2))
  1745. id3 := getIDByName(c, name3)
  1746. if id1 != id3 {
  1747. c.Fatal("The cache should have been used but wasn't")
  1748. }
  1749. }
  1750. // FIXME(vdemeester) this really seems to test the same thing as before (combined)
  1751. func (s *DockerCLIBuildSuite) TestBuildAddLocalAndRemoteFilesWithAndWithoutCache(c *testing.T) {
  1752. const name = "testbuildaddlocalandremotefilewithcache"
  1753. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  1754. "baz": "hello",
  1755. }))
  1756. defer server.Close()
  1757. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1758. MAINTAINER dockerio
  1759. ADD foo /usr/lib/bla/bar
  1760. ADD %s/baz /usr/lib/baz/quux`, server.URL())),
  1761. fakecontext.WithFiles(map[string]string{
  1762. "foo": "hello world",
  1763. }))
  1764. defer ctx.Close()
  1765. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1766. id1 := getIDByName(c, name)
  1767. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1768. id2 := getIDByName(c, name)
  1769. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1770. id3 := getIDByName(c, name)
  1771. if id1 != id2 {
  1772. c.Fatal("The cache should have been used but hasn't.")
  1773. }
  1774. if id1 == id3 {
  1775. c.Fatal("The cache should have been invalidated but hasn't.")
  1776. }
  1777. }
  1778. func testContextTar(c *testing.T, compression archive.Compression) {
  1779. ctx := fakecontext.New(c, "",
  1780. fakecontext.WithDockerfile(`FROM busybox
  1781. ADD foo /foo
  1782. CMD ["cat", "/foo"]`),
  1783. fakecontext.WithFiles(map[string]string{
  1784. "foo": "bar",
  1785. }),
  1786. )
  1787. defer ctx.Close()
  1788. context, err := archive.Tar(ctx.Dir, compression)
  1789. if err != nil {
  1790. c.Fatalf("failed to build context tar: %v", err)
  1791. }
  1792. const name = "contexttar"
  1793. cli.BuildCmd(c, name, build.WithStdinContext(context))
  1794. }
  1795. func (s *DockerCLIBuildSuite) TestBuildContextTarGzip(c *testing.T) {
  1796. testContextTar(c, archive.Gzip)
  1797. }
  1798. func (s *DockerCLIBuildSuite) TestBuildContextTarNoCompression(c *testing.T) {
  1799. testContextTar(c, archive.Uncompressed)
  1800. }
  1801. func (s *DockerCLIBuildSuite) TestBuildNoContext(c *testing.T) {
  1802. const name = "nocontext"
  1803. icmd.RunCmd(icmd.Cmd{
  1804. Command: []string{dockerBinary, "build", "-t", name, "-"},
  1805. Stdin: strings.NewReader(
  1806. `FROM busybox
  1807. CMD ["echo", "ok"]`),
  1808. }).Assert(c, icmd.Success)
  1809. if out := cli.DockerCmd(c, "run", "--rm", "nocontext").Combined(); out != "ok\n" {
  1810. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  1811. }
  1812. }
  1813. // FIXME(vdemeester) migrate to docker/cli e2e
  1814. func (s *DockerCLIBuildSuite) TestBuildDockerfileStdin(c *testing.T) {
  1815. const name = "stdindockerfile"
  1816. tmpDir, err := os.MkdirTemp("", "fake-context")
  1817. assert.NilError(c, err)
  1818. err = os.WriteFile(filepath.Join(tmpDir, "foo"), []byte("bar"), 0o600)
  1819. assert.NilError(c, err)
  1820. icmd.RunCmd(icmd.Cmd{
  1821. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir},
  1822. Stdin: strings.NewReader(
  1823. `FROM busybox
  1824. ADD foo /foo
  1825. CMD ["cat", "/foo"]`),
  1826. }).Assert(c, icmd.Success)
  1827. res := inspectField(c, name, "Config.Cmd")
  1828. assert.Equal(c, strings.TrimSpace(res), `[cat /foo]`)
  1829. }
  1830. // FIXME(vdemeester) migrate to docker/cli tests (unit or e2e)
  1831. func (s *DockerCLIBuildSuite) TestBuildDockerfileStdinConflict(c *testing.T) {
  1832. const name = "stdindockerfiletarcontext"
  1833. icmd.RunCmd(icmd.Cmd{
  1834. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", "-"},
  1835. }).Assert(c, icmd.Expected{
  1836. ExitCode: 1,
  1837. Err: "use stdin for both build context and dockerfile",
  1838. })
  1839. }
  1840. func (s *DockerCLIBuildSuite) TestBuildDockerfileStdinNoExtraFiles(c *testing.T) {
  1841. s.testBuildDockerfileStdinNoExtraFiles(c, false, false)
  1842. }
  1843. func (s *DockerCLIBuildSuite) TestBuildDockerfileStdinDockerignore(c *testing.T) {
  1844. s.testBuildDockerfileStdinNoExtraFiles(c, true, false)
  1845. }
  1846. func (s *DockerCLIBuildSuite) TestBuildDockerfileStdinDockerignoreIgnored(c *testing.T) {
  1847. s.testBuildDockerfileStdinNoExtraFiles(c, true, true)
  1848. }
  1849. func (s *DockerCLIBuildSuite) testBuildDockerfileStdinNoExtraFiles(c *testing.T, hasDockerignore, ignoreDockerignore bool) {
  1850. const name = "stdindockerfilenoextra"
  1851. tmpDir, err := os.MkdirTemp("", "fake-context")
  1852. assert.NilError(c, err)
  1853. defer os.RemoveAll(tmpDir)
  1854. writeFile := func(filename, content string) {
  1855. err = os.WriteFile(filepath.Join(tmpDir, filename), []byte(content), 0o600)
  1856. assert.NilError(c, err)
  1857. }
  1858. writeFile("foo", "bar")
  1859. if hasDockerignore {
  1860. // Add an empty Dockerfile to verify that it is not added to the image
  1861. writeFile("Dockerfile", "")
  1862. ignores := "Dockerfile\n"
  1863. if ignoreDockerignore {
  1864. ignores += ".dockerignore\n"
  1865. }
  1866. writeFile(".dockerignore", ignores)
  1867. }
  1868. result := icmd.RunCmd(icmd.Cmd{
  1869. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir},
  1870. Stdin: strings.NewReader(
  1871. `FROM busybox
  1872. COPY . /baz`),
  1873. })
  1874. result.Assert(c, icmd.Success)
  1875. result = cli.DockerCmd(c, "run", "--rm", name, "ls", "-A", "/baz")
  1876. if hasDockerignore && !ignoreDockerignore {
  1877. assert.Equal(c, result.Stdout(), ".dockerignore\nfoo\n")
  1878. } else {
  1879. assert.Equal(c, result.Stdout(), "foo\n")
  1880. }
  1881. }
  1882. func (s *DockerCLIBuildSuite) TestBuildWithVolumeOwnership(c *testing.T) {
  1883. testRequires(c, DaemonIsLinux)
  1884. const name = "testbuildimg"
  1885. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox:latest
  1886. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  1887. VOLUME /test`))
  1888. out := cli.DockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test").Combined()
  1889. if expected := "drw-------"; !strings.Contains(out, expected) {
  1890. c.Fatalf("expected %s received %s", expected, out)
  1891. }
  1892. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  1893. c.Fatalf("expected %s received %s", expected, out)
  1894. }
  1895. }
  1896. // testing #1405 - config.Cmd does not get cleaned up if
  1897. // utilizing cache
  1898. func (s *DockerCLIBuildSuite) TestBuildEntrypointRunCleanup(c *testing.T) {
  1899. const name = "testbuildcmdcleanup"
  1900. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1901. RUN echo "hello"`))
  1902. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1903. build.WithFile("Dockerfile", `FROM busybox
  1904. RUN echo "hello"
  1905. ADD foo /foo
  1906. ENTRYPOINT ["/bin/echo"]`),
  1907. build.WithFile("foo", "hello")))
  1908. res := inspectField(c, name, "Config.Cmd")
  1909. // Cmd must be cleaned up
  1910. if res != "[]" {
  1911. c.Fatalf("Cmd %s, expected nil", res)
  1912. }
  1913. }
  1914. func (s *DockerCLIBuildSuite) TestBuildAddFileNotFound(c *testing.T) {
  1915. const name = "testbuildaddnotfound"
  1916. buildImage(name, build.WithBuildContext(c,
  1917. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  1918. ADD foo /usr/local/bar`),
  1919. build.WithFile("bar", "hello"))).Assert(c, icmd.Expected{
  1920. ExitCode: 1,
  1921. Err: "stat foo: file does not exist",
  1922. })
  1923. }
  1924. func (s *DockerCLIBuildSuite) TestBuildInheritance(c *testing.T) {
  1925. testRequires(c, DaemonIsLinux)
  1926. const name = "testbuildinheritance"
  1927. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1928. EXPOSE 2375`))
  1929. ports1 := inspectField(c, name, "Config.ExposedPorts")
  1930. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1931. ENTRYPOINT ["/bin/echo"]`, name)))
  1932. res := inspectField(c, name, "Config.Entrypoint")
  1933. if expected := "[/bin/echo]"; res != expected {
  1934. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1935. }
  1936. ports2 := inspectField(c, name, "Config.ExposedPorts")
  1937. if ports1 != ports2 {
  1938. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  1939. }
  1940. }
  1941. func (s *DockerCLIBuildSuite) TestBuildFails(c *testing.T) {
  1942. const name = "testbuildfails"
  1943. buildImage(name, build.WithDockerfile(`FROM busybox
  1944. RUN sh -c "exit 23"`)).Assert(c, icmd.Expected{
  1945. ExitCode: 23,
  1946. Err: "returned a non-zero code: 23",
  1947. })
  1948. }
  1949. func (s *DockerCLIBuildSuite) TestBuildOnBuild(c *testing.T) {
  1950. const name = "testbuildonbuild"
  1951. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1952. ONBUILD RUN touch foobar`))
  1953. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1954. RUN [ -f foobar ]`, name)))
  1955. }
  1956. // gh #2446
  1957. func (s *DockerCLIBuildSuite) TestBuildAddToSymlinkDest(c *testing.T) {
  1958. makeLink := `ln -s /foo /bar`
  1959. if testEnv.DaemonInfo.OSType == "windows" {
  1960. makeLink = `mklink /D C:\bar C:\foo`
  1961. }
  1962. const name = "testbuildaddtosymlinkdest"
  1963. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1964. build.WithFile("Dockerfile", `
  1965. FROM busybox
  1966. RUN sh -c "mkdir /foo"
  1967. RUN `+makeLink+`
  1968. ADD foo /bar/
  1969. RUN sh -c "[ -f /bar/foo ]"
  1970. RUN sh -c "[ -f /foo/foo ]"`),
  1971. build.WithFile("foo", "hello"),
  1972. ))
  1973. }
  1974. func (s *DockerCLIBuildSuite) TestBuildEscapeWhitespace(c *testing.T) {
  1975. const name = "testbuildescapewhitespace"
  1976. buildImageSuccessfully(c, name, build.WithDockerfile(`
  1977. # ESCAPE=\
  1978. FROM busybox
  1979. MAINTAINER "Docker \
  1980. IO <io@\
  1981. docker.com>"
  1982. `))
  1983. res := inspectField(c, name, "Author")
  1984. if res != `"Docker IO <io@docker.com>"` {
  1985. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  1986. }
  1987. }
  1988. func (s *DockerCLIBuildSuite) TestBuildVerifyIntString(c *testing.T) {
  1989. // Verify that strings that look like ints are still passed as strings
  1990. const name = "testbuildstringing"
  1991. buildImageSuccessfully(c, name, build.WithDockerfile(`
  1992. FROM busybox
  1993. MAINTAINER 123`))
  1994. out := cli.DockerCmd(c, "inspect", name).Stdout()
  1995. if !strings.Contains(out, `"123"`) {
  1996. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  1997. }
  1998. }
  1999. func (s *DockerCLIBuildSuite) TestBuildDockerignore(c *testing.T) {
  2000. const name = "testbuilddockerignore"
  2001. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2002. build.WithFile("Dockerfile", `
  2003. FROM busybox
  2004. ADD . /bla
  2005. RUN sh -c "[[ -f /bla/src/x.go ]]"
  2006. RUN sh -c "[[ -f /bla/Makefile ]]"
  2007. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  2008. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  2009. RUN sh -c "[[ ! -e /bla/README.md ]]"
  2010. RUN sh -c "[[ ! -e /bla/dir/foo ]]"
  2011. RUN sh -c "[[ ! -e /bla/foo ]]"
  2012. RUN sh -c "[[ ! -e /bla/.git ]]"
  2013. RUN sh -c "[[ ! -e v.cc ]]"
  2014. RUN sh -c "[[ ! -e src/v.cc ]]"
  2015. RUN sh -c "[[ ! -e src/_vendor/v.cc ]]"`),
  2016. build.WithFile("Makefile", "all:"),
  2017. build.WithFile(".git/HEAD", "ref: foo"),
  2018. build.WithFile("src/x.go", "package main"),
  2019. build.WithFile("src/_vendor/v.go", "package main"),
  2020. build.WithFile("src/_vendor/v.cc", "package main"),
  2021. build.WithFile("src/v.cc", "package main"),
  2022. build.WithFile("v.cc", "package main"),
  2023. build.WithFile("dir/foo", ""),
  2024. build.WithFile(".gitignore", ""),
  2025. build.WithFile("README.md", "readme"),
  2026. build.WithFile(".dockerignore", `
  2027. .git
  2028. pkg
  2029. .gitignore
  2030. src/_vendor
  2031. *.md
  2032. **/*.cc
  2033. dir`),
  2034. ))
  2035. }
  2036. func (s *DockerCLIBuildSuite) TestBuildDockerignoreCleanPaths(c *testing.T) {
  2037. const name = "testbuilddockerignorecleanpaths"
  2038. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2039. build.WithFile("Dockerfile", `
  2040. FROM busybox
  2041. ADD . /tmp/
  2042. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)"`),
  2043. build.WithFile("foo", "foo"),
  2044. build.WithFile("foo2", "foo2"),
  2045. build.WithFile("dir1/foo", "foo in dir1"),
  2046. build.WithFile(".dockerignore", "./foo\ndir1//foo\n./dir1/../foo2"),
  2047. ))
  2048. }
  2049. func (s *DockerCLIBuildSuite) TestBuildDockerignoreExceptions(c *testing.T) {
  2050. const name = "testbuilddockerignoreexceptions"
  2051. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2052. build.WithFile("Dockerfile", `
  2053. FROM busybox
  2054. ADD . /bla
  2055. RUN sh -c "[[ -f /bla/src/x.go ]]"
  2056. RUN sh -c "[[ -f /bla/Makefile ]]"
  2057. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  2058. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  2059. RUN sh -c "[[ ! -e /bla/README.md ]]"
  2060. RUN sh -c "[[ -e /bla/dir/dir/foo ]]"
  2061. RUN sh -c "[[ ! -e /bla/dir/foo1 ]]"
  2062. RUN sh -c "[[ -f /bla/dir/e ]]"
  2063. RUN sh -c "[[ -f /bla/dir/e-dir/foo ]]"
  2064. RUN sh -c "[[ ! -e /bla/foo ]]"
  2065. RUN sh -c "[[ ! -e /bla/.git ]]"
  2066. RUN sh -c "[[ -e /bla/dir/a.cc ]]"`),
  2067. build.WithFile("Makefile", "all:"),
  2068. build.WithFile(".git/HEAD", "ref: foo"),
  2069. build.WithFile("src/x.go", "package main"),
  2070. build.WithFile("src/_vendor/v.go", "package main"),
  2071. build.WithFile("dir/foo", ""),
  2072. build.WithFile("dir/foo1", ""),
  2073. build.WithFile("dir/dir/f1", ""),
  2074. build.WithFile("dir/dir/foo", ""),
  2075. build.WithFile("dir/e", ""),
  2076. build.WithFile("dir/e-dir/foo", ""),
  2077. build.WithFile(".gitignore", ""),
  2078. build.WithFile("README.md", "readme"),
  2079. build.WithFile("dir/a.cc", "hello"),
  2080. build.WithFile(".dockerignore", `
  2081. .git
  2082. pkg
  2083. .gitignore
  2084. src/_vendor
  2085. *.md
  2086. dir
  2087. !dir/e*
  2088. !dir/dir/foo
  2089. **/*.cc
  2090. !**/*.cc`),
  2091. ))
  2092. }
  2093. func (s *DockerCLIBuildSuite) TestBuildDockerignoringDockerfile(c *testing.T) {
  2094. const name = "testbuilddockerignoredockerfile"
  2095. dockerfile := `
  2096. FROM busybox
  2097. ADD . /tmp/
  2098. RUN sh -c "! ls /tmp/Dockerfile"
  2099. RUN ls /tmp/.dockerignore`
  2100. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2101. build.WithFile("Dockerfile", dockerfile),
  2102. build.WithFile(".dockerignore", "Dockerfile\n"),
  2103. ))
  2104. // FIXME(vdemeester) why twice ?
  2105. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2106. build.WithFile("Dockerfile", dockerfile),
  2107. build.WithFile(".dockerignore", "./Dockerfile\n"),
  2108. ))
  2109. }
  2110. func (s *DockerCLIBuildSuite) TestBuildDockerignoringRenamedDockerfile(c *testing.T) {
  2111. const name = "testbuilddockerignoredockerfile"
  2112. dockerfile := `
  2113. FROM busybox
  2114. ADD . /tmp/
  2115. RUN ls /tmp/Dockerfile
  2116. RUN sh -c "! ls /tmp/MyDockerfile"
  2117. RUN ls /tmp/.dockerignore`
  2118. buildImageSuccessfully(c, name, cli.WithFlags("-f", "MyDockerfile"), build.WithBuildContext(c,
  2119. build.WithFile("Dockerfile", "Should not use me"),
  2120. build.WithFile("MyDockerfile", dockerfile),
  2121. build.WithFile(".dockerignore", "MyDockerfile\n"),
  2122. ))
  2123. // FIXME(vdemeester) why twice ?
  2124. buildImageSuccessfully(c, name, cli.WithFlags("-f", "MyDockerfile"), build.WithBuildContext(c,
  2125. build.WithFile("Dockerfile", "Should not use me"),
  2126. build.WithFile("MyDockerfile", dockerfile),
  2127. build.WithFile(".dockerignore", "./MyDockerfile\n"),
  2128. ))
  2129. }
  2130. func (s *DockerCLIBuildSuite) TestBuildDockerignoringDockerignore(c *testing.T) {
  2131. const name = "testbuilddockerignoredockerignore"
  2132. dockerfile := `
  2133. FROM busybox
  2134. ADD . /tmp/
  2135. RUN sh -c "! ls /tmp/.dockerignore"
  2136. RUN ls /tmp/Dockerfile`
  2137. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2138. build.WithFile("Dockerfile", dockerfile),
  2139. build.WithFile(".dockerignore", ".dockerignore\n"),
  2140. ))
  2141. }
  2142. func (s *DockerCLIBuildSuite) TestBuildDockerignoreTouchDockerfile(c *testing.T) {
  2143. const name = "testbuilddockerignoretouchdockerfile"
  2144. dockerfile := `
  2145. FROM busybox
  2146. ADD . /tmp/`
  2147. ctx := fakecontext.New(c, "",
  2148. fakecontext.WithDockerfile(dockerfile),
  2149. fakecontext.WithFiles(map[string]string{
  2150. ".dockerignore": "Dockerfile\n",
  2151. }))
  2152. defer ctx.Close()
  2153. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2154. id1 := getIDByName(c, name)
  2155. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2156. id2 := getIDByName(c, name)
  2157. if id1 != id2 {
  2158. c.Fatalf("Didn't use the cache - 1")
  2159. }
  2160. // Now make sure touching Dockerfile doesn't invalidate the cache
  2161. if err := ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2162. c.Fatalf("Didn't add Dockerfile: %s", err)
  2163. }
  2164. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2165. id2 = getIDByName(c, name)
  2166. if id1 != id2 {
  2167. c.Fatalf("Didn't use the cache - 2")
  2168. }
  2169. // One more time but just 'touch' it instead of changing the content
  2170. if err := ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2171. c.Fatalf("Didn't add Dockerfile: %s", err)
  2172. }
  2173. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2174. id2 = getIDByName(c, name)
  2175. if id1 != id2 {
  2176. c.Fatalf("Didn't use the cache - 3")
  2177. }
  2178. }
  2179. func (s *DockerCLIBuildSuite) TestBuildDockerignoringWholeDir(c *testing.T) {
  2180. const name = "testbuilddockerignorewholedir"
  2181. dockerfile := `
  2182. FROM busybox
  2183. COPY . /
  2184. RUN sh -c "[[ ! -e /.gitignore ]]"
  2185. RUN sh -c "[[ ! -e /Makefile ]]"`
  2186. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2187. build.WithFile("Dockerfile", dockerfile),
  2188. build.WithFile(".dockerignore", "*\n"),
  2189. build.WithFile("Makefile", "all:"),
  2190. build.WithFile(".gitignore", ""),
  2191. ))
  2192. }
  2193. func (s *DockerCLIBuildSuite) TestBuildDockerignoringOnlyDotfiles(c *testing.T) {
  2194. const name = "testbuilddockerignorewholedir"
  2195. dockerfile := `
  2196. FROM busybox
  2197. COPY . /
  2198. RUN sh -c "[[ ! -e /.gitignore ]]"
  2199. RUN sh -c "[[ -f /Makefile ]]"`
  2200. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2201. build.WithFile("Dockerfile", dockerfile),
  2202. build.WithFile(".dockerignore", ".*"),
  2203. build.WithFile("Makefile", "all:"),
  2204. build.WithFile(".gitignore", ""),
  2205. ))
  2206. }
  2207. func (s *DockerCLIBuildSuite) TestBuildDockerignoringBadExclusion(c *testing.T) {
  2208. const name = "testbuilddockerignorebadexclusion"
  2209. buildImage(name, build.WithBuildContext(c,
  2210. build.WithFile("Dockerfile", `
  2211. FROM busybox
  2212. COPY . /
  2213. RUN sh -c "[[ ! -e /.gitignore ]]"
  2214. RUN sh -c "[[ -f /Makefile ]]"`),
  2215. build.WithFile("Makefile", "all:"),
  2216. build.WithFile(".gitignore", ""),
  2217. build.WithFile(".dockerignore", "!\n"),
  2218. )).Assert(c, icmd.Expected{
  2219. ExitCode: 1,
  2220. Err: `illegal exclusion pattern: "!"`,
  2221. })
  2222. }
  2223. func (s *DockerCLIBuildSuite) TestBuildDockerignoringWildTopDir(c *testing.T) {
  2224. dockerfile := `
  2225. FROM busybox
  2226. COPY . /
  2227. RUN sh -c "[[ ! -e /.dockerignore ]]"
  2228. RUN sh -c "[[ ! -e /Dockerfile ]]"
  2229. RUN sh -c "[[ ! -e /file1 ]]"
  2230. RUN sh -c "[[ ! -e /dir ]]"`
  2231. // All of these should result in ignoring all files
  2232. for _, variant := range []string{"**", "**/", "**/**", "*"} {
  2233. buildImageSuccessfully(c, "noname", build.WithBuildContext(c,
  2234. build.WithFile("Dockerfile", dockerfile),
  2235. build.WithFile("file1", ""),
  2236. build.WithFile("dir/file1", ""),
  2237. build.WithFile(".dockerignore", variant),
  2238. ))
  2239. cli.DockerCmd(c, "rmi", "noname")
  2240. }
  2241. }
  2242. func (s *DockerCLIBuildSuite) TestBuildDockerignoringWildDirs(c *testing.T) {
  2243. dockerfile := `
  2244. FROM busybox
  2245. COPY . /
  2246. #RUN sh -c "[[ -e /.dockerignore ]]"
  2247. RUN sh -c "[[ -e /Dockerfile ]] && \
  2248. [[ ! -e /file0 ]] && \
  2249. [[ ! -e /dir1/file0 ]] && \
  2250. [[ ! -e /dir2/file0 ]] && \
  2251. [[ ! -e /file1 ]] && \
  2252. [[ ! -e /dir1/file1 ]] && \
  2253. [[ ! -e /dir1/dir2/file1 ]] && \
  2254. [[ ! -e /dir1/file2 ]] && \
  2255. [[ -e /dir1/dir2/file2 ]] && \
  2256. [[ ! -e /dir1/dir2/file4 ]] && \
  2257. [[ ! -e /dir1/dir2/file5 ]] && \
  2258. [[ ! -e /dir1/dir2/file6 ]] && \
  2259. [[ ! -e /dir1/dir3/file7 ]] && \
  2260. [[ ! -e /dir1/dir3/file8 ]] && \
  2261. [[ -e /dir1/dir3 ]] && \
  2262. [[ -e /dir1/dir4 ]] && \
  2263. [[ ! -e 'dir1/dir5/fileAA' ]] && \
  2264. [[ -e 'dir1/dir5/fileAB' ]] && \
  2265. [[ -e 'dir1/dir5/fileB' ]]" # "." in pattern means nothing
  2266. RUN echo all done!`
  2267. dockerignore := `
  2268. **/file0
  2269. **/*file1
  2270. **/dir1/file2
  2271. dir1/**/file4
  2272. **/dir2/file5
  2273. **/dir1/dir2/file6
  2274. dir1/dir3/**
  2275. **/dir4/**
  2276. **/file?A
  2277. **/file\?B
  2278. **/dir5/file.
  2279. `
  2280. buildImageSuccessfully(c, "noname", build.WithBuildContext(c,
  2281. build.WithFile("Dockerfile", dockerfile),
  2282. build.WithFile(".dockerignore", dockerignore),
  2283. build.WithFile("dir1/file0", ""),
  2284. build.WithFile("dir1/dir2/file0", ""),
  2285. build.WithFile("file1", ""),
  2286. build.WithFile("dir1/file1", ""),
  2287. build.WithFile("dir1/dir2/file1", ""),
  2288. build.WithFile("dir1/file2", ""),
  2289. build.WithFile("dir1/dir2/file2", ""), // remains
  2290. build.WithFile("dir1/dir2/file4", ""),
  2291. build.WithFile("dir1/dir2/file5", ""),
  2292. build.WithFile("dir1/dir2/file6", ""),
  2293. build.WithFile("dir1/dir3/file7", ""),
  2294. build.WithFile("dir1/dir3/file8", ""),
  2295. build.WithFile("dir1/dir4/file9", ""),
  2296. build.WithFile("dir1/dir5/fileAA", ""),
  2297. build.WithFile("dir1/dir5/fileAB", ""),
  2298. build.WithFile("dir1/dir5/fileB", ""),
  2299. ))
  2300. }
  2301. func (s *DockerCLIBuildSuite) TestBuildLineBreak(c *testing.T) {
  2302. testRequires(c, DaemonIsLinux)
  2303. const name = "testbuildlinebreak"
  2304. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2305. RUN sh -c 'echo root:testpass \
  2306. > /tmp/passwd'
  2307. RUN mkdir -p /var/run/sshd
  2308. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  2309. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`))
  2310. }
  2311. func (s *DockerCLIBuildSuite) TestBuildEOLInLine(c *testing.T) {
  2312. testRequires(c, DaemonIsLinux)
  2313. const name = "testbuildeolinline"
  2314. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2315. RUN sh -c 'echo root:testpass > /tmp/passwd'
  2316. RUN echo "foo \n bar"; echo "baz"
  2317. RUN mkdir -p /var/run/sshd
  2318. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  2319. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`))
  2320. }
  2321. func (s *DockerCLIBuildSuite) TestBuildCommentsShebangs(c *testing.T) {
  2322. testRequires(c, DaemonIsLinux)
  2323. const name = "testbuildcomments"
  2324. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2325. # This is an ordinary comment.
  2326. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  2327. RUN [ ! -x /hello.sh ]
  2328. # comment with line break \
  2329. RUN chmod +x /hello.sh
  2330. RUN [ -x /hello.sh ]
  2331. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  2332. RUN [ "$(/hello.sh)" = "hello world" ]`))
  2333. }
  2334. func (s *DockerCLIBuildSuite) TestBuildUsersAndGroups(c *testing.T) {
  2335. testRequires(c, DaemonIsLinux)
  2336. const name = "testbuildusers"
  2337. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2338. # Make sure our defaults work
  2339. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  2340. # TODO decide if "args.user = strconv.Itoa(syscall.Getuid())" is acceptable behavior for changeUser in sysvinit instead of "return nil" when "USER" isn't specified (so that we get the proper group list even if that is the empty list, even in the default case of not supplying an explicit USER to run as, which implies USER 0)
  2341. USER root
  2342. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  2343. # Setup dockerio user and group
  2344. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd && \
  2345. echo 'dockerio:x:1001:' >> /etc/group
  2346. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  2347. USER dockerio
  2348. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2349. # Switch back to root and double check that worked exactly as we might expect it to
  2350. USER root
  2351. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ] && \
  2352. # Add a "supplementary" group for our dockerio user
  2353. echo 'supplementary:x:1002:dockerio' >> /etc/group
  2354. # ... and then go verify that we get it like we expect
  2355. USER dockerio
  2356. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  2357. USER 1001
  2358. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  2359. # super test the new "user:group" syntax
  2360. USER dockerio:dockerio
  2361. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2362. USER 1001:dockerio
  2363. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2364. USER dockerio:1001
  2365. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2366. USER 1001:1001
  2367. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2368. USER dockerio:supplementary
  2369. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2370. USER dockerio:1002
  2371. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2372. USER 1001:supplementary
  2373. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2374. USER 1001:1002
  2375. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2376. # make sure unknown uid/gid still works properly
  2377. USER 1042:1043
  2378. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`))
  2379. }
  2380. // FIXME(vdemeester) rename this test (and probably "merge" it with the one below TestBuildEnvUsage2)
  2381. func (s *DockerCLIBuildSuite) TestBuildEnvUsage(c *testing.T) {
  2382. // /docker/world/hello is not owned by the correct user
  2383. testRequires(c, NotUserNamespace)
  2384. testRequires(c, DaemonIsLinux)
  2385. const name = "testbuildenvusage"
  2386. dockerfile := `FROM busybox
  2387. ENV HOME /root
  2388. ENV PATH $HOME/bin:$PATH
  2389. ENV PATH /tmp:$PATH
  2390. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  2391. ENV FOO /foo/baz
  2392. ENV BAR /bar
  2393. ENV BAZ $BAR
  2394. ENV FOOPATH $PATH:$FOO
  2395. RUN [ "$BAR" = "$BAZ" ]
  2396. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  2397. ENV FROM hello/docker/world
  2398. ENV TO /docker/world/hello
  2399. ADD $FROM $TO
  2400. RUN [ "$(cat $TO)" = "hello" ]
  2401. ENV abc=def
  2402. ENV ghi=$abc
  2403. RUN [ "$ghi" = "def" ]
  2404. `
  2405. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2406. build.WithFile("Dockerfile", dockerfile),
  2407. build.WithFile("hello/docker/world", "hello"),
  2408. ))
  2409. }
  2410. // FIXME(vdemeester) rename this test (and probably "merge" it with the one above TestBuildEnvUsage)
  2411. func (s *DockerCLIBuildSuite) TestBuildEnvUsage2(c *testing.T) {
  2412. // /docker/world/hello is not owned by the correct user
  2413. testRequires(c, NotUserNamespace)
  2414. testRequires(c, DaemonIsLinux)
  2415. const name = "testbuildenvusage2"
  2416. dockerfile := `FROM busybox
  2417. ENV abc=def def="hello world"
  2418. RUN [ "$abc,$def" = "def,hello world" ]
  2419. ENV def=hello\ world v1=abc v2="hi there" v3='boogie nights' v4="with'quotes too"
  2420. RUN [ "$def,$v1,$v2,$v3,$v4" = "hello world,abc,hi there,boogie nights,with'quotes too" ]
  2421. ENV abc=zzz FROM=hello/docker/world
  2422. ENV abc=zzz TO=/docker/world/hello
  2423. ADD $FROM $TO
  2424. RUN [ "$abc,$(cat $TO)" = "zzz,hello" ]
  2425. ENV abc 'yyy'
  2426. RUN [ $abc = 'yyy' ]
  2427. ENV abc=
  2428. RUN [ "$abc" = "" ]
  2429. # use grep to make sure if the builder substitutes \$foo by mistake
  2430. # we don't get a false positive
  2431. ENV abc=\$foo
  2432. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  2433. ENV abc \$foo
  2434. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  2435. ENV abc=\'foo\' abc2=\"foo\"
  2436. RUN [ "$abc,$abc2" = "'foo',\"foo\"" ]
  2437. ENV abc "foo"
  2438. RUN [ "$abc" = "foo" ]
  2439. ENV abc 'foo'
  2440. RUN [ "$abc" = 'foo' ]
  2441. ENV abc \'foo\'
  2442. RUN [ "$abc" = "'foo'" ]
  2443. ENV abc \"foo\"
  2444. RUN [ "$abc" = '"foo"' ]
  2445. ENV abc=ABC
  2446. RUN [ "$abc" = "ABC" ]
  2447. ENV def1=${abc:-DEF} def2=${ccc:-DEF}
  2448. ENV def3=${ccc:-${def2}xx} def4=${abc:+ALT} def5=${def2:+${abc}:} def6=${ccc:-\$abc:} def7=${ccc:-\${abc}:}
  2449. RUN [ "$def1,$def2,$def3,$def4,$def5,$def6,$def7" = 'ABC,DEF,DEFxx,ALT,ABC:,$abc:,${abc:}' ]
  2450. ENV mypath=${mypath:+$mypath:}/home
  2451. ENV mypath=${mypath:+$mypath:}/away
  2452. RUN [ "$mypath" = '/home:/away' ]
  2453. ENV e1=bar
  2454. ENV e2=$e1 e3=$e11 e4=\$e1 e5=\$e11
  2455. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  2456. ENV ee1 bar
  2457. ENV ee2 $ee1
  2458. ENV ee3 $ee11
  2459. ENV ee4 \$ee1
  2460. ENV ee5 \$ee11
  2461. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  2462. ENV eee1="foo" eee2='foo'
  2463. ENV eee3 "foo"
  2464. ENV eee4 'foo'
  2465. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  2466. `
  2467. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2468. build.WithFile("Dockerfile", dockerfile),
  2469. build.WithFile("hello/docker/world", "hello"),
  2470. ))
  2471. }
  2472. func (s *DockerCLIBuildSuite) TestBuildAddScript(c *testing.T) {
  2473. testRequires(c, DaemonIsLinux)
  2474. const name = "testbuildaddscript"
  2475. dockerfile := `
  2476. FROM busybox
  2477. ADD test /test
  2478. RUN ["chmod","+x","/test"]
  2479. RUN ["/test"]
  2480. RUN [ "$(cat /testfile)" = 'test!' ]`
  2481. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2482. build.WithFile("Dockerfile", dockerfile),
  2483. build.WithFile("test", "#!/bin/sh\necho 'test!' > /testfile"),
  2484. ))
  2485. }
  2486. func (s *DockerCLIBuildSuite) TestBuildAddTar(c *testing.T) {
  2487. // /test/foo is not owned by the correct user
  2488. testRequires(c, NotUserNamespace)
  2489. const name = "testbuildaddtar"
  2490. ctx := func() *fakecontext.Fake {
  2491. dockerfile := `
  2492. FROM busybox
  2493. ADD test.tar /
  2494. RUN cat /test/foo | grep Hi
  2495. ADD test.tar /test.tar
  2496. RUN cat /test.tar/test/foo | grep Hi
  2497. ADD test.tar /unlikely-to-exist
  2498. RUN cat /unlikely-to-exist/test/foo | grep Hi
  2499. ADD test.tar /unlikely-to-exist-trailing-slash/
  2500. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  2501. RUN sh -c "mkdir /existing-directory" #sh -c is needed on Windows to use the correct mkdir
  2502. ADD test.tar /existing-directory
  2503. RUN cat /existing-directory/test/foo | grep Hi
  2504. ADD test.tar /existing-directory-trailing-slash/
  2505. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  2506. tmpDir, err := os.MkdirTemp("", "fake-context")
  2507. assert.NilError(c, err)
  2508. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2509. if err != nil {
  2510. c.Fatalf("failed to create test.tar archive: %v", err)
  2511. }
  2512. defer testTar.Close()
  2513. tw := tar.NewWriter(testTar)
  2514. if err := tw.WriteHeader(&tar.Header{
  2515. Name: "test/foo",
  2516. Size: 2,
  2517. }); err != nil {
  2518. c.Fatalf("failed to write tar file header: %v", err)
  2519. }
  2520. if _, err := tw.Write([]byte("Hi")); err != nil {
  2521. c.Fatalf("failed to write tar file content: %v", err)
  2522. }
  2523. if err := tw.Close(); err != nil {
  2524. c.Fatalf("failed to close tar archive: %v", err)
  2525. }
  2526. if err := os.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0o644); err != nil {
  2527. c.Fatalf("failed to open destination dockerfile: %v", err)
  2528. }
  2529. return fakecontext.New(c, tmpDir)
  2530. }()
  2531. defer ctx.Close()
  2532. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2533. }
  2534. func (s *DockerCLIBuildSuite) TestBuildAddBrokenTar(c *testing.T) {
  2535. const name = "testbuildaddbrokentar"
  2536. ctx := func() *fakecontext.Fake {
  2537. dockerfile := `
  2538. FROM busybox
  2539. ADD test.tar /`
  2540. tmpDir, err := os.MkdirTemp("", "fake-context")
  2541. assert.NilError(c, err)
  2542. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2543. if err != nil {
  2544. c.Fatalf("failed to create test.tar archive: %v", err)
  2545. }
  2546. defer testTar.Close()
  2547. tw := tar.NewWriter(testTar)
  2548. if err := tw.WriteHeader(&tar.Header{
  2549. Name: "test/foo",
  2550. Size: 2,
  2551. }); err != nil {
  2552. c.Fatalf("failed to write tar file header: %v", err)
  2553. }
  2554. if _, err := tw.Write([]byte("Hi")); err != nil {
  2555. c.Fatalf("failed to write tar file content: %v", err)
  2556. }
  2557. if err := tw.Close(); err != nil {
  2558. c.Fatalf("failed to close tar archive: %v", err)
  2559. }
  2560. // Corrupt the tar by removing one byte off the end
  2561. stat, err := testTar.Stat()
  2562. if err != nil {
  2563. c.Fatalf("failed to stat tar archive: %v", err)
  2564. }
  2565. if err := testTar.Truncate(stat.Size() - 1); err != nil {
  2566. c.Fatalf("failed to truncate tar archive: %v", err)
  2567. }
  2568. if err := os.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0o644); err != nil {
  2569. c.Fatalf("failed to open destination dockerfile: %v", err)
  2570. }
  2571. return fakecontext.New(c, tmpDir)
  2572. }()
  2573. defer ctx.Close()
  2574. buildImage(name, build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  2575. ExitCode: 1,
  2576. })
  2577. }
  2578. func (s *DockerCLIBuildSuite) TestBuildAddNonTar(c *testing.T) {
  2579. const name = "testbuildaddnontar"
  2580. // Should not try to extract test.tar
  2581. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2582. build.WithFile("Dockerfile", `
  2583. FROM busybox
  2584. ADD test.tar /
  2585. RUN test -f /test.tar`),
  2586. build.WithFile("test.tar", "not_a_tar_file"),
  2587. ))
  2588. }
  2589. func (s *DockerCLIBuildSuite) TestBuildAddTarXz(c *testing.T) {
  2590. // /test/foo is not owned by the correct user
  2591. testRequires(c, NotUserNamespace)
  2592. testRequires(c, DaemonIsLinux)
  2593. const name = "testbuildaddtarxz"
  2594. ctx := func() *fakecontext.Fake {
  2595. dockerfile := `
  2596. FROM busybox
  2597. ADD test.tar.xz /
  2598. RUN cat /test/foo | grep Hi`
  2599. tmpDir, err := os.MkdirTemp("", "fake-context")
  2600. assert.NilError(c, err)
  2601. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2602. if err != nil {
  2603. c.Fatalf("failed to create test.tar archive: %v", err)
  2604. }
  2605. defer testTar.Close()
  2606. tw := tar.NewWriter(testTar)
  2607. if err := tw.WriteHeader(&tar.Header{
  2608. Name: "test/foo",
  2609. Size: 2,
  2610. }); err != nil {
  2611. c.Fatalf("failed to write tar file header: %v", err)
  2612. }
  2613. if _, err := tw.Write([]byte("Hi")); err != nil {
  2614. c.Fatalf("failed to write tar file content: %v", err)
  2615. }
  2616. if err := tw.Close(); err != nil {
  2617. c.Fatalf("failed to close tar archive: %v", err)
  2618. }
  2619. icmd.RunCmd(icmd.Cmd{
  2620. Command: []string{"xz", "-k", "test.tar"},
  2621. Dir: tmpDir,
  2622. }).Assert(c, icmd.Success)
  2623. if err := os.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0o644); err != nil {
  2624. c.Fatalf("failed to open destination dockerfile: %v", err)
  2625. }
  2626. return fakecontext.New(c, tmpDir)
  2627. }()
  2628. defer ctx.Close()
  2629. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2630. }
  2631. func (s *DockerCLIBuildSuite) TestBuildAddTarXzGz(c *testing.T) {
  2632. testRequires(c, DaemonIsLinux)
  2633. const name = "testbuildaddtarxzgz"
  2634. ctx := func() *fakecontext.Fake {
  2635. dockerfile := `
  2636. FROM busybox
  2637. ADD test.tar.xz.gz /
  2638. RUN ls /test.tar.xz.gz`
  2639. tmpDir, err := os.MkdirTemp("", "fake-context")
  2640. assert.NilError(c, err)
  2641. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2642. if err != nil {
  2643. c.Fatalf("failed to create test.tar archive: %v", err)
  2644. }
  2645. defer testTar.Close()
  2646. tw := tar.NewWriter(testTar)
  2647. if err := tw.WriteHeader(&tar.Header{
  2648. Name: "test/foo",
  2649. Size: 2,
  2650. }); err != nil {
  2651. c.Fatalf("failed to write tar file header: %v", err)
  2652. }
  2653. if _, err := tw.Write([]byte("Hi")); err != nil {
  2654. c.Fatalf("failed to write tar file content: %v", err)
  2655. }
  2656. if err := tw.Close(); err != nil {
  2657. c.Fatalf("failed to close tar archive: %v", err)
  2658. }
  2659. icmd.RunCmd(icmd.Cmd{
  2660. Command: []string{"xz", "-k", "test.tar"},
  2661. Dir: tmpDir,
  2662. }).Assert(c, icmd.Success)
  2663. icmd.RunCmd(icmd.Cmd{
  2664. Command: []string{"gzip", "test.tar.xz"},
  2665. Dir: tmpDir,
  2666. })
  2667. if err := os.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0o644); err != nil {
  2668. c.Fatalf("failed to open destination dockerfile: %v", err)
  2669. }
  2670. return fakecontext.New(c, tmpDir)
  2671. }()
  2672. defer ctx.Close()
  2673. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2674. }
  2675. // FIXME(vdemeester) most of the from git tests could be moved to `docker/cli` e2e tests
  2676. func (s *DockerCLIBuildSuite) TestBuildFromGit(c *testing.T) {
  2677. const name = "testbuildfromgit"
  2678. git := fakegit.New(c, "repo", map[string]string{
  2679. "Dockerfile": `FROM busybox
  2680. ADD first /first
  2681. RUN [ -f /first ]
  2682. MAINTAINER docker`,
  2683. "first": "test git data",
  2684. }, true)
  2685. defer git.Close()
  2686. buildImageSuccessfully(c, name, build.WithContextPath(git.RepoURL))
  2687. res := inspectField(c, name, "Author")
  2688. if res != "docker" {
  2689. c.Fatalf("Maintainer should be docker, got %s", res)
  2690. }
  2691. }
  2692. func (s *DockerCLIBuildSuite) TestBuildFromGitWithContext(c *testing.T) {
  2693. const name = "testbuildfromgit"
  2694. git := fakegit.New(c, "repo", map[string]string{
  2695. "docker/Dockerfile": `FROM busybox
  2696. ADD first /first
  2697. RUN [ -f /first ]
  2698. MAINTAINER docker`,
  2699. "docker/first": "test git data",
  2700. }, true)
  2701. defer git.Close()
  2702. buildImageSuccessfully(c, name, build.WithContextPath(fmt.Sprintf("%s#master:docker", git.RepoURL)))
  2703. res := inspectField(c, name, "Author")
  2704. if res != "docker" {
  2705. c.Fatalf("Maintainer should be docker, got %s", res)
  2706. }
  2707. }
  2708. func (s *DockerCLIBuildSuite) TestBuildFromGitWithF(c *testing.T) {
  2709. const name = "testbuildfromgitwithf"
  2710. git := fakegit.New(c, "repo", map[string]string{
  2711. "myApp/myDockerfile": `FROM busybox
  2712. RUN echo hi from Dockerfile`,
  2713. }, true)
  2714. defer git.Close()
  2715. buildImage(name, cli.WithFlags("-f", "myApp/myDockerfile"), build.WithContextPath(git.RepoURL)).Assert(c, icmd.Expected{
  2716. Out: "hi from Dockerfile",
  2717. })
  2718. }
  2719. func (s *DockerCLIBuildSuite) TestBuildFromRemoteTarball(c *testing.T) {
  2720. const name = "testbuildfromremotetarball"
  2721. buffer := new(bytes.Buffer)
  2722. tw := tar.NewWriter(buffer)
  2723. defer tw.Close()
  2724. dockerfile := []byte(`FROM busybox
  2725. MAINTAINER docker`)
  2726. if err := tw.WriteHeader(&tar.Header{
  2727. Name: "Dockerfile",
  2728. Size: int64(len(dockerfile)),
  2729. }); err != nil {
  2730. c.Fatalf("failed to write tar file header: %v", err)
  2731. }
  2732. if _, err := tw.Write(dockerfile); err != nil {
  2733. c.Fatalf("failed to write tar file content: %v", err)
  2734. }
  2735. if err := tw.Close(); err != nil {
  2736. c.Fatalf("failed to close tar archive: %v", err)
  2737. }
  2738. server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
  2739. "testT.tar": buffer,
  2740. }))
  2741. defer server.Close()
  2742. cli.BuildCmd(c, name, build.WithContextPath(server.URL()+"/testT.tar"))
  2743. res := inspectField(c, name, "Author")
  2744. if res != "docker" {
  2745. c.Fatalf("Maintainer should be docker, got %s", res)
  2746. }
  2747. }
  2748. func (s *DockerCLIBuildSuite) TestBuildCleanupCmdOnEntrypoint(c *testing.T) {
  2749. const name = "testbuildcmdcleanuponentrypoint"
  2750. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  2751. CMD ["test"]
  2752. ENTRYPOINT ["echo"]`))
  2753. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  2754. ENTRYPOINT ["cat"]`, name)))
  2755. res := inspectField(c, name, "Config.Cmd")
  2756. if res != "[]" {
  2757. c.Fatalf("Cmd %s, expected nil", res)
  2758. }
  2759. res = inspectField(c, name, "Config.Entrypoint")
  2760. if expected := "[cat]"; res != expected {
  2761. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2762. }
  2763. }
  2764. func (s *DockerCLIBuildSuite) TestBuildClearCmd(c *testing.T) {
  2765. const name = "testbuildclearcmd"
  2766. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  2767. ENTRYPOINT ["/bin/bash"]
  2768. CMD []`))
  2769. cmd := inspectFieldJSON(c, name, "Config.Cmd")
  2770. // OCI types specify `omitempty` JSON annotation which doesn't serialize
  2771. // empty arrays and the Cmd will not be present at all.
  2772. if testEnv.UsingSnapshotter() {
  2773. assert.Check(c, is.Equal(cmd, "null"))
  2774. } else {
  2775. assert.Check(c, is.Equal(cmd, "[]"))
  2776. }
  2777. }
  2778. func (s *DockerCLIBuildSuite) TestBuildEmptyCmd(c *testing.T) {
  2779. // Skip on Windows. Base image on Windows has a CMD set in the image.
  2780. testRequires(c, DaemonIsLinux)
  2781. const name = "testbuildemptycmd"
  2782. buildImageSuccessfully(c, name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n"))
  2783. res := inspectFieldJSON(c, name, "Config.Cmd")
  2784. if res != "null" {
  2785. c.Fatalf("Cmd %s, expected %s", res, "null")
  2786. }
  2787. }
  2788. func (s *DockerCLIBuildSuite) TestBuildOnBuildOutput(c *testing.T) {
  2789. const name = "testbuildonbuildparent"
  2790. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nONBUILD RUN echo foo\n"))
  2791. buildImage(name, build.WithDockerfile("FROM "+name+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2792. Out: "# Executing 1 build trigger",
  2793. })
  2794. }
  2795. // FIXME(vdemeester) should be a unit test
  2796. func (s *DockerCLIBuildSuite) TestBuildInvalidTag(c *testing.T) {
  2797. name := "abcd:" + testutil.GenerateRandomAlphaOnlyString(200)
  2798. buildImage(name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2799. ExitCode: 125,
  2800. Err: "invalid reference format",
  2801. })
  2802. }
  2803. func (s *DockerCLIBuildSuite) TestBuildCmdShDashC(c *testing.T) {
  2804. const name = "testbuildcmdshc"
  2805. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD echo cmd\n"))
  2806. res := inspectFieldJSON(c, name, "Config.Cmd")
  2807. expected := `["/bin/sh","-c","echo cmd"]`
  2808. if testEnv.DaemonInfo.OSType == "windows" {
  2809. expected = `["cmd /S /C echo cmd"]`
  2810. }
  2811. if res != expected {
  2812. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2813. }
  2814. }
  2815. func (s *DockerCLIBuildSuite) TestBuildCmdSpaces(c *testing.T) {
  2816. // Test to make sure that when we strcat arrays we take into account
  2817. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  2818. // look the same
  2819. const name = "testbuildcmdspaces"
  2820. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo hi\"]\n"))
  2821. id1 := getIDByName(c, name)
  2822. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"hi\"]\n"))
  2823. id2 := getIDByName(c, name)
  2824. if id1 == id2 {
  2825. c.Fatal("Should not have resulted in the same CMD")
  2826. }
  2827. // Now do the same with ENTRYPOINT
  2828. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT [\"echo hi\"]\n"))
  2829. id1 = getIDByName(c, name)
  2830. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n"))
  2831. id2 = getIDByName(c, name)
  2832. if id1 == id2 {
  2833. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  2834. }
  2835. }
  2836. func (s *DockerCLIBuildSuite) TestBuildCmdJSONNoShDashC(c *testing.T) {
  2837. const name = "testbuildcmdjson"
  2838. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"cmd\"]"))
  2839. res := inspectFieldJSON(c, name, "Config.Cmd")
  2840. expected := `["echo","cmd"]`
  2841. if res != expected {
  2842. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2843. }
  2844. }
  2845. func (s *DockerCLIBuildSuite) TestBuildEntrypointCanBeOverriddenByChild(c *testing.T) {
  2846. buildImageSuccessfully(c, "parent", build.WithDockerfile(`
  2847. FROM busybox
  2848. ENTRYPOINT exit 130
  2849. `))
  2850. icmd.RunCommand(dockerBinary, "run", "parent").Assert(c, icmd.Expected{
  2851. ExitCode: 130,
  2852. })
  2853. buildImageSuccessfully(c, "child", build.WithDockerfile(`
  2854. FROM parent
  2855. ENTRYPOINT exit 5
  2856. `))
  2857. icmd.RunCommand(dockerBinary, "run", "child").Assert(c, icmd.Expected{
  2858. ExitCode: 5,
  2859. })
  2860. }
  2861. func (s *DockerCLIBuildSuite) TestBuildEntrypointCanBeOverriddenByChildInspect(c *testing.T) {
  2862. var (
  2863. name = "testbuildepinherit"
  2864. name2 = "testbuildepinherit2"
  2865. expected = `["/bin/sh","-c","echo quux"]`
  2866. )
  2867. if testEnv.DaemonInfo.OSType == "windows" {
  2868. expected = `["cmd /S /C echo quux"]`
  2869. }
  2870. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT /foo/bar"))
  2871. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name)))
  2872. res := inspectFieldJSON(c, name2, "Config.Entrypoint")
  2873. if res != expected {
  2874. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  2875. }
  2876. icmd.RunCommand(dockerBinary, "run", name2).Assert(c, icmd.Expected{
  2877. Out: "quux",
  2878. })
  2879. }
  2880. func (s *DockerCLIBuildSuite) TestBuildRunShEntrypoint(c *testing.T) {
  2881. const name = "testbuildentrypoint"
  2882. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2883. ENTRYPOINT echo`))
  2884. cli.DockerCmd(c, "run", "--rm", name)
  2885. }
  2886. func (s *DockerCLIBuildSuite) TestBuildExoticShellInterpolation(c *testing.T) {
  2887. testRequires(c, DaemonIsLinux)
  2888. const name = "testbuildexoticshellinterpolation"
  2889. buildImageSuccessfully(c, name, build.WithDockerfile(`
  2890. FROM busybox
  2891. ENV SOME_VAR a.b.c
  2892. RUN [ "$SOME_VAR" = 'a.b.c' ]
  2893. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  2894. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  2895. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  2896. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  2897. RUN [ "${SOME_VAR##*.}" = 'c' ]
  2898. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  2899. RUN [ "${#SOME_VAR}" = '5' ]
  2900. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  2901. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  2902. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  2903. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  2904. `))
  2905. }
  2906. func (s *DockerCLIBuildSuite) TestBuildVerifySingleQuoteFails(c *testing.T) {
  2907. // This testcase is supposed to generate an error because the
  2908. // JSON array we're passing in on the CMD uses single quotes instead
  2909. // of double quotes (per the JSON spec). This means we interpret it
  2910. // as a "string" instead of "JSON array" and pass it on to "sh -c" and
  2911. // it should barf on it.
  2912. const name = "testbuildsinglequotefails"
  2913. expectedExitCode := 2
  2914. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2915. CMD [ '/bin/sh', '-c', 'echo hi' ]`))
  2916. icmd.RunCommand(dockerBinary, "run", "--rm", name).Assert(c, icmd.Expected{
  2917. ExitCode: expectedExitCode,
  2918. })
  2919. }
  2920. func (s *DockerCLIBuildSuite) TestBuildVerboseOut(c *testing.T) {
  2921. const name = "testbuildverboseout"
  2922. expected := "\n123\n"
  2923. if testEnv.DaemonInfo.OSType == "windows" {
  2924. expected = "\n123\r\n"
  2925. }
  2926. buildImage(name, build.WithDockerfile(`FROM busybox
  2927. RUN echo 123`)).Assert(c, icmd.Expected{
  2928. Out: expected,
  2929. })
  2930. }
  2931. func (s *DockerCLIBuildSuite) TestBuildWithTabs(c *testing.T) {
  2932. skip.If(c, versions.GreaterThan(testEnv.DaemonAPIVersion(), "1.44"), "ContainerConfig is deprecated")
  2933. skip.If(c, testEnv.UsingSnapshotter, "ContainerConfig is not filled in c8d")
  2934. const name = "testbuildwithtabs"
  2935. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nRUN echo\tone\t\ttwo"))
  2936. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  2937. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  2938. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2939. if testEnv.DaemonInfo.OSType == "windows" {
  2940. expected1 = `["cmd /S /C echo\tone\t\ttwo"]`
  2941. expected2 = `["cmd /S /C echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2942. }
  2943. if res != expected1 && res != expected2 {
  2944. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  2945. }
  2946. }
  2947. func (s *DockerCLIBuildSuite) TestBuildLabels(c *testing.T) {
  2948. const name = "testbuildlabel"
  2949. expected := `{"License":"GPL","Vendor":"Acme"}`
  2950. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2951. LABEL Vendor=Acme
  2952. LABEL License GPL`))
  2953. res := inspectFieldJSON(c, name, "Config.Labels")
  2954. if res != expected {
  2955. c.Fatalf("Labels %s, expected %s", res, expected)
  2956. }
  2957. }
  2958. func (s *DockerCLIBuildSuite) TestBuildLabelsCache(c *testing.T) {
  2959. const name = "testbuildlabelcache"
  2960. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2961. LABEL Vendor=Acme`))
  2962. id1 := getIDByName(c, name)
  2963. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2964. LABEL Vendor=Acme`))
  2965. id2 := getIDByName(c, name)
  2966. if id1 != id2 {
  2967. c.Fatalf("Build 2 should have worked & used cache(%s,%s)", id1, id2)
  2968. }
  2969. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2970. LABEL Vendor=Acme1`))
  2971. id2 = getIDByName(c, name)
  2972. if id1 == id2 {
  2973. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s)", id1, id2)
  2974. }
  2975. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2976. LABEL Vendor Acme`))
  2977. id2 = getIDByName(c, name)
  2978. if id1 != id2 {
  2979. c.Fatalf("Build 4 should have worked & used cache(%s,%s)", id1, id2)
  2980. }
  2981. // Now make sure the cache isn't used by mistake
  2982. buildImageSuccessfully(c, name, build.WithoutCache, build.WithDockerfile(`FROM busybox
  2983. LABEL f1=b1 f2=b2`))
  2984. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2985. LABEL f1=b1 f2=b2`))
  2986. id2 = getIDByName(c, name)
  2987. if id1 == id2 {
  2988. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s)", id1, id2)
  2989. }
  2990. }
  2991. // FIXME(vdemeester) port to docker/cli e2e tests (api tests should test suppressOutput option though)
  2992. func (s *DockerCLIBuildSuite) TestBuildNotVerboseSuccess(c *testing.T) {
  2993. // This test makes sure that -q works correctly when build is successful:
  2994. // stdout has only the image ID (long image ID) and stderr is empty.
  2995. outRegexp := regexp.MustCompile(`^(sha256:|)[a-z0-9]{64}\n$`)
  2996. buildFlags := cli.WithFlags("-q")
  2997. tt := []struct {
  2998. Name string
  2999. BuildFunc func(string) *icmd.Result
  3000. }{
  3001. {
  3002. Name: "quiet_build_stdin_success",
  3003. BuildFunc: func(name string) *icmd.Result {
  3004. return buildImage(name, buildFlags, build.WithDockerfile("FROM busybox"))
  3005. },
  3006. },
  3007. {
  3008. Name: "quiet_build_ctx_success",
  3009. BuildFunc: func(name string) *icmd.Result {
  3010. return buildImage(name, buildFlags, build.WithBuildContext(c,
  3011. build.WithFile("Dockerfile", "FROM busybox"),
  3012. build.WithFile("quiet_build_success_fctx", "test"),
  3013. ))
  3014. },
  3015. },
  3016. {
  3017. Name: "quiet_build_git_success",
  3018. BuildFunc: func(name string) *icmd.Result {
  3019. git := fakegit.New(c, "repo", map[string]string{
  3020. "Dockerfile": "FROM busybox",
  3021. }, true)
  3022. return buildImage(name, buildFlags, build.WithContextPath(git.RepoURL))
  3023. },
  3024. },
  3025. }
  3026. for _, te := range tt {
  3027. result := te.BuildFunc(te.Name)
  3028. result.Assert(c, icmd.Success)
  3029. if outRegexp.Find([]byte(result.Stdout())) == nil {
  3030. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, result.Stdout())
  3031. }
  3032. if result.Stderr() != "" {
  3033. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, result.Stderr())
  3034. }
  3035. }
  3036. }
  3037. // FIXME(vdemeester) migrate to docker/cli tests
  3038. func (s *DockerCLIBuildSuite) TestBuildNotVerboseFailureWithNonExistImage(c *testing.T) {
  3039. // This test makes sure that -q works correctly when build fails by
  3040. // comparing between the stderr output in quiet mode and in stdout
  3041. // and stderr output in verbose mode
  3042. testRequires(c, Network)
  3043. testName := "quiet_build_not_exists_image"
  3044. dockerfile := "FROM busybox11"
  3045. quietResult := buildImage(testName, cli.WithFlags("-q"), build.WithDockerfile(dockerfile))
  3046. quietResult.Assert(c, icmd.Expected{
  3047. ExitCode: 1,
  3048. })
  3049. result := buildImage(testName, build.WithDockerfile(dockerfile))
  3050. result.Assert(c, icmd.Expected{
  3051. ExitCode: 1,
  3052. })
  3053. if quietResult.Stderr() != result.Combined() {
  3054. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", testName, quietResult.Stderr(), result.Combined()))
  3055. }
  3056. }
  3057. // FIXME(vdemeester) migrate to docker/cli tests
  3058. func (s *DockerCLIBuildSuite) TestBuildNotVerboseFailure(c *testing.T) {
  3059. // This test makes sure that -q works correctly when build fails by
  3060. // comparing between the stderr output in quiet mode and in stdout
  3061. // and stderr output in verbose mode
  3062. testCases := []struct {
  3063. testName string
  3064. dockerfile string
  3065. }{
  3066. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  3067. {"quiet_build_unknown_instr", "FROMD busybox"},
  3068. }
  3069. for _, tc := range testCases {
  3070. quietResult := buildImage(tc.testName, cli.WithFlags("-q"), build.WithDockerfile(tc.dockerfile))
  3071. quietResult.Assert(c, icmd.Expected{
  3072. ExitCode: 1,
  3073. })
  3074. result := buildImage(tc.testName, build.WithDockerfile(tc.dockerfile))
  3075. result.Assert(c, icmd.Expected{
  3076. ExitCode: 1,
  3077. })
  3078. if quietResult.Stderr() != result.Combined() {
  3079. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", tc.testName, quietResult.Stderr(), result.Combined()))
  3080. }
  3081. }
  3082. }
  3083. // FIXME(vdemeester) migrate to docker/cli tests
  3084. func (s *DockerCLIBuildSuite) TestBuildNotVerboseFailureRemote(c *testing.T) {
  3085. // This test ensures that when given a wrong URL, stderr in quiet mode and
  3086. // stderr in verbose mode are identical.
  3087. // TODO(vdemeester) with cobra, stdout has a carriage return too much so this test should not check stdout
  3088. URL := "http://something.invalid"
  3089. const name = "quiet_build_wrong_remote"
  3090. quietResult := buildImage(name, cli.WithFlags("-q"), build.WithContextPath(URL))
  3091. quietResult.Assert(c, icmd.Expected{
  3092. ExitCode: 1,
  3093. })
  3094. result := buildImage(name, build.WithContextPath(URL))
  3095. result.Assert(c, icmd.Expected{
  3096. ExitCode: 1,
  3097. })
  3098. // An error message should contain name server IP and port, like this:
  3099. // "dial tcp: lookup something.invalid on 172.29.128.11:53: no such host"
  3100. // The IP:port need to be removed in order to not trigger a test failur
  3101. // when more than one nameserver is configured.
  3102. // While at it, also strip excessive newlines.
  3103. normalize := func(msg string) string {
  3104. return strings.TrimSpace(regexp.MustCompile("[1-9][0-9.]+:[0-9]+").ReplaceAllLiteralString(msg, "<ip:port>"))
  3105. }
  3106. if normalize(quietResult.Stderr()) != normalize(result.Combined()) {
  3107. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", name, quietResult.Stderr(), result.Combined()))
  3108. }
  3109. }
  3110. // FIXME(vdemeester) migrate to docker/cli tests
  3111. func (s *DockerCLIBuildSuite) TestBuildStderr(c *testing.T) {
  3112. // This test just makes sure that no non-error output goes
  3113. // to stderr
  3114. const name = "testbuildstderr"
  3115. result := buildImage(name, build.WithDockerfile("FROM busybox\nRUN echo one"))
  3116. result.Assert(c, icmd.Success)
  3117. // Windows to non-Windows should have a security warning
  3118. if runtime.GOOS == "windows" && testEnv.DaemonInfo.OSType != "windows" && !strings.Contains(result.Stdout(), "SECURITY WARNING:") {
  3119. c.Fatalf("Stdout contains unexpected output: %q", result.Stdout())
  3120. }
  3121. // Stderr should always be empty
  3122. if result.Stderr() != "" {
  3123. c.Fatalf("Stderr should have been empty, instead it's: %q", result.Stderr())
  3124. }
  3125. }
  3126. func (s *DockerCLIBuildSuite) TestBuildChownSingleFile(c *testing.T) {
  3127. testRequires(c, UnixCli, DaemonIsLinux) // test uses chown: not available on windows
  3128. const name = "testbuildchownsinglefile"
  3129. ctx := fakecontext.New(c, "",
  3130. fakecontext.WithDockerfile(`
  3131. FROM busybox
  3132. COPY test /
  3133. RUN ls -l /test
  3134. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3135. `),
  3136. fakecontext.WithFiles(map[string]string{
  3137. "test": "test",
  3138. }))
  3139. defer ctx.Close()
  3140. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  3141. c.Fatal(err)
  3142. }
  3143. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  3144. }
  3145. func (s *DockerCLIBuildSuite) TestBuildSymlinkBreakout(c *testing.T) {
  3146. const name = "testbuildsymlinkbreakout"
  3147. tmpdir, err := os.MkdirTemp("", name)
  3148. assert.NilError(c, err)
  3149. // See https://github.com/moby/moby/pull/37770 for reason for next line.
  3150. tmpdir, err = getLongPathName(tmpdir)
  3151. assert.NilError(c, err)
  3152. defer os.RemoveAll(tmpdir)
  3153. ctx := filepath.Join(tmpdir, "context")
  3154. if err := os.MkdirAll(ctx, 0o755); err != nil {
  3155. c.Fatal(err)
  3156. }
  3157. if err := os.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  3158. from busybox
  3159. add symlink.tar /
  3160. add inject /symlink/
  3161. `), 0o644); err != nil {
  3162. c.Fatal(err)
  3163. }
  3164. inject := filepath.Join(ctx, "inject")
  3165. if err := os.WriteFile(inject, nil, 0o644); err != nil {
  3166. c.Fatal(err)
  3167. }
  3168. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  3169. if err != nil {
  3170. c.Fatal(err)
  3171. }
  3172. w := tar.NewWriter(f)
  3173. w.WriteHeader(&tar.Header{
  3174. Name: "symlink2",
  3175. Typeflag: tar.TypeSymlink,
  3176. Linkname: "/../../../../../../../../../../../../../../",
  3177. Uid: os.Getuid(),
  3178. Gid: os.Getgid(),
  3179. })
  3180. w.WriteHeader(&tar.Header{
  3181. Name: "symlink",
  3182. Typeflag: tar.TypeSymlink,
  3183. Linkname: filepath.Join("symlink2", tmpdir),
  3184. Uid: os.Getuid(),
  3185. Gid: os.Getgid(),
  3186. })
  3187. w.Close()
  3188. f.Close()
  3189. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(fakecontext.New(c, ctx)))
  3190. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  3191. c.Fatal("symlink breakout - inject")
  3192. } else if !os.IsNotExist(err) {
  3193. c.Fatalf("unexpected error: %v", err)
  3194. }
  3195. }
  3196. func (s *DockerCLIBuildSuite) TestBuildXZHost(c *testing.T) {
  3197. // /usr/local/sbin/xz gets permission denied for the user
  3198. testRequires(c, NotUserNamespace)
  3199. testRequires(c, DaemonIsLinux)
  3200. const name = "testbuildxzhost"
  3201. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3202. build.WithFile("Dockerfile", `
  3203. FROM busybox
  3204. ADD xz /usr/local/sbin/
  3205. RUN chmod 755 /usr/local/sbin/xz
  3206. ADD test.xz /
  3207. RUN [ ! -e /injected ]`),
  3208. build.WithFile("test.xz", "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00"+"\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd"+"\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21"),
  3209. build.WithFile("xz", "#!/bin/sh\ntouch /injected"),
  3210. ))
  3211. }
  3212. func (s *DockerCLIBuildSuite) TestBuildVolumesRetainContents(c *testing.T) {
  3213. // /foo/file gets permission denied for the user
  3214. testRequires(c, NotUserNamespace)
  3215. testRequires(c, DaemonIsLinux) // TODO Windows: Issue #20127
  3216. var (
  3217. name = "testbuildvolumescontent"
  3218. expected = "some text"
  3219. volName = "/foo"
  3220. )
  3221. if testEnv.DaemonInfo.OSType == "windows" {
  3222. volName = "C:/foo"
  3223. }
  3224. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3225. build.WithFile("Dockerfile", `
  3226. FROM busybox
  3227. COPY content /foo/file
  3228. VOLUME `+volName+`
  3229. CMD cat /foo/file`),
  3230. build.WithFile("content", expected),
  3231. ))
  3232. out := cli.DockerCmd(c, "run", "--rm", name).Combined()
  3233. if out != expected {
  3234. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  3235. }
  3236. }
  3237. func (s *DockerCLIBuildSuite) TestBuildFromMixedcaseDockerfile(c *testing.T) {
  3238. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  3239. testRequires(c, DaemonIsLinux)
  3240. // If Dockerfile is not present, use dockerfile
  3241. buildImage("test1", build.WithBuildContext(c,
  3242. build.WithFile("dockerfile", `FROM busybox
  3243. RUN echo from dockerfile`),
  3244. )).Assert(c, icmd.Expected{
  3245. Out: "from dockerfile",
  3246. })
  3247. // Prefer Dockerfile in place of dockerfile
  3248. buildImage("test1", build.WithBuildContext(c,
  3249. build.WithFile("dockerfile", `FROM busybox
  3250. RUN echo from dockerfile`),
  3251. build.WithFile("Dockerfile", `FROM busybox
  3252. RUN echo from Dockerfile`),
  3253. )).Assert(c, icmd.Expected{
  3254. Out: "from Dockerfile",
  3255. })
  3256. }
  3257. // FIXME(vdemeester) should migrate to docker/cli tests
  3258. func (s *DockerCLIBuildSuite) TestBuildFromURLWithF(c *testing.T) {
  3259. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{"baz": `FROM busybox
  3260. RUN echo from baz
  3261. COPY * /tmp/
  3262. RUN find /tmp/`}))
  3263. defer server.Close()
  3264. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3265. RUN echo from Dockerfile`))
  3266. defer ctx.Close()
  3267. // Make sure that -f is ignored and that we don't use the Dockerfile
  3268. // that's in the current dir
  3269. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", server.URL()+"/baz"), func(cmd *icmd.Cmd) func() {
  3270. cmd.Dir = ctx.Dir
  3271. return nil
  3272. })
  3273. if !strings.Contains(result.Combined(), "from baz") ||
  3274. strings.Contains(result.Combined(), "/tmp/baz") ||
  3275. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3276. c.Fatalf("Missing proper output: %s", result.Combined())
  3277. }
  3278. }
  3279. // FIXME(vdemeester) should migrate to docker/cli tests
  3280. func (s *DockerCLIBuildSuite) TestBuildFromStdinWithF(c *testing.T) {
  3281. testRequires(c, DaemonIsLinux) // TODO Windows: This test is flaky; no idea why
  3282. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3283. RUN echo "from Dockerfile"`))
  3284. defer ctx.Close()
  3285. // Make sure that -f is ignored and that we don't use the Dockerfile
  3286. // that's in the current dir
  3287. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", "-"), func(cmd *icmd.Cmd) func() {
  3288. cmd.Dir = ctx.Dir
  3289. cmd.Stdin = strings.NewReader(`FROM busybox
  3290. RUN echo "from baz"
  3291. COPY * /tmp/
  3292. RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`)
  3293. return nil
  3294. })
  3295. if !strings.Contains(result.Combined(), "from baz") ||
  3296. strings.Contains(result.Combined(), "/tmp/baz") ||
  3297. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3298. c.Fatalf("Missing proper output: %s", result.Combined())
  3299. }
  3300. }
  3301. func (s *DockerCLIBuildSuite) TestBuildFromOfficialNames(c *testing.T) {
  3302. const name = "testbuildfromofficial"
  3303. fromNames := []string{
  3304. "busybox",
  3305. "docker.io/busybox",
  3306. "index.docker.io/busybox",
  3307. "library/busybox",
  3308. "docker.io/library/busybox",
  3309. "index.docker.io/library/busybox",
  3310. }
  3311. for idx, fromName := range fromNames {
  3312. imgName := fmt.Sprintf("%s%d", name, idx)
  3313. buildImageSuccessfully(c, imgName, build.WithDockerfile("FROM "+fromName))
  3314. cli.DockerCmd(c, "rmi", imgName)
  3315. }
  3316. }
  3317. // FIXME(vdemeester) should be a unit test
  3318. func (s *DockerCLIBuildSuite) TestBuildSpaces(c *testing.T) {
  3319. // Test to make sure that leading/trailing spaces on a command
  3320. // doesn't change the error msg we get
  3321. const name = "testspaces"
  3322. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM busybox\nCOPY\n"))
  3323. defer ctx.Close()
  3324. result1 := cli.Docker(cli.Args("build", "-t", name), build.WithExternalBuildContext(ctx))
  3325. result1.Assert(c, icmd.Expected{
  3326. ExitCode: 1,
  3327. })
  3328. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  3329. result2 := cli.Docker(cli.Args("build", "-t", name), build.WithExternalBuildContext(ctx))
  3330. result2.Assert(c, icmd.Expected{
  3331. ExitCode: 1,
  3332. })
  3333. removeLogTimestamps := func(s string) string {
  3334. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  3335. }
  3336. // Skip over the times
  3337. e1 := removeLogTimestamps(result1.Error.Error())
  3338. e2 := removeLogTimestamps(result2.Error.Error())
  3339. // Ignore whitespace since that's what were verifying doesn't change stuff
  3340. if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
  3341. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
  3342. }
  3343. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  3344. result2 = cli.Docker(cli.Args("build", "-t", name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3345. result2.Assert(c, icmd.Expected{
  3346. ExitCode: 1,
  3347. })
  3348. // Skip over the times
  3349. e1 = removeLogTimestamps(result1.Error.Error())
  3350. e2 = removeLogTimestamps(result2.Error.Error())
  3351. // Ignore whitespace since that's what were verifying doesn't change stuff
  3352. if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
  3353. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
  3354. }
  3355. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  3356. result2 = cli.Docker(cli.Args("build", "-t", name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3357. result2.Assert(c, icmd.Expected{
  3358. ExitCode: 1,
  3359. })
  3360. // Skip over the times
  3361. e1 = removeLogTimestamps(result1.Error.Error())
  3362. e2 = removeLogTimestamps(result2.Error.Error())
  3363. // Ignore whitespace since that's what were verifying doesn't change stuff
  3364. if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
  3365. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
  3366. }
  3367. }
  3368. func (s *DockerCLIBuildSuite) TestBuildSpacesWithQuotes(c *testing.T) {
  3369. // Test to make sure that spaces in quotes aren't lost
  3370. const name = "testspacesquotes"
  3371. dockerfile := `FROM busybox
  3372. RUN echo " \
  3373. foo "`
  3374. expected := "\n foo \n"
  3375. // Windows uses the builtin echo, which preserves quotes
  3376. if testEnv.DaemonInfo.OSType == "windows" {
  3377. expected = "\" foo \""
  3378. }
  3379. buildImage(name, build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3380. Out: expected,
  3381. })
  3382. }
  3383. // #4393
  3384. func (s *DockerCLIBuildSuite) TestBuildVolumeFileExistsinContainer(c *testing.T) {
  3385. testRequires(c, DaemonIsLinux) // TODO Windows: This should error out
  3386. buildImage("docker-test-errcreatevolumewithfile", build.WithDockerfile(`
  3387. FROM busybox
  3388. RUN touch /foo
  3389. VOLUME /foo
  3390. `)).Assert(c, icmd.Expected{
  3391. ExitCode: 1,
  3392. Err: "file exists",
  3393. })
  3394. }
  3395. // FIXME(vdemeester) should be a unit test
  3396. func (s *DockerCLIBuildSuite) TestBuildMissingArgs(c *testing.T) {
  3397. // Test to make sure that all Dockerfile commands (except the ones listed
  3398. // in skipCmds) will generate an error if no args are provided.
  3399. // Note: INSERT is deprecated so we exclude it because of that.
  3400. skipCmds := map[string]struct{}{
  3401. "CMD": {},
  3402. "RUN": {},
  3403. "ENTRYPOINT": {},
  3404. "INSERT": {},
  3405. }
  3406. if testEnv.DaemonInfo.OSType == "windows" {
  3407. skipCmds = map[string]struct{}{
  3408. "CMD": {},
  3409. "RUN": {},
  3410. "ENTRYPOINT": {},
  3411. "INSERT": {},
  3412. "STOPSIGNAL": {},
  3413. "ARG": {},
  3414. "USER": {},
  3415. "EXPOSE": {},
  3416. }
  3417. }
  3418. for cmd := range command.Commands {
  3419. cmd = strings.ToUpper(cmd)
  3420. if _, ok := skipCmds[cmd]; ok {
  3421. continue
  3422. }
  3423. var dockerfile string
  3424. if cmd == "FROM" {
  3425. dockerfile = cmd
  3426. } else {
  3427. // Add FROM to make sure we don't complain about it missing
  3428. dockerfile = "FROM busybox\n" + cmd
  3429. }
  3430. buildImage("args", build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3431. ExitCode: 1,
  3432. Err: cmd + " requires",
  3433. })
  3434. }
  3435. }
  3436. func (s *DockerCLIBuildSuite) TestBuildEmptyScratch(c *testing.T) {
  3437. testRequires(c, DaemonIsLinux)
  3438. buildImage("sc", build.WithDockerfile("FROM scratch")).Assert(c, icmd.Expected{
  3439. ExitCode: 1,
  3440. Err: "No image was generated",
  3441. })
  3442. }
  3443. func (s *DockerCLIBuildSuite) TestBuildDotDotFile(c *testing.T) {
  3444. buildImageSuccessfully(c, "sc", build.WithBuildContext(c,
  3445. build.WithFile("Dockerfile", "FROM busybox\n"),
  3446. build.WithFile("..gitme", ""),
  3447. ))
  3448. }
  3449. func (s *DockerCLIBuildSuite) TestBuildRUNoneJSON(c *testing.T) {
  3450. testRequires(c, DaemonIsLinux) // No hello-world Windows image
  3451. const name = "testbuildrunonejson"
  3452. buildImage(name, build.WithDockerfile(`FROM hello-world:frozen
  3453. RUN [ "/hello" ]`)).Assert(c, icmd.Expected{
  3454. Out: "Hello from Docker",
  3455. })
  3456. }
  3457. func (s *DockerCLIBuildSuite) TestBuildEmptyStringVolume(c *testing.T) {
  3458. const name = "testbuildemptystringvolume"
  3459. buildImage(name, build.WithDockerfile(`
  3460. FROM busybox
  3461. ENV foo=""
  3462. VOLUME $foo
  3463. `)).Assert(c, icmd.Expected{
  3464. ExitCode: 1,
  3465. })
  3466. }
  3467. func (s *DockerCLIBuildSuite) TestBuildContainerWithCgroupParent(c *testing.T) {
  3468. testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  3469. cgroupParent := "test"
  3470. data, err := os.ReadFile("/proc/self/cgroup")
  3471. if err != nil {
  3472. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  3473. }
  3474. selfCgroupPaths := ParseCgroupPaths(string(data))
  3475. _, found := selfCgroupPaths["memory"]
  3476. if !found {
  3477. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  3478. }
  3479. result := buildImage("buildcgroupparent",
  3480. cli.WithFlags("--cgroup-parent", cgroupParent),
  3481. build.WithDockerfile(`
  3482. FROM busybox
  3483. RUN cat /proc/self/cgroup
  3484. `))
  3485. result.Assert(c, icmd.Success)
  3486. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), result.Combined())
  3487. assert.NilError(c, err)
  3488. if !m {
  3489. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, result.Combined())
  3490. }
  3491. }
  3492. // FIXME(vdemeester) could be a unit test
  3493. func (s *DockerCLIBuildSuite) TestBuildNoDupOutput(c *testing.T) {
  3494. // Check to make sure our build output prints the Dockerfile cmd
  3495. // property - there was a bug that caused it to be duplicated on the
  3496. // Step X line
  3497. const name = "testbuildnodupoutput"
  3498. result := buildImage(name, build.WithDockerfile(`
  3499. FROM busybox
  3500. RUN env`))
  3501. result.Assert(c, icmd.Success)
  3502. exp := "\nStep 2/2 : RUN env\n"
  3503. if !strings.Contains(result.Combined(), exp) {
  3504. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3505. }
  3506. }
  3507. // GH15826
  3508. // FIXME(vdemeester) could be a unit test
  3509. func (s *DockerCLIBuildSuite) TestBuildStartsFromOne(c *testing.T) {
  3510. // Explicit check to ensure that build starts from step 1 rather than 0
  3511. const name = "testbuildstartsfromone"
  3512. result := buildImage(name, build.WithDockerfile(`FROM busybox`))
  3513. result.Assert(c, icmd.Success)
  3514. exp := "\nStep 1/1 : FROM busybox\n"
  3515. if !strings.Contains(result.Combined(), exp) {
  3516. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3517. }
  3518. }
  3519. func (s *DockerCLIBuildSuite) TestBuildRUNErrMsg(c *testing.T) {
  3520. // Test to make sure the bad command is quoted with just "s and
  3521. // not as a Go []string
  3522. const name = "testbuildbadrunerrmsg"
  3523. shell := "/bin/sh -c"
  3524. exitCode := 127
  3525. if testEnv.DaemonInfo.OSType == "windows" {
  3526. shell = "cmd /S /C"
  3527. // architectural - Windows has to start the container to determine the exe is bad, Linux does not
  3528. exitCode = 1
  3529. }
  3530. exp := fmt.Sprintf(`The command '%s badEXE a1 \& a2 a3' returned a non-zero code: %d`, shell, exitCode)
  3531. buildImage(name, build.WithDockerfile(`
  3532. FROM busybox
  3533. RUN badEXE a1 \& a2 a3`)).Assert(c, icmd.Expected{
  3534. ExitCode: exitCode,
  3535. Err: exp,
  3536. })
  3537. }
  3538. // Issue #15634: COPY fails when path starts with "null"
  3539. func (s *DockerCLIBuildSuite) TestBuildNullStringInAddCopyVolume(c *testing.T) {
  3540. const name = "testbuildnullstringinaddcopyvolume"
  3541. volName := "nullvolume"
  3542. if testEnv.DaemonInfo.OSType == "windows" {
  3543. volName = `C:\\nullvolume`
  3544. }
  3545. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3546. build.WithFile("Dockerfile", `
  3547. FROM busybox
  3548. ADD null /
  3549. COPY nullfile /
  3550. VOLUME `+volName+`
  3551. `),
  3552. build.WithFile("null", "test1"),
  3553. build.WithFile("nullfile", "test2"),
  3554. ))
  3555. }
  3556. func (s *DockerCLIBuildSuite) TestBuildStopSignal(c *testing.T) {
  3557. testRequires(c, DaemonIsLinux) // Windows does not support STOPSIGNAL yet
  3558. imgName := "test_build_stop_signal"
  3559. buildImageSuccessfully(c, imgName, build.WithDockerfile(`FROM busybox
  3560. STOPSIGNAL SIGKILL`))
  3561. res := inspectFieldJSON(c, imgName, "Config.StopSignal")
  3562. if res != `"SIGKILL"` {
  3563. c.Fatalf("Signal %s, expected SIGKILL", res)
  3564. }
  3565. containerName := "test-container-stop-signal"
  3566. cli.DockerCmd(c, "run", "-d", "--name", containerName, imgName, "top")
  3567. res = inspectFieldJSON(c, containerName, "Config.StopSignal")
  3568. if res != `"SIGKILL"` {
  3569. c.Fatalf("Signal %s, expected SIGKILL", res)
  3570. }
  3571. }
  3572. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArg(c *testing.T) {
  3573. imgName := "bldargtest"
  3574. envKey := "foo"
  3575. envVal := "bar"
  3576. var dockerfile string
  3577. if testEnv.DaemonInfo.OSType == "windows" {
  3578. // Bugs in Windows busybox port - use the default base image and native cmd stuff
  3579. dockerfile = fmt.Sprintf(`FROM `+minimalBaseImage()+`
  3580. ARG %s
  3581. RUN echo %%%s%%
  3582. CMD setlocal enableextensions && if defined %s (echo %%%s%%)`, envKey, envKey, envKey, envKey)
  3583. } else {
  3584. dockerfile = fmt.Sprintf(`FROM busybox
  3585. ARG %s
  3586. RUN echo $%s
  3587. CMD echo $%s`, envKey, envKey, envKey)
  3588. }
  3589. buildImage(imgName,
  3590. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3591. build.WithDockerfile(dockerfile),
  3592. ).Assert(c, icmd.Expected{
  3593. Out: envVal,
  3594. })
  3595. containerName := "bldargCont"
  3596. out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined()
  3597. out = strings.Trim(out, " \r\n'")
  3598. if out != "" {
  3599. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3600. }
  3601. }
  3602. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgHistory(c *testing.T) {
  3603. imgName := "bldargtest"
  3604. envKey := "foo"
  3605. envVal := "bar"
  3606. envDef := "bar1"
  3607. dockerfile := fmt.Sprintf(`FROM busybox
  3608. ARG %s=%s`, envKey, envDef)
  3609. buildImage(imgName,
  3610. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3611. build.WithDockerfile(dockerfile),
  3612. ).Assert(c, icmd.Expected{
  3613. Out: envVal,
  3614. })
  3615. out := cli.DockerCmd(c, "history", "--no-trunc", imgName).Combined()
  3616. outputTabs := strings.Split(out, "\n")[1]
  3617. if !strings.Contains(outputTabs, envDef) {
  3618. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  3619. }
  3620. }
  3621. func (s *DockerCLIBuildSuite) TestBuildTimeArgHistoryExclusions(c *testing.T) {
  3622. imgName := "bldargtest"
  3623. envKey := "foo"
  3624. envVal := "bar"
  3625. proxy := "HTTP_PROXY=http://user:password@proxy.example.com"
  3626. explicitProxyKey := "http_proxy"
  3627. explicitProxyVal := "http://user:password@someproxy.example.com"
  3628. dockerfile := fmt.Sprintf(`FROM busybox
  3629. ARG %s
  3630. ARG %s
  3631. RUN echo "Testing Build Args!"`, envKey, explicitProxyKey)
  3632. buildImage := func(imgName string) string {
  3633. cli.BuildCmd(c, imgName,
  3634. cli.WithFlags("--build-arg", "https_proxy=https://proxy.example.com",
  3635. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3636. "--build-arg", fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal),
  3637. "--build-arg", proxy),
  3638. build.WithDockerfile(dockerfile),
  3639. )
  3640. return getIDByName(c, imgName)
  3641. }
  3642. origID := buildImage(imgName)
  3643. result := cli.DockerCmd(c, "history", "--no-trunc", imgName)
  3644. out := result.Stdout()
  3645. if strings.Contains(out, proxy) {
  3646. c.Fatalf("failed to exclude proxy settings from history!")
  3647. }
  3648. if strings.Contains(out, "https_proxy") {
  3649. c.Fatalf("failed to exclude proxy settings from history!")
  3650. }
  3651. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", envKey, envVal)})
  3652. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal)})
  3653. cacheID := buildImage(imgName + "-two")
  3654. assert.Equal(c, origID, cacheID)
  3655. }
  3656. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgCacheHit(c *testing.T) {
  3657. imgName := "bldargtest"
  3658. envKey := "foo"
  3659. envVal := "bar"
  3660. dockerfile := fmt.Sprintf(`FROM busybox
  3661. ARG %s
  3662. RUN echo $%s`, envKey, envKey)
  3663. buildImageSuccessfully(c, imgName,
  3664. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3665. build.WithDockerfile(dockerfile),
  3666. )
  3667. origImgID := getIDByName(c, imgName)
  3668. imgNameCache := "bldargtestcachehit"
  3669. buildImageSuccessfully(c, imgNameCache,
  3670. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3671. build.WithDockerfile(dockerfile),
  3672. )
  3673. newImgID := getIDByName(c, imgName)
  3674. if newImgID != origImgID {
  3675. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  3676. }
  3677. }
  3678. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *testing.T) {
  3679. imgName := "bldargtest"
  3680. envKey := "foo"
  3681. envVal := "bar"
  3682. extraEnvKey := "foo1"
  3683. extraEnvVal := "bar1"
  3684. dockerfile := fmt.Sprintf(`FROM busybox
  3685. ARG %s
  3686. ARG %s
  3687. RUN echo $%s`, envKey, extraEnvKey, envKey)
  3688. buildImageSuccessfully(c, imgName,
  3689. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3690. build.WithDockerfile(dockerfile),
  3691. )
  3692. origImgID := getIDByName(c, imgName)
  3693. imgNameCache := "bldargtestcachemiss"
  3694. buildImageSuccessfully(c, imgNameCache,
  3695. cli.WithFlags(
  3696. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3697. "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal),
  3698. ),
  3699. build.WithDockerfile(dockerfile),
  3700. )
  3701. newImgID := getIDByName(c, imgNameCache)
  3702. if newImgID == origImgID {
  3703. c.Fatalf("build used cache, expected a miss!")
  3704. }
  3705. }
  3706. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *testing.T) {
  3707. imgName := "bldargtest"
  3708. envKey := "foo"
  3709. envVal := "bar"
  3710. newEnvVal := "bar1"
  3711. dockerfile := fmt.Sprintf(`FROM busybox
  3712. ARG %s
  3713. RUN echo $%s`, envKey, envKey)
  3714. buildImageSuccessfully(c, imgName,
  3715. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3716. build.WithDockerfile(dockerfile),
  3717. )
  3718. origImgID := getIDByName(c, imgName)
  3719. imgNameCache := "bldargtestcachemiss"
  3720. buildImageSuccessfully(c, imgNameCache,
  3721. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal)),
  3722. build.WithDockerfile(dockerfile),
  3723. )
  3724. newImgID := getIDByName(c, imgNameCache)
  3725. if newImgID == origImgID {
  3726. c.Fatalf("build used cache, expected a miss!")
  3727. }
  3728. }
  3729. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *testing.T) {
  3730. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3731. imgName := "bldargtest"
  3732. envKey := "foo"
  3733. envVal := "bar"
  3734. envValOverride := "barOverride"
  3735. dockerfile := fmt.Sprintf(`FROM busybox
  3736. ARG %s
  3737. ENV %s %s
  3738. RUN echo $%s
  3739. CMD echo $%s
  3740. `, envKey, envKey, envValOverride, envKey, envKey)
  3741. result := buildImage(imgName,
  3742. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3743. build.WithDockerfile(dockerfile),
  3744. )
  3745. result.Assert(c, icmd.Success)
  3746. if strings.Count(result.Combined(), envValOverride) != 2 {
  3747. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3748. }
  3749. containerName := "bldargCont"
  3750. if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); !strings.Contains(out, envValOverride) {
  3751. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3752. }
  3753. }
  3754. // FIXME(vdemeester) might be useful to merge with the one above ?
  3755. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *testing.T) {
  3756. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3757. imgName := "bldargtest"
  3758. envKey := "foo"
  3759. envVal := "bar"
  3760. envValOverride := "barOverride"
  3761. dockerfile := fmt.Sprintf(`FROM busybox
  3762. ENV %s %s
  3763. ARG %s
  3764. RUN echo $%s
  3765. CMD echo $%s
  3766. `, envKey, envValOverride, envKey, envKey, envKey)
  3767. result := buildImage(imgName,
  3768. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3769. build.WithDockerfile(dockerfile),
  3770. )
  3771. result.Assert(c, icmd.Success)
  3772. if strings.Count(result.Combined(), envValOverride) != 2 {
  3773. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3774. }
  3775. containerName := "bldargCont"
  3776. if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); !strings.Contains(out, envValOverride) {
  3777. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3778. }
  3779. }
  3780. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgExpansion(c *testing.T) {
  3781. imgName := "bldvarstest"
  3782. wdVar := "WDIR"
  3783. wdVal := "/tmp/"
  3784. addVar := "AFILE"
  3785. addVal := "addFile"
  3786. copyVar := "CFILE"
  3787. copyVal := "copyFile"
  3788. envVar := "foo"
  3789. envVal := "bar"
  3790. exposeVar := "EPORT"
  3791. exposeVal := "9999"
  3792. userVar := "USER"
  3793. userVal := "testUser"
  3794. volVar := "VOL"
  3795. volVal := "/testVol/"
  3796. if DaemonIsWindows() {
  3797. volVal = "C:\\testVol"
  3798. wdVal = "C:\\tmp"
  3799. }
  3800. buildImageSuccessfully(c, imgName,
  3801. cli.WithFlags(
  3802. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  3803. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  3804. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  3805. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  3806. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  3807. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  3808. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  3809. ),
  3810. build.WithBuildContext(c,
  3811. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  3812. ARG %s
  3813. WORKDIR ${%s}
  3814. ARG %s
  3815. ADD ${%s} testDir/
  3816. ARG %s
  3817. COPY $%s testDir/
  3818. ARG %s
  3819. ENV %s=${%s}
  3820. ARG %s
  3821. EXPOSE $%s
  3822. ARG %s
  3823. USER $%s
  3824. ARG %s
  3825. VOLUME ${%s}`,
  3826. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  3827. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar)),
  3828. build.WithFile(addVal, "some stuff"),
  3829. build.WithFile(copyVal, "some stuff"),
  3830. ),
  3831. )
  3832. res := inspectField(c, imgName, "Config.WorkingDir")
  3833. assert.Equal(c, filepath.ToSlash(res), filepath.ToSlash(wdVal))
  3834. var resArr []string
  3835. inspectFieldAndUnmarshall(c, imgName, "Config.Env", &resArr)
  3836. found := false
  3837. for _, v := range resArr {
  3838. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  3839. found = true
  3840. break
  3841. }
  3842. }
  3843. if !found {
  3844. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  3845. envVar, envVal, resArr)
  3846. }
  3847. var resMap map[string]interface{}
  3848. inspectFieldAndUnmarshall(c, imgName, "Config.ExposedPorts", &resMap)
  3849. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  3850. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  3851. }
  3852. res = inspectField(c, imgName, "Config.User")
  3853. if res != userVal {
  3854. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  3855. }
  3856. inspectFieldAndUnmarshall(c, imgName, "Config.Volumes", &resMap)
  3857. if _, ok := resMap[volVal]; !ok {
  3858. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  3859. }
  3860. }
  3861. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgExpansionOverride(c *testing.T) {
  3862. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3863. imgName := "bldvarstest"
  3864. envKey := "foo"
  3865. envVal := "bar"
  3866. envKey1 := "foo1"
  3867. envValOverride := "barOverride"
  3868. dockerfile := fmt.Sprintf(`FROM busybox
  3869. ARG %s
  3870. ENV %s %s
  3871. ENV %s ${%s}
  3872. RUN echo $%s
  3873. CMD echo $%s`, envKey, envKey, envValOverride, envKey1, envKey, envKey1, envKey1)
  3874. result := buildImage(imgName,
  3875. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3876. build.WithDockerfile(dockerfile),
  3877. )
  3878. result.Assert(c, icmd.Success)
  3879. if strings.Count(result.Combined(), envValOverride) != 2 {
  3880. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3881. }
  3882. containerName := "bldargCont"
  3883. if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); !strings.Contains(out, envValOverride) {
  3884. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3885. }
  3886. }
  3887. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *testing.T) {
  3888. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3889. imgName := "bldargtest"
  3890. envKey := "foo"
  3891. envVal := "bar"
  3892. dockerfile := fmt.Sprintf(`FROM busybox
  3893. RUN echo $%s
  3894. ARG %s
  3895. CMD echo $%s`, envKey, envKey, envKey)
  3896. result := buildImage(imgName,
  3897. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3898. build.WithDockerfile(dockerfile),
  3899. )
  3900. result.Assert(c, icmd.Success)
  3901. if strings.Contains(result.Combined(), envVal) {
  3902. c.Fatalf("able to access environment variable in output: %q expected to be missing", result.Combined())
  3903. }
  3904. containerName := "bldargCont"
  3905. if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); out != "\n" {
  3906. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3907. }
  3908. }
  3909. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgBuiltinArg(c *testing.T) {
  3910. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  3911. imgName := "bldargtest"
  3912. envKey := "HTTP_PROXY"
  3913. envVal := "bar"
  3914. dockerfile := fmt.Sprintf(`FROM busybox
  3915. RUN echo $%s
  3916. CMD echo $%s`, envKey, envKey)
  3917. result := buildImage(imgName,
  3918. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3919. build.WithDockerfile(dockerfile),
  3920. )
  3921. result.Assert(c, icmd.Success)
  3922. if !strings.Contains(result.Combined(), envVal) {
  3923. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envVal)
  3924. }
  3925. containerName := "bldargCont"
  3926. if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); out != "\n" {
  3927. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3928. }
  3929. }
  3930. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgDefaultOverride(c *testing.T) {
  3931. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3932. imgName := "bldargtest"
  3933. envKey := "foo"
  3934. envVal := "bar"
  3935. envValOverride := "barOverride"
  3936. dockerfile := fmt.Sprintf(`FROM busybox
  3937. ARG %s=%s
  3938. ENV %s $%s
  3939. RUN echo $%s
  3940. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  3941. result := buildImage(imgName,
  3942. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envValOverride)),
  3943. build.WithDockerfile(dockerfile),
  3944. )
  3945. result.Assert(c, icmd.Success)
  3946. if strings.Count(result.Combined(), envValOverride) != 1 {
  3947. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3948. }
  3949. containerName := "bldargCont"
  3950. if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); !strings.Contains(out, envValOverride) {
  3951. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3952. }
  3953. }
  3954. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgUnconsumedArg(c *testing.T) {
  3955. imgName := "bldargtest"
  3956. envKey := "foo"
  3957. envVal := "bar"
  3958. dockerfile := fmt.Sprintf(`FROM busybox
  3959. RUN echo $%s
  3960. CMD echo $%s`, envKey, envKey)
  3961. warnStr := "[Warning] One or more build-args"
  3962. buildImage(imgName,
  3963. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3964. build.WithDockerfile(dockerfile),
  3965. ).Assert(c, icmd.Expected{
  3966. Out: warnStr,
  3967. })
  3968. }
  3969. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgEnv(c *testing.T) {
  3970. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3971. dockerfile := `FROM busybox
  3972. ARG FOO1=fromfile
  3973. ARG FOO2=fromfile
  3974. ARG FOO3=fromfile
  3975. ARG FOO4=fromfile
  3976. ARG FOO5
  3977. ARG FOO6
  3978. ARG FO10
  3979. RUN env
  3980. RUN [ "$FOO1" = "fromcmd" ]
  3981. RUN [ "$FOO2" = "" ]
  3982. RUN [ "$FOO3" = "fromenv" ]
  3983. RUN [ "$FOO4" = "fromfile" ]
  3984. RUN [ "$FOO5" = "fromcmd" ]
  3985. # The following should not exist at all in the env
  3986. RUN [ "$(env | grep FOO6)" = "" ]
  3987. RUN [ "$(env | grep FOO7)" = "" ]
  3988. RUN [ "$(env | grep FOO8)" = "" ]
  3989. RUN [ "$(env | grep FOO9)" = "" ]
  3990. RUN [ "$FO10" = "" ]
  3991. `
  3992. result := buildImage("testbuildtimeargenv",
  3993. cli.WithFlags(
  3994. "--build-arg", "FOO1=fromcmd",
  3995. "--build-arg", "FOO2=",
  3996. "--build-arg", "FOO3", // set in env
  3997. "--build-arg", "FOO4", // not set in env
  3998. "--build-arg", "FOO5=fromcmd",
  3999. // FOO6 is not set at all
  4000. "--build-arg", "FOO7=fromcmd", // should produce a warning
  4001. "--build-arg", "FOO8=", // should produce a warning
  4002. "--build-arg", "FOO9", // should produce a warning
  4003. "--build-arg", "FO10", // not set in env, empty value
  4004. ),
  4005. cli.WithEnvironmentVariables(append(os.Environ(),
  4006. "FOO1=fromenv",
  4007. "FOO2=fromenv",
  4008. "FOO3=fromenv")...),
  4009. build.WithBuildContext(c,
  4010. build.WithFile("Dockerfile", dockerfile),
  4011. ),
  4012. )
  4013. result.Assert(c, icmd.Success)
  4014. // Now check to make sure we got a warning msg about unused build-args
  4015. i := strings.Index(result.Combined(), "[Warning]")
  4016. if i < 0 {
  4017. c.Fatalf("Missing the build-arg warning in %q", result.Combined())
  4018. }
  4019. out := result.Combined()[i:] // "out" should contain just the warning message now
  4020. // These were specified on a --build-arg but no ARG was in the Dockerfile
  4021. assert.Assert(c, strings.Contains(out, "FOO7"))
  4022. assert.Assert(c, strings.Contains(out, "FOO8"))
  4023. assert.Assert(c, strings.Contains(out, "FOO9"))
  4024. }
  4025. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgQuotedValVariants(c *testing.T) {
  4026. imgName := "bldargtest"
  4027. envKey := "foo"
  4028. envKey1 := "foo1"
  4029. envKey2 := "foo2"
  4030. envKey3 := "foo3"
  4031. dockerfile := fmt.Sprintf(`FROM busybox
  4032. ARG %s=""
  4033. ARG %s=''
  4034. ARG %s="''"
  4035. ARG %s='""'
  4036. RUN [ "$%s" != "$%s" ]
  4037. RUN [ "$%s" != "$%s" ]
  4038. RUN [ "$%s" != "$%s" ]
  4039. RUN [ "$%s" != "$%s" ]
  4040. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  4041. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  4042. envKey2, envKey3)
  4043. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4044. }
  4045. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgEmptyValVariants(c *testing.T) {
  4046. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4047. imgName := "bldargtest"
  4048. envKey := "foo"
  4049. envKey1 := "foo1"
  4050. envKey2 := "foo2"
  4051. dockerfile := fmt.Sprintf(`FROM busybox
  4052. ARG %s=
  4053. ARG %s=""
  4054. ARG %s=''
  4055. RUN [ "$%s" = "$%s" ]
  4056. RUN [ "$%s" = "$%s" ]
  4057. RUN [ "$%s" = "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  4058. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4059. }
  4060. func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgDefinitionWithNoEnvInjection(c *testing.T) {
  4061. imgName := "bldargtest"
  4062. envKey := "foo"
  4063. dockerfile := fmt.Sprintf(`FROM busybox
  4064. ARG %s
  4065. RUN env`, envKey)
  4066. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4067. result.Assert(c, icmd.Success)
  4068. if strings.Count(result.Combined(), envKey) != 1 {
  4069. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", result.Combined())
  4070. }
  4071. }
  4072. func (s *DockerCLIBuildSuite) TestBuildMultiStageArg(c *testing.T) {
  4073. imgName := "multifrombldargtest"
  4074. dockerfile := `FROM busybox
  4075. ARG foo=abc
  4076. LABEL multifromtest=1
  4077. RUN env > /out
  4078. FROM busybox
  4079. ARG bar=def
  4080. RUN env > /out`
  4081. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4082. result.Assert(c, icmd.Success)
  4083. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4084. result.Assert(c, icmd.Success)
  4085. imgs := strings.Split(strings.TrimSpace(result.Stdout()), "\n")
  4086. assert.Assert(c, is.Len(imgs, 1), `only one image with "multifromtest" label is expected`)
  4087. parentID := imgs[0]
  4088. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4089. assert.Assert(c, strings.Contains(result.Stdout(), "foo=abc"))
  4090. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4091. assert.Assert(c, !strings.Contains(result.Stdout(), "foo"))
  4092. assert.Assert(c, strings.Contains(result.Stdout(), "bar=def"))
  4093. }
  4094. func (s *DockerCLIBuildSuite) TestBuildMultiStageGlobalArg(c *testing.T) {
  4095. imgName := "multifrombldargtest"
  4096. dockerfile := `ARG tag=nosuchtag
  4097. FROM busybox:${tag}
  4098. LABEL multifromtest2=1
  4099. RUN env > /out
  4100. FROM busybox:${tag}
  4101. ARG tag
  4102. RUN env > /out`
  4103. result := cli.BuildCmd(c, imgName,
  4104. build.WithDockerfile(dockerfile),
  4105. cli.WithFlags("--build-arg", "tag=latest"))
  4106. result.Assert(c, icmd.Success)
  4107. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest2=1")
  4108. result.Assert(c, icmd.Success)
  4109. imgs := strings.Split(strings.TrimSpace(result.Stdout()), "\n")
  4110. assert.Assert(c, is.Len(imgs, 1), `only one image with "multifromtest" label is expected`)
  4111. parentID := imgs[0]
  4112. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4113. assert.Assert(c, !strings.Contains(result.Stdout(), "tag"))
  4114. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4115. assert.Assert(c, strings.Contains(result.Stdout(), "tag=latest"))
  4116. }
  4117. func (s *DockerCLIBuildSuite) TestBuildMultiStageUnusedArg(c *testing.T) {
  4118. imgName := "multifromunusedarg"
  4119. dockerfile := `FROM busybox
  4120. ARG foo
  4121. FROM busybox
  4122. ARG bar
  4123. RUN env > /out`
  4124. result := cli.BuildCmd(c, imgName,
  4125. build.WithDockerfile(dockerfile),
  4126. cli.WithFlags("--build-arg", "baz=abc"))
  4127. result.Assert(c, icmd.Success)
  4128. assert.Assert(c, strings.Contains(result.Combined(), "[Warning]"))
  4129. assert.Assert(c, strings.Contains(result.Combined(), "[baz] were not consumed"))
  4130. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4131. assert.Assert(c, !strings.Contains(result.Stdout(), "bar"))
  4132. assert.Assert(c, !strings.Contains(result.Stdout(), "baz"))
  4133. }
  4134. func (s *DockerCLIBuildSuite) TestBuildNoNamedVolume(c *testing.T) {
  4135. volName := "testname:/foo"
  4136. if testEnv.DaemonInfo.OSType == "windows" {
  4137. volName = "testname:C:\\foo"
  4138. }
  4139. cli.DockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops")
  4140. dockerFile := `FROM busybox
  4141. VOLUME ` + volName + `
  4142. RUN ls /foo/oops
  4143. `
  4144. buildImage("test", build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  4145. ExitCode: 1,
  4146. })
  4147. }
  4148. func (s *DockerCLIBuildSuite) TestBuildTagEvent(c *testing.T) {
  4149. since := daemonUnixTime(c)
  4150. dockerFile := `FROM busybox
  4151. RUN echo events
  4152. `
  4153. buildImageSuccessfully(c, "test", build.WithDockerfile(dockerFile))
  4154. until := daemonUnixTime(c)
  4155. out := cli.DockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image").Stdout()
  4156. events := strings.Split(strings.TrimSpace(out), "\n")
  4157. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  4158. var foundTag bool
  4159. for _, a := range actions {
  4160. if a == "tag" {
  4161. foundTag = true
  4162. break
  4163. }
  4164. }
  4165. assert.Assert(c, foundTag, "No tag event found:\n%s", out)
  4166. }
  4167. // #15780
  4168. func (s *DockerCLIBuildSuite) TestBuildMultipleTags(c *testing.T) {
  4169. dockerfile := `
  4170. FROM busybox
  4171. MAINTAINER test-15780
  4172. `
  4173. buildImageSuccessfully(c, "tag1", cli.WithFlags("-t", "tag2:v2", "-t", "tag1:latest", "-t", "tag1"), build.WithDockerfile(dockerfile))
  4174. id1 := getIDByName(c, "tag1")
  4175. id2 := getIDByName(c, "tag2:v2")
  4176. assert.Equal(c, id1, id2)
  4177. }
  4178. // #17290
  4179. func (s *DockerCLIBuildSuite) TestBuildCacheBrokenSymlink(c *testing.T) {
  4180. const name = "testbuildbrokensymlink"
  4181. ctx := fakecontext.New(c, "",
  4182. fakecontext.WithDockerfile(`
  4183. FROM busybox
  4184. COPY . ./`),
  4185. fakecontext.WithFiles(map[string]string{
  4186. "foo": "bar",
  4187. }))
  4188. defer ctx.Close()
  4189. err := os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  4190. assert.NilError(c, err)
  4191. // warm up cache
  4192. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4193. // add new file to context, should invalidate cache
  4194. err = os.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0o644)
  4195. assert.NilError(c, err)
  4196. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4197. if strings.Contains(result.Combined(), "Using cache") {
  4198. c.Fatal("2nd build used cache on ADD, it shouldn't")
  4199. }
  4200. }
  4201. func (s *DockerCLIBuildSuite) TestBuildFollowSymlinkToFile(c *testing.T) {
  4202. const name = "testbuildbrokensymlink"
  4203. ctx := fakecontext.New(c, "",
  4204. fakecontext.WithDockerfile(`
  4205. FROM busybox
  4206. COPY asymlink target`),
  4207. fakecontext.WithFiles(map[string]string{
  4208. "foo": "bar",
  4209. }))
  4210. defer ctx.Close()
  4211. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4212. assert.NilError(c, err)
  4213. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4214. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4215. assert.Assert(c, is.Regexp("^bar$", out))
  4216. // change target file should invalidate cache
  4217. err = os.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0o644)
  4218. assert.NilError(c, err)
  4219. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4220. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4221. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4222. assert.Assert(c, is.Regexp("^baz$", out))
  4223. }
  4224. func (s *DockerCLIBuildSuite) TestBuildFollowSymlinkToDir(c *testing.T) {
  4225. const name = "testbuildbrokensymlink"
  4226. ctx := fakecontext.New(c, "",
  4227. fakecontext.WithDockerfile(`
  4228. FROM busybox
  4229. COPY asymlink /`),
  4230. fakecontext.WithFiles(map[string]string{
  4231. "foo/abc": "bar",
  4232. "foo/def": "baz",
  4233. }))
  4234. defer ctx.Close()
  4235. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4236. assert.NilError(c, err)
  4237. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4238. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4239. assert.Assert(c, is.Regexp("^barbaz$", out))
  4240. // change target file should invalidate cache
  4241. err = os.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0o644)
  4242. assert.NilError(c, err)
  4243. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4244. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4245. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4246. assert.Assert(c, is.Regexp("^barbax$", out))
  4247. }
  4248. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  4249. // not from the target file.
  4250. func (s *DockerCLIBuildSuite) TestBuildSymlinkBasename(c *testing.T) {
  4251. const name = "testbuildbrokensymlink"
  4252. ctx := fakecontext.New(c, "",
  4253. fakecontext.WithDockerfile(`
  4254. FROM busybox
  4255. COPY asymlink /`),
  4256. fakecontext.WithFiles(map[string]string{
  4257. "foo": "bar",
  4258. }))
  4259. defer ctx.Close()
  4260. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4261. assert.NilError(c, err)
  4262. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4263. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "asymlink").Combined()
  4264. assert.Assert(c, is.Regexp("^bar$", out))
  4265. }
  4266. // #17827
  4267. func (s *DockerCLIBuildSuite) TestBuildCacheRootSource(c *testing.T) {
  4268. const name = "testbuildrootsource"
  4269. ctx := fakecontext.New(c, "",
  4270. fakecontext.WithDockerfile(`
  4271. FROM busybox
  4272. COPY / /data`),
  4273. fakecontext.WithFiles(map[string]string{
  4274. "foo": "bar",
  4275. }))
  4276. defer ctx.Close()
  4277. // warm up cache
  4278. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4279. // change file, should invalidate cache
  4280. err := os.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0o644)
  4281. assert.NilError(c, err)
  4282. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4283. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4284. }
  4285. // #19375
  4286. // FIXME(vdemeester) should migrate to docker/cli tests
  4287. func (s *DockerCLIBuildSuite) TestBuildFailsGitNotCallable(c *testing.T) {
  4288. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4289. build.WithContextPath("github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4290. ExitCode: 1,
  4291. Err: "unable to prepare context: unable to find 'git': ",
  4292. })
  4293. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4294. build.WithContextPath("https://github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4295. ExitCode: 1,
  4296. Err: "unable to prepare context: unable to find 'git': ",
  4297. })
  4298. }
  4299. // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir
  4300. func (s *DockerCLIBuildSuite) TestBuildWorkdirWindowsPath(c *testing.T) {
  4301. testRequires(c, DaemonIsWindows)
  4302. const name = "testbuildworkdirwindowspath"
  4303. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4304. FROM `+testEnv.PlatformDefaults.BaseImage+`
  4305. RUN mkdir C:\\work
  4306. WORKDIR C:\\work
  4307. RUN if "%CD%" NEQ "C:\work" exit -1
  4308. `))
  4309. }
  4310. func (s *DockerCLIBuildSuite) TestBuildLabel(c *testing.T) {
  4311. const name = "testbuildlabel"
  4312. testLabel := "foo"
  4313. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4314. build.WithDockerfile(`
  4315. FROM `+minimalBaseImage()+`
  4316. LABEL default foo
  4317. `))
  4318. var labels map[string]string
  4319. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4320. if _, ok := labels[testLabel]; !ok {
  4321. c.Fatal("label not found in image")
  4322. }
  4323. }
  4324. func (s *DockerCLIBuildSuite) TestBuildLabelOneNode(c *testing.T) {
  4325. const name = "testbuildlabel"
  4326. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=bar"),
  4327. build.WithDockerfile("FROM busybox"))
  4328. var labels map[string]string
  4329. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4330. v, ok := labels["foo"]
  4331. if !ok {
  4332. c.Fatal("label `foo` not found in image")
  4333. }
  4334. assert.Equal(c, v, "bar")
  4335. }
  4336. func (s *DockerCLIBuildSuite) TestBuildLabelCacheCommit(c *testing.T) {
  4337. const name = "testbuildlabelcachecommit"
  4338. testLabel := "foo"
  4339. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4340. FROM `+minimalBaseImage()+`
  4341. LABEL default foo
  4342. `))
  4343. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4344. build.WithDockerfile(`
  4345. FROM `+minimalBaseImage()+`
  4346. LABEL default foo
  4347. `))
  4348. var labels map[string]string
  4349. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4350. if _, ok := labels[testLabel]; !ok {
  4351. c.Fatal("label not found in image")
  4352. }
  4353. }
  4354. func (s *DockerCLIBuildSuite) TestBuildLabelMultiple(c *testing.T) {
  4355. const name = "testbuildlabelmultiple"
  4356. testLabels := map[string]string{
  4357. "foo": "bar",
  4358. "123": "456",
  4359. }
  4360. var labelArgs []string
  4361. for k, v := range testLabels {
  4362. labelArgs = append(labelArgs, "--label", k+"="+v)
  4363. }
  4364. buildImageSuccessfully(c, name, cli.WithFlags(labelArgs...),
  4365. build.WithDockerfile(`
  4366. FROM `+minimalBaseImage()+`
  4367. LABEL default foo
  4368. `))
  4369. var labels map[string]string
  4370. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4371. for k, v := range testLabels {
  4372. if x, ok := labels[k]; !ok || x != v {
  4373. c.Fatalf("label %s=%s not found in image", k, v)
  4374. }
  4375. }
  4376. }
  4377. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *testing.T) {
  4378. cli.DockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4379. baseImage := privateRegistryURL + "/baseimage"
  4380. buildImageSuccessfully(c, baseImage, build.WithDockerfile(`
  4381. FROM busybox
  4382. ENV env1 val1
  4383. `))
  4384. cli.DockerCmd(c, "push", baseImage)
  4385. cli.DockerCmd(c, "rmi", baseImage)
  4386. buildImageSuccessfully(c, baseImage, build.WithDockerfile(fmt.Sprintf(`
  4387. FROM %s
  4388. ENV env2 val2
  4389. `, baseImage)))
  4390. }
  4391. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *testing.T) {
  4392. workingDir, err := os.Getwd()
  4393. assert.NilError(c, err)
  4394. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  4395. assert.NilError(c, err)
  4396. osPath := os.Getenv("PATH")
  4397. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  4398. c.Setenv("PATH", testPath)
  4399. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  4400. tmp, err := os.MkdirTemp("", "integration-cli-")
  4401. assert.NilError(c, err)
  4402. externalAuthConfig := `{ "credsStore": "shell-test" }`
  4403. configPath := filepath.Join(tmp, "config.json")
  4404. err = os.WriteFile(configPath, []byte(externalAuthConfig), 0o644)
  4405. assert.NilError(c, err)
  4406. cli.DockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4407. b, err := os.ReadFile(configPath)
  4408. assert.NilError(c, err)
  4409. assert.Assert(c, !strings.Contains(string(b), "\"auth\":"))
  4410. cli.DockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  4411. cli.DockerCmd(c, "--config", tmp, "push", repoName)
  4412. // make sure the image is pulled when building
  4413. cli.DockerCmd(c, "rmi", repoName)
  4414. icmd.RunCmd(icmd.Cmd{
  4415. Command: []string{dockerBinary, "--config", tmp, "build", "-"},
  4416. Stdin: strings.NewReader(fmt.Sprintf("FROM %s", repoName)),
  4417. }).Assert(c, icmd.Success)
  4418. }
  4419. // Test cases in #22036
  4420. func (s *DockerCLIBuildSuite) TestBuildLabelsOverride(c *testing.T) {
  4421. // Command line option labels will always override
  4422. name := "scratchy"
  4423. expected := `{"bar":"from-flag","foo":"from-flag"}`
  4424. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4425. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4426. LABEL foo=from-dockerfile`))
  4427. res := inspectFieldJSON(c, name, "Config.Labels")
  4428. if res != expected {
  4429. c.Fatalf("Labels %s, expected %s", res, expected)
  4430. }
  4431. name = "from"
  4432. expected = `{"foo":"from-dockerfile"}`
  4433. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4434. LABEL foo from-dockerfile`))
  4435. res = inspectFieldJSON(c, name, "Config.Labels")
  4436. if res != expected {
  4437. c.Fatalf("Labels %s, expected %s", res, expected)
  4438. }
  4439. // Command line option label will override even via `FROM`
  4440. name = "new"
  4441. expected = `{"bar":"from-dockerfile2","foo":"new"}`
  4442. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=new"),
  4443. build.WithDockerfile(`FROM from
  4444. LABEL bar from-dockerfile2`))
  4445. res = inspectFieldJSON(c, name, "Config.Labels")
  4446. if res != expected {
  4447. c.Fatalf("Labels %s, expected %s", res, expected)
  4448. }
  4449. // Command line option without a value set (--label foo, --label bar=)
  4450. // will be treated as --label foo="", --label bar=""
  4451. name = "scratchy2"
  4452. expected = `{"bar":"","foo":""}`
  4453. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo", "--label", "bar="),
  4454. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4455. LABEL foo=from-dockerfile`))
  4456. res = inspectFieldJSON(c, name, "Config.Labels")
  4457. if res != expected {
  4458. c.Fatalf("Labels %s, expected %s", res, expected)
  4459. }
  4460. // Command line option without a value set (--label foo, --label bar=)
  4461. // will be treated as --label foo="", --label bar=""
  4462. // This time is for inherited images
  4463. name = "new2"
  4464. expected = `{"bar":"","foo":""}`
  4465. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=", "--label", "bar"),
  4466. build.WithDockerfile(`FROM from
  4467. LABEL bar from-dockerfile2`))
  4468. res = inspectFieldJSON(c, name, "Config.Labels")
  4469. if res != expected {
  4470. c.Fatalf("Labels %s, expected %s", res, expected)
  4471. }
  4472. // Command line option labels with only `FROM`
  4473. name = "scratchy"
  4474. expected = `{"bar":"from-flag","foo":"from-flag"}`
  4475. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4476. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4477. res = inspectFieldJSON(c, name, "Config.Labels")
  4478. if res != expected {
  4479. c.Fatalf("Labels %s, expected %s", res, expected)
  4480. }
  4481. // Command line option labels with env var
  4482. name = "scratchz"
  4483. expected = `{"bar":"$PATH"}`
  4484. buildImageSuccessfully(c, name, cli.WithFlags("--label", "bar=$PATH"),
  4485. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4486. res = inspectFieldJSON(c, name, "Config.Labels")
  4487. if res != expected {
  4488. c.Fatalf("Labels %s, expected %s", res, expected)
  4489. }
  4490. }
  4491. // Test case for #22855
  4492. func (s *DockerCLIBuildSuite) TestBuildDeleteCommittedFile(c *testing.T) {
  4493. const name = "test-delete-committed-file"
  4494. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4495. RUN echo test > file
  4496. RUN test -e file
  4497. RUN rm file
  4498. RUN sh -c "! test -e file"`))
  4499. }
  4500. // #20083
  4501. func (s *DockerCLIBuildSuite) TestBuildDockerignoreComment(c *testing.T) {
  4502. // TODO Windows: Figure out why this test is flakey on TP5. If you add
  4503. // something like RUN sleep 5, or even RUN ls /tmp after the ADD line,
  4504. // it is more reliable, but that's not a good fix.
  4505. testRequires(c, DaemonIsLinux)
  4506. const name = "testbuilddockerignorecleanpaths"
  4507. dockerfile := `
  4508. FROM busybox
  4509. ADD . /tmp/
  4510. RUN sh -c "(ls -la /tmp/#1)"
  4511. RUN sh -c "(! ls -la /tmp/#2)"
  4512. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (ls /tmp/dir1/foo)"`
  4513. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4514. build.WithFile("Dockerfile", dockerfile),
  4515. build.WithFile("foo", "foo"),
  4516. build.WithFile("foo2", "foo2"),
  4517. build.WithFile("dir1/foo", "foo in dir1"),
  4518. build.WithFile("#1", "# file 1"),
  4519. build.WithFile("#2", "# file 2"),
  4520. build.WithFile(".dockerignore", `# Visual C++ cache files
  4521. # because we have git ;-)
  4522. # The above comment is from #20083
  4523. foo
  4524. #dir1/foo
  4525. foo2
  4526. # The following is considered as comment as # is at the beginning
  4527. #1
  4528. # The following is not considered as comment as # is not at the beginning
  4529. #2
  4530. `)))
  4531. }
  4532. // Test case for #23221
  4533. func (s *DockerCLIBuildSuite) TestBuildWithUTF8BOM(c *testing.T) {
  4534. const name = "test-with-utf8-bom"
  4535. dockerfile := []byte(`FROM busybox`)
  4536. bomDockerfile := append([]byte{0xEF, 0xBB, 0xBF}, dockerfile...)
  4537. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4538. build.WithFile("Dockerfile", string(bomDockerfile)),
  4539. ))
  4540. }
  4541. // Test case for UTF-8 BOM in .dockerignore, related to #23221
  4542. func (s *DockerCLIBuildSuite) TestBuildWithUTF8BOMDockerignore(c *testing.T) {
  4543. const name = "test-with-utf8-bom-dockerignore"
  4544. dockerfile := `
  4545. FROM busybox
  4546. ADD . /tmp/
  4547. RUN ls -la /tmp
  4548. RUN sh -c "! ls /tmp/Dockerfile"
  4549. RUN ls /tmp/.dockerignore`
  4550. dockerignore := []byte("./Dockerfile\n")
  4551. bomDockerignore := append([]byte{0xEF, 0xBB, 0xBF}, dockerignore...)
  4552. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4553. build.WithFile("Dockerfile", dockerfile),
  4554. build.WithFile(".dockerignore", string(bomDockerignore)),
  4555. ))
  4556. }
  4557. // #22489 Shell test to confirm config gets updated correctly
  4558. func (s *DockerCLIBuildSuite) TestBuildShellUpdatesConfig(c *testing.T) {
  4559. skip.If(c, versions.GreaterThan(testEnv.DaemonAPIVersion(), "1.44"), "ContainerConfig is deprecated")
  4560. skip.If(c, testEnv.UsingSnapshotter, "ContainerConfig is not filled in c8d")
  4561. const name = "testbuildshellupdatesconfig"
  4562. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4563. SHELL ["foo", "-bar"]`))
  4564. expected := `["foo","-bar","#(nop) ","SHELL [foo -bar]"]`
  4565. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  4566. if res != expected {
  4567. c.Fatalf("%s, expected %s", res, expected)
  4568. }
  4569. res = inspectFieldJSON(c, name, "ContainerConfig.Shell")
  4570. if res != `["foo","-bar"]` {
  4571. c.Fatalf(`%s, expected ["foo","-bar"]`, res)
  4572. }
  4573. }
  4574. // #22489 Changing the shell multiple times and CMD after.
  4575. func (s *DockerCLIBuildSuite) TestBuildShellMultiple(c *testing.T) {
  4576. const name = "testbuildshellmultiple"
  4577. result := buildImage(name, build.WithDockerfile(`FROM busybox
  4578. RUN echo defaultshell
  4579. SHELL ["echo"]
  4580. RUN echoshell
  4581. SHELL ["ls"]
  4582. RUN -l
  4583. CMD -l`))
  4584. result.Assert(c, icmd.Success)
  4585. // Must contain 'defaultshell' twice
  4586. if len(strings.Split(result.Combined(), "defaultshell")) != 3 {
  4587. c.Fatalf("defaultshell should have appeared twice in %s", result.Combined())
  4588. }
  4589. // Must contain 'echoshell' twice
  4590. if len(strings.Split(result.Combined(), "echoshell")) != 3 {
  4591. c.Fatalf("echoshell should have appeared twice in %s", result.Combined())
  4592. }
  4593. // Must contain "total " (part of ls -l)
  4594. if !strings.Contains(result.Combined(), "total ") {
  4595. c.Fatalf("%s should have contained 'total '", result.Combined())
  4596. }
  4597. // A container started from the image uses the shell-form CMD.
  4598. // Last shell is ls. CMD is -l. So should contain 'total '.
  4599. outrun := cli.DockerCmd(c, "run", "--rm", name).Combined()
  4600. if !strings.Contains(outrun, "total ") {
  4601. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4602. }
  4603. }
  4604. // #22489. Changed SHELL with ENTRYPOINT
  4605. func (s *DockerCLIBuildSuite) TestBuildShellEntrypoint(c *testing.T) {
  4606. const name = "testbuildshellentrypoint"
  4607. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4608. SHELL ["ls"]
  4609. ENTRYPOINT -l`))
  4610. // A container started from the image uses the shell-form ENTRYPOINT.
  4611. // Shell is ls. ENTRYPOINT is -l. So should contain 'total '.
  4612. outrun := cli.DockerCmd(c, "run", "--rm", name).Combined()
  4613. if !strings.Contains(outrun, "total ") {
  4614. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4615. }
  4616. }
  4617. // #22489 Shell test to confirm shell is inherited in a subsequent build
  4618. func (s *DockerCLIBuildSuite) TestBuildShellInherited(c *testing.T) {
  4619. const name1 = "testbuildshellinherited1"
  4620. buildImageSuccessfully(c, name1, build.WithDockerfile(`FROM busybox
  4621. SHELL ["ls"]`))
  4622. const name2 = "testbuildshellinherited2"
  4623. buildImage(name2, build.WithDockerfile(`FROM `+name1+`
  4624. RUN -l`)).Assert(c, icmd.Expected{
  4625. // ls -l has "total " followed by some number in it, ls without -l does not.
  4626. Out: "total ",
  4627. })
  4628. }
  4629. // #22489 Shell test to confirm non-JSON doesn't work
  4630. func (s *DockerCLIBuildSuite) TestBuildShellNotJSON(c *testing.T) {
  4631. const name = "testbuildshellnotjson"
  4632. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4633. sHeLl exec -form`, // Casing explicit to ensure error is upper-cased.
  4634. )).Assert(c, icmd.Expected{
  4635. ExitCode: 1,
  4636. Err: "SHELL requires the arguments to be in JSON form",
  4637. })
  4638. }
  4639. // #22489 Windows shell test to confirm native is powershell if executing a PS command
  4640. // This would error if the default shell were still cmd.
  4641. func (s *DockerCLIBuildSuite) TestBuildShellWindowsPowershell(c *testing.T) {
  4642. testRequires(c, DaemonIsWindows)
  4643. const name = "testbuildshellpowershell"
  4644. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4645. SHELL ["powershell", "-command"]
  4646. RUN Write-Host John`)).Assert(c, icmd.Expected{
  4647. Out: "\nJohn\n",
  4648. })
  4649. }
  4650. // Verify that escape is being correctly applied to words when escape directive is not \.
  4651. // Tests WORKDIR, ADD
  4652. func (s *DockerCLIBuildSuite) TestBuildEscapeNotBackslashWordTest(c *testing.T) {
  4653. testRequires(c, DaemonIsWindows)
  4654. const name1 = "testbuildescapenotbackslashwordtesta"
  4655. buildImage(name1, build.WithDockerfile(`# escape= `+"`"+`
  4656. FROM `+minimalBaseImage()+`
  4657. WORKDIR c:\windows
  4658. RUN dir /w`)).Assert(c, icmd.Expected{
  4659. Out: "[System32]",
  4660. })
  4661. const name2 = "testbuildescapenotbackslashwordtestb"
  4662. buildImage(name2, build.WithDockerfile(`# escape= `+"`"+`
  4663. FROM `+minimalBaseImage()+`
  4664. SHELL ["powershell.exe"]
  4665. WORKDIR c:\foo
  4666. ADD Dockerfile c:\foo\
  4667. RUN dir Dockerfile`)).Assert(c, icmd.Expected{
  4668. Out: "-a----",
  4669. })
  4670. }
  4671. // #22868. Make sure shell-form CMD is not marked as escaped in the config of the image,
  4672. // but an exec-form CMD is marked.
  4673. func (s *DockerCLIBuildSuite) TestBuildCmdShellArgsEscaped(c *testing.T) {
  4674. testRequires(c, DaemonIsWindows)
  4675. const name1 = "testbuildcmdshellescapedshellform"
  4676. buildImageSuccessfully(c, name1, build.WithDockerfile(`
  4677. FROM `+minimalBaseImage()+`
  4678. CMD "ipconfig"
  4679. `))
  4680. res := inspectFieldJSON(c, name1, "Config.ArgsEscaped")
  4681. if res != "true" {
  4682. c.Fatalf("CMD did not update Config.ArgsEscaped on image: %v", res)
  4683. }
  4684. cli.DockerCmd(c, "run", "--name", "inspectme1", name1)
  4685. cli.DockerCmd(c, "wait", "inspectme1")
  4686. res = inspectFieldJSON(c, name1, "Config.Cmd")
  4687. if res != `["cmd /S /C \"ipconfig\""]` {
  4688. c.Fatalf("CMD incorrect in Config.Cmd: got %v", res)
  4689. }
  4690. // Now in JSON/exec-form
  4691. const name2 = "testbuildcmdshellescapedexecform"
  4692. buildImageSuccessfully(c, name2, build.WithDockerfile(`
  4693. FROM `+minimalBaseImage()+`
  4694. CMD ["ipconfig"]
  4695. `))
  4696. res = inspectFieldJSON(c, name2, "Config.ArgsEscaped")
  4697. if res != "false" {
  4698. c.Fatalf("CMD set Config.ArgsEscaped on image: %v", res)
  4699. }
  4700. cli.DockerCmd(c, "run", "--name", "inspectme2", name2)
  4701. cli.DockerCmd(c, "wait", "inspectme2")
  4702. res = inspectFieldJSON(c, name2, "Config.Cmd")
  4703. if res != `["ipconfig"]` {
  4704. c.Fatalf("CMD incorrect in Config.Cmd: got %v", res)
  4705. }
  4706. }
  4707. // Test case for #24912.
  4708. func (s *DockerCLIBuildSuite) TestBuildStepsWithProgress(c *testing.T) {
  4709. const name = "testbuildstepswithprogress"
  4710. totalRun := 5
  4711. result := buildImage(name, build.WithDockerfile("FROM busybox\n"+strings.Repeat("RUN echo foo\n", totalRun)))
  4712. result.Assert(c, icmd.Success)
  4713. assert.Assert(c, strings.Contains(result.Combined(), fmt.Sprintf("Step 1/%d : FROM busybox", 1+totalRun)))
  4714. for i := 2; i <= 1+totalRun; i++ {
  4715. assert.Assert(c, strings.Contains(result.Combined(), fmt.Sprintf("Step %d/%d : RUN echo foo", i, 1+totalRun)))
  4716. }
  4717. }
  4718. func (s *DockerCLIBuildSuite) TestBuildWithFailure(c *testing.T) {
  4719. const name = "testbuildwithfailure"
  4720. // First test case can only detect `nobody` in runtime so all steps will show up
  4721. dockerfile := "FROM busybox\nRUN nobody"
  4722. result := buildImage(name, build.WithDockerfile(dockerfile))
  4723. assert.Assert(c, result.Error != nil)
  4724. assert.Assert(c, strings.Contains(result.Stdout(), "Step 1/2 : FROM busybox"))
  4725. assert.Assert(c, strings.Contains(result.Stdout(), "Step 2/2 : RUN nobody"))
  4726. // Second test case `FFOM` should have been detected before build runs so no steps
  4727. dockerfile = "FFOM nobody\nRUN nobody"
  4728. result = buildImage(name, build.WithDockerfile(dockerfile))
  4729. assert.Assert(c, result.Error != nil)
  4730. assert.Assert(c, !strings.Contains(result.Stdout(), "Step 1/2 : FROM busybox"))
  4731. assert.Assert(c, !strings.Contains(result.Stdout(), "Step 2/2 : RUN nobody"))
  4732. }
  4733. func (s *DockerCLIBuildSuite) TestBuildCacheFromEqualDiffIDsLength(c *testing.T) {
  4734. dockerfile := `
  4735. FROM busybox
  4736. RUN echo "test"
  4737. ENTRYPOINT ["sh"]`
  4738. ctx := fakecontext.New(c, "",
  4739. fakecontext.WithDockerfile(dockerfile),
  4740. fakecontext.WithFiles(map[string]string{
  4741. "Dockerfile": dockerfile,
  4742. }))
  4743. defer ctx.Close()
  4744. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4745. id1 := getIDByName(c, "build1")
  4746. // rebuild with cache-from
  4747. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4748. id2 := getIDByName(c, "build2")
  4749. assert.Equal(c, id1, id2)
  4750. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4751. }
  4752. func (s *DockerCLIBuildSuite) TestBuildCacheFrom(c *testing.T) {
  4753. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4754. dockerfile := `
  4755. FROM busybox
  4756. ENV FOO=bar
  4757. ADD baz /
  4758. RUN touch bax`
  4759. ctx := fakecontext.New(c, "",
  4760. fakecontext.WithDockerfile(dockerfile),
  4761. fakecontext.WithFiles(map[string]string{
  4762. "Dockerfile": dockerfile,
  4763. "baz": "baz",
  4764. }))
  4765. defer ctx.Close()
  4766. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4767. id1 := getIDByName(c, "build1")
  4768. // rebuild with cache-from
  4769. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4770. id2 := getIDByName(c, "build2")
  4771. assert.Equal(c, id1, id2)
  4772. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4773. cli.DockerCmd(c, "rmi", "build2")
  4774. // no cache match with unknown source
  4775. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=nosuchtag"), build.WithExternalBuildContext(ctx))
  4776. id2 = getIDByName(c, "build2")
  4777. assert.Assert(c, id1 != id2)
  4778. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 0)
  4779. cli.DockerCmd(c, "rmi", "build2")
  4780. // Modify file, everything up to last command and layers are reused
  4781. dockerfile = `
  4782. FROM busybox
  4783. ENV FOO=bar
  4784. ADD baz /
  4785. RUN touch newfile`
  4786. err := os.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(dockerfile), 0o644)
  4787. assert.NilError(c, err)
  4788. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4789. id2 = getIDByName(c, "build2")
  4790. assert.Assert(c, id1 != id2)
  4791. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4792. layers1Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build1").Combined()
  4793. layers2Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build2").Combined()
  4794. var layers1 []string
  4795. var layers2 []string
  4796. assert.Assert(c, json.Unmarshal([]byte(layers1Str), &layers1) == nil)
  4797. assert.Assert(c, json.Unmarshal([]byte(layers2Str), &layers2) == nil)
  4798. assert.Equal(c, len(layers1), len(layers2))
  4799. for i := 0; i < len(layers1)-1; i++ {
  4800. assert.Equal(c, layers1[i], layers2[i])
  4801. }
  4802. assert.Assert(c, layers1[len(layers1)-1] != layers2[len(layers1)-1])
  4803. }
  4804. func (s *DockerCLIBuildSuite) TestBuildCacheFromLoad(c *testing.T) {
  4805. skip.If(c, testEnv.UsingSnapshotter, "Parent-child relations are lost when save/load-ing with the containerd image store")
  4806. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4807. dockerfile := `
  4808. FROM busybox
  4809. ENV FOO=bar
  4810. ADD baz /
  4811. RUN touch bax`
  4812. ctx := fakecontext.New(c, "",
  4813. fakecontext.WithDockerfile(dockerfile),
  4814. fakecontext.WithFiles(map[string]string{
  4815. "Dockerfile": dockerfile,
  4816. "baz": "baz",
  4817. }))
  4818. defer ctx.Close()
  4819. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4820. id1 := getIDByName(c, "build1")
  4821. // clear parent images
  4822. tempDir, err := os.MkdirTemp("", "test-build-cache-from-")
  4823. if err != nil {
  4824. c.Fatalf("failed to create temporary directory: %s", tempDir)
  4825. }
  4826. defer os.RemoveAll(tempDir)
  4827. tempFile := filepath.Join(tempDir, "img.tar")
  4828. cli.DockerCmd(c, "save", "-o", tempFile, "build1")
  4829. cli.DockerCmd(c, "rmi", "build1")
  4830. cli.DockerCmd(c, "load", "-i", tempFile)
  4831. parentID := cli.DockerCmd(c, "inspect", "-f", "{{.Parent}}", "build1").Combined()
  4832. assert.Equal(c, strings.TrimSpace(parentID), "")
  4833. // cache still applies without parents
  4834. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4835. id2 := getIDByName(c, "build2")
  4836. assert.Equal(c, id1, id2)
  4837. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4838. history1 := cli.DockerCmd(c, "history", "-q", "build2").Combined()
  4839. // Retry, no new intermediate images
  4840. result = cli.BuildCmd(c, "build3", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4841. id3 := getIDByName(c, "build3")
  4842. assert.Equal(c, id1, id3)
  4843. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4844. history2 := cli.DockerCmd(c, "history", "-q", "build3").Combined()
  4845. assert.Equal(c, history1, history2)
  4846. cli.DockerCmd(c, "rmi", "build2")
  4847. cli.DockerCmd(c, "rmi", "build3")
  4848. cli.DockerCmd(c, "rmi", "build1")
  4849. cli.DockerCmd(c, "load", "-i", tempFile)
  4850. }
  4851. func (s *DockerCLIBuildSuite) TestBuildMultiStageCache(c *testing.T) {
  4852. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4853. dockerfile := `
  4854. FROM busybox
  4855. ADD baz /
  4856. FROM busybox
  4857. ADD baz /`
  4858. ctx := fakecontext.New(c, "",
  4859. fakecontext.WithDockerfile(dockerfile),
  4860. fakecontext.WithFiles(map[string]string{
  4861. "Dockerfile": dockerfile,
  4862. "baz": "baz",
  4863. }))
  4864. defer ctx.Close()
  4865. result := cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4866. // second part of dockerfile was a repeat of first so should be cached
  4867. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 1)
  4868. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4869. // now both parts of dockerfile should be cached
  4870. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4871. }
  4872. func (s *DockerCLIBuildSuite) TestBuildNetNone(c *testing.T) {
  4873. testRequires(c, DaemonIsLinux)
  4874. const name = "testbuildnetnone"
  4875. buildImage(name, cli.WithFlags("--network=none"), build.WithDockerfile(`
  4876. FROM busybox
  4877. RUN ping -c 1 8.8.8.8
  4878. `)).Assert(c, icmd.Expected{
  4879. ExitCode: 1,
  4880. Out: "unreachable",
  4881. })
  4882. }
  4883. func (s *DockerCLIBuildSuite) TestBuildNetContainer(c *testing.T) {
  4884. testRequires(c, DaemonIsLinux)
  4885. id := cli.DockerCmd(c, "run", "--hostname", "foobar", "-d", "busybox", "nc", "-ll", "-p", "1234", "-e", "hostname").Stdout()
  4886. const name = "testbuildnetcontainer"
  4887. buildImageSuccessfully(c, name, cli.WithFlags("--network=container:"+strings.TrimSpace(id)),
  4888. build.WithDockerfile(`
  4889. FROM busybox
  4890. RUN nc localhost 1234 > /otherhost
  4891. `))
  4892. host := cli.DockerCmd(c, "run", "testbuildnetcontainer", "cat", "/otherhost").Combined()
  4893. assert.Equal(c, strings.TrimSpace(host), "foobar")
  4894. }
  4895. func (s *DockerCLIBuildSuite) TestBuildWithExtraHost(c *testing.T) {
  4896. testRequires(c, DaemonIsLinux)
  4897. const name = "testbuildwithextrahost"
  4898. buildImageSuccessfully(c, name,
  4899. cli.WithFlags(
  4900. "--add-host", "foo:127.0.0.1",
  4901. "--add-host", "bar:127.0.0.1",
  4902. ),
  4903. build.WithDockerfile(`
  4904. FROM busybox
  4905. RUN ping -c 1 foo
  4906. RUN ping -c 1 bar
  4907. `))
  4908. }
  4909. func (s *DockerCLIBuildSuite) TestBuildWithExtraHostInvalidFormat(c *testing.T) {
  4910. testRequires(c, DaemonIsLinux)
  4911. dockerfile := `
  4912. FROM busybox
  4913. RUN ping -c 1 foo`
  4914. testCases := []struct {
  4915. testName string
  4916. dockerfile string
  4917. buildFlag string
  4918. }{
  4919. {"extra_host_missing_ip", dockerfile, "--add-host=foo"},
  4920. {"extra_host_missing_ip_with_delimiter", dockerfile, "--add-host=foo:"},
  4921. {"extra_host_missing_hostname", dockerfile, "--add-host=:127.0.0.1"},
  4922. {"extra_host_invalid_ipv4", dockerfile, "--add-host=foo:101.10.2"},
  4923. {"extra_host_invalid_ipv6", dockerfile, "--add-host=foo:2001::1::3F"},
  4924. }
  4925. for _, tc := range testCases {
  4926. result := buildImage(tc.testName, cli.WithFlags(tc.buildFlag), build.WithDockerfile(tc.dockerfile))
  4927. result.Assert(c, icmd.Expected{
  4928. ExitCode: 125,
  4929. })
  4930. }
  4931. }
  4932. func (s *DockerCLIBuildSuite) TestBuildMultiStageCopyFromSyntax(c *testing.T) {
  4933. dockerfile := `
  4934. FROM busybox AS first
  4935. COPY foo bar
  4936. FROM busybox
  4937. %s
  4938. COPY baz baz
  4939. RUN echo mno > baz/cc
  4940. FROM busybox
  4941. COPY bar /
  4942. COPY --from=1 baz sub/
  4943. COPY --from=0 bar baz
  4944. COPY --from=first bar bay`
  4945. ctx := fakecontext.New(c, "",
  4946. fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, "")),
  4947. fakecontext.WithFiles(map[string]string{
  4948. "foo": "abc",
  4949. "bar": "def",
  4950. "baz/aa": "ghi",
  4951. "baz/bb": "jkl",
  4952. }))
  4953. defer ctx.Close()
  4954. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4955. cli.DockerCmd(c, "run", "build1", "cat", "bar").Assert(c, icmd.Expected{Out: "def"})
  4956. cli.DockerCmd(c, "run", "build1", "cat", "sub/aa").Assert(c, icmd.Expected{Out: "ghi"})
  4957. cli.DockerCmd(c, "run", "build1", "cat", "sub/cc").Assert(c, icmd.Expected{Out: "mno"})
  4958. cli.DockerCmd(c, "run", "build1", "cat", "baz").Assert(c, icmd.Expected{Out: "abc"})
  4959. cli.DockerCmd(c, "run", "build1", "cat", "bay").Assert(c, icmd.Expected{Out: "abc"})
  4960. result := cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  4961. // all commands should be cached
  4962. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 7)
  4963. assert.Equal(c, getIDByName(c, "build1"), getIDByName(c, "build2"))
  4964. err := os.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(fmt.Sprintf(dockerfile, "COPY baz/aa foo")), 0o644)
  4965. assert.NilError(c, err)
  4966. // changing file in parent block should not affect last block
  4967. result = cli.BuildCmd(c, "build3", build.WithExternalBuildContext(ctx))
  4968. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 5)
  4969. err = os.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("pqr"), 0o644)
  4970. assert.NilError(c, err)
  4971. // changing file in parent block should affect both first and last block
  4972. result = cli.BuildCmd(c, "build4", build.WithExternalBuildContext(ctx))
  4973. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 5)
  4974. cli.DockerCmd(c, "run", "build4", "cat", "bay").Assert(c, icmd.Expected{Out: "pqr"})
  4975. cli.DockerCmd(c, "run", "build4", "cat", "baz").Assert(c, icmd.Expected{Out: "pqr"})
  4976. }
  4977. func (s *DockerCLIBuildSuite) TestBuildMultiStageCopyFromErrors(c *testing.T) {
  4978. testCases := []struct {
  4979. dockerfile string
  4980. expectedError string
  4981. }{
  4982. {
  4983. dockerfile: `
  4984. FROM busybox
  4985. COPY --from=foo foo bar`,
  4986. expectedError: "invalid from flag value foo",
  4987. },
  4988. {
  4989. dockerfile: `
  4990. FROM busybox
  4991. COPY --from=0 foo bar`,
  4992. expectedError: "invalid from flag value 0: refers to current build stage",
  4993. },
  4994. {
  4995. dockerfile: `
  4996. FROM busybox AS foo
  4997. COPY --from=bar foo bar`,
  4998. expectedError: "invalid from flag value bar",
  4999. },
  5000. {
  5001. dockerfile: `
  5002. FROM busybox AS 1
  5003. COPY --from=1 foo bar`,
  5004. expectedError: "invalid name for build stage",
  5005. },
  5006. }
  5007. for _, tc := range testCases {
  5008. ctx := fakecontext.New(c, "",
  5009. fakecontext.WithDockerfile(tc.dockerfile),
  5010. fakecontext.WithFiles(map[string]string{
  5011. "foo": "abc",
  5012. }))
  5013. cli.Docker(cli.Args("build", "-t", "build1"), build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  5014. ExitCode: 1,
  5015. Err: tc.expectedError,
  5016. })
  5017. ctx.Close()
  5018. }
  5019. }
  5020. func (s *DockerCLIBuildSuite) TestBuildMultiStageMultipleBuilds(c *testing.T) {
  5021. dockerfile := `
  5022. FROM busybox
  5023. COPY foo bar`
  5024. ctx := fakecontext.New(c, "",
  5025. fakecontext.WithDockerfile(dockerfile),
  5026. fakecontext.WithFiles(map[string]string{
  5027. "foo": "abc",
  5028. }))
  5029. defer ctx.Close()
  5030. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5031. dockerfile = `
  5032. FROM build1:latest AS foo
  5033. FROM busybox
  5034. COPY --from=foo bar /
  5035. COPY foo /`
  5036. ctx = fakecontext.New(c, "",
  5037. fakecontext.WithDockerfile(dockerfile),
  5038. fakecontext.WithFiles(map[string]string{
  5039. "foo": "def",
  5040. }))
  5041. defer ctx.Close()
  5042. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5043. out := cli.DockerCmd(c, "run", "build2", "cat", "bar").Combined()
  5044. assert.Equal(c, strings.TrimSpace(out), "abc")
  5045. out = cli.DockerCmd(c, "run", "build2", "cat", "foo").Combined()
  5046. assert.Equal(c, strings.TrimSpace(out), "def")
  5047. }
  5048. func (s *DockerCLIBuildSuite) TestBuildMultiStageImplicitFrom(c *testing.T) {
  5049. dockerfile := `
  5050. FROM busybox
  5051. COPY --from=busybox /etc/passwd /mypasswd
  5052. RUN cmp /etc/passwd /mypasswd`
  5053. if DaemonIsWindows() {
  5054. dockerfile = `
  5055. FROM busybox
  5056. COPY --from=busybox License.txt foo`
  5057. }
  5058. ctx := fakecontext.New(c, "",
  5059. fakecontext.WithDockerfile(dockerfile),
  5060. )
  5061. defer ctx.Close()
  5062. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5063. if DaemonIsWindows() {
  5064. out := cli.DockerCmd(c, "run", "build1", "cat", "License.txt").Combined()
  5065. assert.Assert(c, len(out) > 10)
  5066. out2 := cli.DockerCmd(c, "run", "build1", "cat", "foo").Combined()
  5067. assert.Equal(c, out, out2)
  5068. }
  5069. }
  5070. func (s *DockerRegistrySuite) TestBuildMultiStageImplicitPull(c *testing.T) {
  5071. repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL)
  5072. dockerfile := `
  5073. FROM busybox
  5074. COPY foo bar`
  5075. ctx := fakecontext.New(c, "",
  5076. fakecontext.WithDockerfile(dockerfile),
  5077. fakecontext.WithFiles(map[string]string{
  5078. "foo": "abc",
  5079. }))
  5080. defer ctx.Close()
  5081. cli.BuildCmd(c, repoName, build.WithExternalBuildContext(ctx))
  5082. cli.DockerCmd(c, "push", repoName)
  5083. cli.DockerCmd(c, "rmi", repoName)
  5084. dockerfile = `
  5085. FROM busybox
  5086. COPY --from=%s bar baz`
  5087. ctx = fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, repoName)))
  5088. defer ctx.Close()
  5089. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5090. cli.Docker(cli.Args("run", "build1", "cat", "baz")).Assert(c, icmd.Expected{Out: "abc"})
  5091. }
  5092. func (s *DockerCLIBuildSuite) TestBuildMultiStageNameVariants(c *testing.T) {
  5093. dockerfile := `
  5094. FROM busybox as foo
  5095. COPY foo /
  5096. FROM foo as foo1
  5097. RUN echo 1 >> foo
  5098. FROM foo as foO2
  5099. RUN echo 2 >> foo
  5100. FROM foo
  5101. COPY --from=foo1 foo f1
  5102. COPY --from=FOo2 foo f2
  5103. ` // foo2 case also tests that names are case insensitive
  5104. ctx := fakecontext.New(c, "",
  5105. fakecontext.WithDockerfile(dockerfile),
  5106. fakecontext.WithFiles(map[string]string{
  5107. "foo": "bar",
  5108. }))
  5109. defer ctx.Close()
  5110. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5111. cli.Docker(cli.Args("run", "build1", "cat", "foo")).Assert(c, icmd.Expected{Out: "bar"})
  5112. cli.Docker(cli.Args("run", "build1", "cat", "f1")).Assert(c, icmd.Expected{Out: "bar1"})
  5113. cli.Docker(cli.Args("run", "build1", "cat", "f2")).Assert(c, icmd.Expected{Out: "bar2"})
  5114. }
  5115. func (s *DockerCLIBuildSuite) TestBuildMultiStageMultipleBuildsWindows(c *testing.T) {
  5116. testRequires(c, DaemonIsWindows)
  5117. dockerfile := `
  5118. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5119. COPY foo c:\\bar`
  5120. ctx := fakecontext.New(c, "",
  5121. fakecontext.WithDockerfile(dockerfile),
  5122. fakecontext.WithFiles(map[string]string{
  5123. "foo": "abc",
  5124. }))
  5125. defer ctx.Close()
  5126. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5127. dockerfile = `
  5128. FROM build1:latest
  5129. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5130. COPY --from=0 c:\\bar /
  5131. COPY foo /`
  5132. ctx = fakecontext.New(c, "",
  5133. fakecontext.WithDockerfile(dockerfile),
  5134. fakecontext.WithFiles(map[string]string{
  5135. "foo": "def",
  5136. }))
  5137. defer ctx.Close()
  5138. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5139. out := cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\bar").Combined()
  5140. assert.Equal(c, strings.TrimSpace(out), "abc")
  5141. out = cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\foo").Combined()
  5142. assert.Equal(c, strings.TrimSpace(out), "def")
  5143. }
  5144. func (s *DockerCLIBuildSuite) TestBuildCopyFromForbidWindowsSystemPaths(c *testing.T) {
  5145. testRequires(c, DaemonIsWindows)
  5146. dockerfile := `
  5147. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5148. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5149. COPY --from=0 %s c:\\oscopy
  5150. `
  5151. exp := icmd.Expected{
  5152. ExitCode: 1,
  5153. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5154. }
  5155. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\"))).Assert(c, exp)
  5156. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "C:\\\\"))).Assert(c, exp)
  5157. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\windows"))).Assert(c, exp)
  5158. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\wInDows"))).Assert(c, exp)
  5159. }
  5160. func (s *DockerCLIBuildSuite) TestBuildCopyFromForbidWindowsRelativePaths(c *testing.T) {
  5161. testRequires(c, DaemonIsWindows)
  5162. dockerfile := `
  5163. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5164. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5165. COPY --from=0 %s c:\\oscopy
  5166. `
  5167. exp := icmd.Expected{
  5168. ExitCode: 1,
  5169. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5170. }
  5171. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:"))).Assert(c, exp)
  5172. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "."))).Assert(c, exp)
  5173. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "..\\\\"))).Assert(c, exp)
  5174. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, ".\\\\windows"))).Assert(c, exp)
  5175. buildImage("testforbidsystempaths5", build.WithDockerfile(fmt.Sprintf(dockerfile, "\\\\windows"))).Assert(c, exp)
  5176. }
  5177. func (s *DockerCLIBuildSuite) TestBuildCopyFromWindowsIsCaseInsensitive(c *testing.T) {
  5178. testRequires(c, DaemonIsWindows)
  5179. dockerfile := `
  5180. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5181. COPY foo /
  5182. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5183. COPY --from=0 c:\\fOo c:\\copied
  5184. RUN type c:\\copied
  5185. `
  5186. cli.Docker(cli.Args("build", "-t", "copyfrom-windows-insensitive"), build.WithBuildContext(c,
  5187. build.WithFile("Dockerfile", dockerfile),
  5188. build.WithFile("foo", "hello world"),
  5189. )).Assert(c, icmd.Expected{
  5190. ExitCode: 0,
  5191. Out: "hello world",
  5192. })
  5193. }
  5194. // #33176
  5195. func (s *DockerCLIBuildSuite) TestBuildMultiStageResetScratch(c *testing.T) {
  5196. testRequires(c, DaemonIsLinux)
  5197. dockerfile := `
  5198. FROM busybox
  5199. WORKDIR /foo/bar
  5200. FROM scratch
  5201. ENV FOO=bar
  5202. `
  5203. ctx := fakecontext.New(c, "",
  5204. fakecontext.WithDockerfile(dockerfile),
  5205. )
  5206. defer ctx.Close()
  5207. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5208. res := cli.InspectCmd(c, "build1", cli.Format(".Config.WorkingDir")).Combined()
  5209. assert.Equal(c, strings.TrimSpace(res), "")
  5210. }
  5211. func (s *DockerCLIBuildSuite) TestBuildIntermediateTarget(c *testing.T) {
  5212. dockerfile := `
  5213. FROM busybox AS build-env
  5214. CMD ["/dev"]
  5215. FROM busybox
  5216. CMD ["/dist"]
  5217. `
  5218. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  5219. defer ctx.Close()
  5220. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5221. cli.WithFlags("--target", "build-env"))
  5222. res := cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5223. assert.Equal(c, strings.TrimSpace(res), `["/dev"]`)
  5224. // Stage name is case-insensitive by design
  5225. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5226. cli.WithFlags("--target", "BUIld-EnV"))
  5227. res = cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5228. assert.Equal(c, strings.TrimSpace(res), `["/dev"]`)
  5229. result := cli.Docker(cli.Args("build", "-t", "build1"), build.WithExternalBuildContext(ctx),
  5230. cli.WithFlags("--target", "nosuchtarget"))
  5231. result.Assert(c, icmd.Expected{
  5232. ExitCode: 1,
  5233. Err: "target stage \"nosuchtarget\" could not be found",
  5234. })
  5235. }
  5236. // TestBuildOpaqueDirectory tests that a build succeeds which
  5237. // creates opaque directories.
  5238. // See https://github.com/docker/docker/issues/25244
  5239. func (s *DockerCLIBuildSuite) TestBuildOpaqueDirectory(c *testing.T) {
  5240. testRequires(c, DaemonIsLinux)
  5241. dockerFile := `
  5242. FROM busybox
  5243. RUN mkdir /dir1 && touch /dir1/f1
  5244. RUN rm -rf /dir1 && mkdir /dir1 && touch /dir1/f2
  5245. RUN touch /dir1/f3
  5246. RUN [ -f /dir1/f2 ]
  5247. `
  5248. // Test that build succeeds, last command fails if opaque directory
  5249. // was not handled correctly
  5250. buildImageSuccessfully(c, "testopaquedirectory", build.WithDockerfile(dockerFile))
  5251. }
  5252. // Windows test for USER in dockerfile
  5253. func (s *DockerCLIBuildSuite) TestBuildWindowsUser(c *testing.T) {
  5254. testRequires(c, DaemonIsWindows)
  5255. const name = "testbuildwindowsuser"
  5256. buildImage(name, build.WithDockerfile(`FROM `+testEnv.PlatformDefaults.BaseImage+`
  5257. RUN net user user /add
  5258. USER user
  5259. RUN set username
  5260. `)).Assert(c, icmd.Expected{
  5261. Out: "USERNAME=user",
  5262. })
  5263. }
  5264. // Verifies if COPY file . when WORKDIR is set to a non-existing directory,
  5265. // the directory is created and the file is copied into the directory,
  5266. // as opposed to the file being copied as a file with the name of the
  5267. // directory. Fix for 27545 (found on Windows, but regression good for Linux too).
  5268. // Note 27545 was reverted in 28505, but a new fix was added subsequently in 28514.
  5269. func (s *DockerCLIBuildSuite) TestBuildCopyFileDotWithWorkdir(c *testing.T) {
  5270. const name = "testbuildcopyfiledotwithworkdir"
  5271. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  5272. build.WithFile("Dockerfile", `FROM busybox
  5273. WORKDIR /foo
  5274. COPY file .
  5275. RUN ["cat", "/foo/file"]
  5276. `),
  5277. build.WithFile("file", "content"),
  5278. ))
  5279. }
  5280. // Case-insensitive environment variables on Windows
  5281. func (s *DockerCLIBuildSuite) TestBuildWindowsEnvCaseInsensitive(c *testing.T) {
  5282. testRequires(c, DaemonIsWindows)
  5283. const name = "testbuildwindowsenvcaseinsensitive"
  5284. buildImageSuccessfully(c, name, build.WithDockerfile(`
  5285. FROM `+testEnv.PlatformDefaults.BaseImage+`
  5286. ENV FOO=bar foo=baz
  5287. `))
  5288. res := inspectFieldJSON(c, name, "Config.Env")
  5289. if res != `["foo=baz"]` { // Should not have FOO=bar in it - takes the last one processed. And only one entry as deduped.
  5290. c.Fatalf("Case insensitive environment variables on Windows failed. Got %s", res)
  5291. }
  5292. }
  5293. // Test case for 29667
  5294. func (s *DockerCLIBuildSuite) TestBuildWorkdirImageCmd(c *testing.T) {
  5295. image := "testworkdirimagecmd"
  5296. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5297. FROM busybox
  5298. WORKDIR /foo/bar
  5299. `))
  5300. out := cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image).Stdout()
  5301. assert.Equal(c, strings.TrimSpace(out), `["sh"]`)
  5302. image = "testworkdirlabelimagecmd"
  5303. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5304. FROM busybox
  5305. WORKDIR /foo/bar
  5306. LABEL a=b
  5307. `))
  5308. out = cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image).Stdout()
  5309. assert.Equal(c, strings.TrimSpace(out), `["sh"]`)
  5310. }
  5311. // Test case for 28902/28909
  5312. func (s *DockerCLIBuildSuite) TestBuildWorkdirCmd(c *testing.T) {
  5313. testRequires(c, DaemonIsLinux)
  5314. const name = "testbuildworkdircmd"
  5315. dockerFile := `
  5316. FROM busybox
  5317. WORKDIR /
  5318. `
  5319. buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
  5320. result := buildImage(name, build.WithDockerfile(dockerFile))
  5321. result.Assert(c, icmd.Success)
  5322. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 1)
  5323. }
  5324. // FIXME(vdemeester) should be a unit test
  5325. func (s *DockerCLIBuildSuite) TestBuildLineErrorOnBuild(c *testing.T) {
  5326. const name = "test_build_line_error_onbuild"
  5327. buildImage(name, build.WithDockerfile(`FROM busybox
  5328. ONBUILD
  5329. `)).Assert(c, icmd.Expected{
  5330. ExitCode: 1,
  5331. Err: "parse error on line 2: ONBUILD requires at least one argument",
  5332. })
  5333. }
  5334. // FIXME(vdemeester) should be a unit test
  5335. func (s *DockerCLIBuildSuite) TestBuildLineErrorUnknownInstruction(c *testing.T) {
  5336. const name = "test_build_line_error_unknown_instruction"
  5337. cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(`FROM busybox
  5338. RUN echo hello world
  5339. NOINSTRUCTION echo ba
  5340. RUN echo hello
  5341. ERROR
  5342. `)).Assert(c, icmd.Expected{
  5343. ExitCode: 1,
  5344. Err: "parse error on line 3: unknown instruction: NOINSTRUCTION",
  5345. })
  5346. }
  5347. // FIXME(vdemeester) should be a unit test
  5348. func (s *DockerCLIBuildSuite) TestBuildLineErrorWithEmptyLines(c *testing.T) {
  5349. const name = "test_build_line_error_with_empty_lines"
  5350. cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(`
  5351. FROM busybox
  5352. RUN echo hello world
  5353. NOINSTRUCTION echo ba
  5354. CMD ["/bin/init"]
  5355. `)).Assert(c, icmd.Expected{
  5356. ExitCode: 1,
  5357. Err: "parse error on line 6: unknown instruction: NOINSTRUCTION",
  5358. })
  5359. }
  5360. // FIXME(vdemeester) should be a unit test
  5361. func (s *DockerCLIBuildSuite) TestBuildLineErrorWithComments(c *testing.T) {
  5362. const name = "test_build_line_error_with_comments"
  5363. cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(`FROM busybox
  5364. # This will print hello world
  5365. # and then ba
  5366. RUN echo hello world
  5367. NOINSTRUCTION echo ba
  5368. `)).Assert(c, icmd.Expected{
  5369. ExitCode: 1,
  5370. Err: "parse error on line 5: unknown instruction: NOINSTRUCTION",
  5371. })
  5372. }
  5373. // #31957
  5374. func (s *DockerCLIBuildSuite) TestBuildSetCommandWithDefinedShell(c *testing.T) {
  5375. buildImageSuccessfully(c, "build1", build.WithDockerfile(`
  5376. FROM busybox
  5377. SHELL ["/bin/sh", "-c"]
  5378. `))
  5379. buildImageSuccessfully(c, "build2", build.WithDockerfile(`
  5380. FROM build1
  5381. CMD echo foo
  5382. `))
  5383. out := cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", "build2").Stdout()
  5384. expected := `["/bin/sh","-c","echo foo"]`
  5385. if testEnv.DaemonInfo.OSType == "windows" {
  5386. expected = `["/bin/sh -c echo foo"]`
  5387. }
  5388. assert.Equal(c, strings.TrimSpace(out), expected)
  5389. }
  5390. // FIXME(vdemeester) should migrate to docker/cli tests
  5391. func (s *DockerCLIBuildSuite) TestBuildIidFile(c *testing.T) {
  5392. tmpDir, err := os.MkdirTemp("", "TestBuildIidFile")
  5393. if err != nil {
  5394. c.Fatal(err)
  5395. }
  5396. defer os.RemoveAll(tmpDir)
  5397. tmpIidFile := filepath.Join(tmpDir, "iid")
  5398. const name = "testbuildiidfile"
  5399. // Use a Dockerfile with multiple stages to ensure we get the last one
  5400. cli.BuildCmd(c, name,
  5401. build.WithDockerfile(`FROM `+minimalBaseImage()+` AS stage1
  5402. ENV FOO FOO
  5403. FROM `+minimalBaseImage()+`
  5404. ENV BAR BAZ`),
  5405. cli.WithFlags("--iidfile", tmpIidFile))
  5406. id, err := os.ReadFile(tmpIidFile)
  5407. assert.NilError(c, err)
  5408. d, err := digest.Parse(string(id))
  5409. assert.NilError(c, err)
  5410. assert.Equal(c, d.String(), getIDByName(c, name))
  5411. }
  5412. // FIXME(vdemeester) should migrate to docker/cli tests
  5413. func (s *DockerCLIBuildSuite) TestBuildIidFileCleanupOnFail(c *testing.T) {
  5414. tmpDir, err := os.MkdirTemp("", "TestBuildIidFileCleanupOnFail")
  5415. if err != nil {
  5416. c.Fatal(err)
  5417. }
  5418. defer os.RemoveAll(tmpDir)
  5419. tmpIidFile := filepath.Join(tmpDir, "iid")
  5420. err = os.WriteFile(tmpIidFile, []byte("Dummy"), 0o666)
  5421. assert.NilError(c, err)
  5422. cli.Docker(cli.Args("build", "-t", "testbuildiidfilecleanuponfail"),
  5423. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  5424. RUN /non/existing/command`),
  5425. cli.WithFlags("--iidfile", tmpIidFile)).Assert(c, icmd.Expected{
  5426. ExitCode: 1,
  5427. })
  5428. _, err = os.Stat(tmpIidFile)
  5429. assert.ErrorContains(c, err, "")
  5430. assert.Equal(c, os.IsNotExist(err), true)
  5431. }