docker_cli_build_test.go 203 KB

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