docker_cli_build_test.go 203 KB

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