docker_cli_build_test.go 199 KB

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