docker_cli_build_test.go 203 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400
  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. cli.BuildCmd(c, name1, build.WithDockerfile(`
  290. FROM busybox
  291. ONBUILD CMD ["hello world"]
  292. ONBUILD ENTRYPOINT ["echo"]
  293. ONBUILD RUN ["true"]`))
  294. cli.BuildCmd(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. func (s *DockerSuite) TestBuildAddMultipleLocalFileWithAndWithoutCache(c *check.C) {
  1551. name := "testbuildaddmultiplelocalfilewithcache"
  1552. baseName := name + "-base"
  1553. cli.BuildCmd(c, baseName, build.WithDockerfile(`
  1554. FROM busybox
  1555. ENTRYPOINT ["/bin/sh"]
  1556. `))
  1557. dockerfile := `
  1558. FROM testbuildaddmultiplelocalfilewithcache-base
  1559. MAINTAINER dockerio
  1560. ADD foo Dockerfile /usr/lib/bla/
  1561. RUN sh -c "[ $(cat /usr/lib/bla/foo) = "hello" ]"`
  1562. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1563. "foo": "hello",
  1564. }))
  1565. defer ctx.Close()
  1566. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1567. id1 := getIDByName(c, name)
  1568. result2 := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1569. id2 := getIDByName(c, name)
  1570. result3 := cli.BuildCmd(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1571. id3 := getIDByName(c, name)
  1572. if id1 != id2 {
  1573. c.Fatalf("The cache should have been used but hasn't: %s", result2.Stdout())
  1574. }
  1575. if id1 == id3 {
  1576. c.Fatalf("The cache should have been invalided but hasn't: %s", result3.Stdout())
  1577. }
  1578. }
  1579. func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) {
  1580. name := "testbuildcopydirbutnotfile"
  1581. name2 := "testbuildcopydirbutnotfile2"
  1582. dockerfile := `
  1583. FROM ` + minimalBaseImage() + `
  1584. COPY dir /tmp/`
  1585. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1586. "dir/foo": "hello",
  1587. }))
  1588. defer ctx.Close()
  1589. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1590. id1 := getIDByName(c, name)
  1591. // Check that adding file with similar name doesn't mess with cache
  1592. if err := ctx.Add("dir_file", "hello2"); err != nil {
  1593. c.Fatal(err)
  1594. }
  1595. cli.BuildCmd(c, name2, build.WithExternalBuildContext(ctx))
  1596. id2 := getIDByName(c, name2)
  1597. if id1 != id2 {
  1598. c.Fatal("The cache should have been used but wasn't")
  1599. }
  1600. }
  1601. func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *check.C) {
  1602. name := "testbuildaddcurrentdirwithcache"
  1603. name2 := name + "2"
  1604. name3 := name + "3"
  1605. name4 := name + "4"
  1606. dockerfile := `
  1607. FROM ` + minimalBaseImage() + `
  1608. MAINTAINER dockerio
  1609. ADD . /usr/lib/bla`
  1610. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1611. "foo": "hello",
  1612. }))
  1613. defer ctx.Close()
  1614. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1615. id1 := getIDByName(c, name)
  1616. // Check that adding file invalidate cache of "ADD ."
  1617. if err := ctx.Add("bar", "hello2"); err != nil {
  1618. c.Fatal(err)
  1619. }
  1620. buildImageSuccessfully(c, name2, build.WithExternalBuildContext(ctx))
  1621. id2 := getIDByName(c, name2)
  1622. if id1 == id2 {
  1623. c.Fatal("The cache should have been invalided but hasn't.")
  1624. }
  1625. // Check that changing file invalidate cache of "ADD ."
  1626. if err := ctx.Add("foo", "hello1"); err != nil {
  1627. c.Fatal(err)
  1628. }
  1629. buildImageSuccessfully(c, name3, build.WithExternalBuildContext(ctx))
  1630. id3 := getIDByName(c, name3)
  1631. if id2 == id3 {
  1632. c.Fatal("The cache should have been invalided but hasn't.")
  1633. }
  1634. // Check that changing file to same content with different mtime does not
  1635. // invalidate cache of "ADD ."
  1636. time.Sleep(1 * time.Second) // wait second because of mtime precision
  1637. if err := ctx.Add("foo", "hello1"); err != nil {
  1638. c.Fatal(err)
  1639. }
  1640. buildImageSuccessfully(c, name4, build.WithExternalBuildContext(ctx))
  1641. id4 := getIDByName(c, name4)
  1642. if id3 != id4 {
  1643. c.Fatal("The cache should have been used but hasn't.")
  1644. }
  1645. }
  1646. // FIXME(vdemeester) this really seems to test the same thing as before (TestBuildAddMultipleLocalFileWithAndWithoutCache)
  1647. func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
  1648. name := "testbuildaddcurrentdirwithoutcache"
  1649. dockerfile := `
  1650. FROM ` + minimalBaseImage() + `
  1651. MAINTAINER dockerio
  1652. ADD . /usr/lib/bla`
  1653. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1654. "foo": "hello",
  1655. }))
  1656. defer ctx.Close()
  1657. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1658. id1 := getIDByName(c, name)
  1659. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1660. id2 := getIDByName(c, name)
  1661. if id1 == id2 {
  1662. c.Fatal("The cache should have been invalided but hasn't.")
  1663. }
  1664. }
  1665. func (s *DockerSuite) TestBuildAddRemoteFileWithAndWithoutCache(c *check.C) {
  1666. name := "testbuildaddremotefilewithcache"
  1667. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  1668. "baz": "hello",
  1669. }))
  1670. defer server.Close()
  1671. dockerfile := fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1672. MAINTAINER dockerio
  1673. ADD %s/baz /usr/lib/baz/quux`, server.URL())
  1674. cli.BuildCmd(c, name, build.WithDockerfile(dockerfile))
  1675. id1 := getIDByName(c, name)
  1676. cli.BuildCmd(c, name, build.WithDockerfile(dockerfile))
  1677. id2 := getIDByName(c, name)
  1678. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  1679. id3 := getIDByName(c, name)
  1680. if id1 != id2 {
  1681. c.Fatal("The cache should have been used but hasn't.")
  1682. }
  1683. if id1 == id3 {
  1684. c.Fatal("The cache should have been invalided but hasn't.")
  1685. }
  1686. }
  1687. func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
  1688. name := "testbuildaddremotefilemtime"
  1689. name2 := name + "2"
  1690. name3 := name + "3"
  1691. files := map[string]string{"baz": "hello"}
  1692. server := fakestorage.New(c, "", fakecontext.WithFiles(files))
  1693. defer server.Close()
  1694. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1695. MAINTAINER dockerio
  1696. ADD %s/baz /usr/lib/baz/quux`, server.URL())))
  1697. defer ctx.Close()
  1698. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1699. id1 := getIDByName(c, name)
  1700. cli.BuildCmd(c, name2, build.WithExternalBuildContext(ctx))
  1701. id2 := getIDByName(c, name2)
  1702. if id1 != id2 {
  1703. c.Fatal("The cache should have been used but wasn't - #1")
  1704. }
  1705. // Now create a different server with same contents (causes different mtime)
  1706. // The cache should still be used
  1707. // allow some time for clock to pass as mtime precision is only 1s
  1708. time.Sleep(2 * time.Second)
  1709. server2 := fakestorage.New(c, "", fakecontext.WithFiles(files))
  1710. defer server2.Close()
  1711. ctx2 := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1712. MAINTAINER dockerio
  1713. ADD %s/baz /usr/lib/baz/quux`, server2.URL())))
  1714. defer ctx2.Close()
  1715. cli.BuildCmd(c, name3, build.WithExternalBuildContext(ctx2))
  1716. id3 := getIDByName(c, name3)
  1717. if id1 != id3 {
  1718. c.Fatal("The cache should have been used but wasn't")
  1719. }
  1720. }
  1721. // FIXME(vdemeester) this really seems to test the same thing as before (combined)
  1722. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithAndWithoutCache(c *check.C) {
  1723. name := "testbuildaddlocalandremotefilewithcache"
  1724. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  1725. "baz": "hello",
  1726. }))
  1727. defer server.Close()
  1728. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1729. MAINTAINER dockerio
  1730. ADD foo /usr/lib/bla/bar
  1731. ADD %s/baz /usr/lib/baz/quux`, server.URL())),
  1732. fakecontext.WithFiles(map[string]string{
  1733. "foo": "hello world",
  1734. }))
  1735. defer ctx.Close()
  1736. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1737. id1 := getIDByName(c, name)
  1738. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1739. id2 := getIDByName(c, name)
  1740. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1741. id3 := getIDByName(c, name)
  1742. if id1 != id2 {
  1743. c.Fatal("The cache should have been used but hasn't.")
  1744. }
  1745. if id1 == id3 {
  1746. c.Fatal("The cache should have been invalidated but hasn't.")
  1747. }
  1748. }
  1749. func testContextTar(c *check.C, compression archive.Compression) {
  1750. ctx := fakecontext.New(c, "",
  1751. fakecontext.WithDockerfile(`FROM busybox
  1752. ADD foo /foo
  1753. CMD ["cat", "/foo"]`),
  1754. fakecontext.WithFiles(map[string]string{
  1755. "foo": "bar",
  1756. }),
  1757. )
  1758. defer ctx.Close()
  1759. context, err := archive.Tar(ctx.Dir, compression)
  1760. if err != nil {
  1761. c.Fatalf("failed to build context tar: %v", err)
  1762. }
  1763. name := "contexttar"
  1764. cli.BuildCmd(c, name, build.WithStdinContext(context))
  1765. }
  1766. func (s *DockerSuite) TestBuildContextTarGzip(c *check.C) {
  1767. testContextTar(c, archive.Gzip)
  1768. }
  1769. func (s *DockerSuite) TestBuildContextTarNoCompression(c *check.C) {
  1770. testContextTar(c, archive.Uncompressed)
  1771. }
  1772. func (s *DockerSuite) TestBuildNoContext(c *check.C) {
  1773. name := "nocontext"
  1774. icmd.RunCmd(icmd.Cmd{
  1775. Command: []string{dockerBinary, "build", "-t", name, "-"},
  1776. Stdin: strings.NewReader(
  1777. `FROM busybox
  1778. CMD ["echo", "ok"]`),
  1779. }).Assert(c, icmd.Success)
  1780. if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
  1781. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  1782. }
  1783. }
  1784. func (s *DockerSuite) TestBuildDockerfileStdin(c *check.C) {
  1785. name := "stdindockerfile"
  1786. tmpDir, err := ioutil.TempDir("", "fake-context")
  1787. c.Assert(err, check.IsNil)
  1788. err = ioutil.WriteFile(filepath.Join(tmpDir, "foo"), []byte("bar"), 0600)
  1789. c.Assert(err, check.IsNil)
  1790. icmd.RunCmd(icmd.Cmd{
  1791. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir},
  1792. Stdin: strings.NewReader(
  1793. `FROM busybox
  1794. ADD foo /foo
  1795. CMD ["cat", "/foo"]`),
  1796. }).Assert(c, icmd.Success)
  1797. res := inspectField(c, name, "Config.Cmd")
  1798. c.Assert(strings.TrimSpace(string(res)), checker.Equals, `[cat /foo]`)
  1799. }
  1800. func (s *DockerSuite) TestBuildDockerfileStdinConflict(c *check.C) {
  1801. name := "stdindockerfiletarcontext"
  1802. icmd.RunCmd(icmd.Cmd{
  1803. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", "-"},
  1804. }).Assert(c, icmd.Expected{
  1805. ExitCode: 1,
  1806. Err: "use stdin for both build context and dockerfile",
  1807. })
  1808. }
  1809. func (s *DockerSuite) TestBuildDockerfileStdinNoExtraFiles(c *check.C) {
  1810. s.testBuildDockerfileStdinNoExtraFiles(c, false, false)
  1811. }
  1812. func (s *DockerSuite) TestBuildDockerfileStdinDockerignore(c *check.C) {
  1813. s.testBuildDockerfileStdinNoExtraFiles(c, true, false)
  1814. }
  1815. func (s *DockerSuite) TestBuildDockerfileStdinDockerignoreIgnored(c *check.C) {
  1816. s.testBuildDockerfileStdinNoExtraFiles(c, true, true)
  1817. }
  1818. func (s *DockerSuite) testBuildDockerfileStdinNoExtraFiles(c *check.C, hasDockerignore, ignoreDockerignore bool) {
  1819. name := "stdindockerfilenoextra"
  1820. tmpDir, err := ioutil.TempDir("", "fake-context")
  1821. c.Assert(err, check.IsNil)
  1822. defer os.RemoveAll(tmpDir)
  1823. writeFile := func(filename, content string) {
  1824. err = ioutil.WriteFile(filepath.Join(tmpDir, filename), []byte(content), 0600)
  1825. c.Assert(err, check.IsNil)
  1826. }
  1827. writeFile("foo", "bar")
  1828. if hasDockerignore {
  1829. // Add an empty Dockerfile to verify that it is not added to the image
  1830. writeFile("Dockerfile", "")
  1831. ignores := "Dockerfile\n"
  1832. if ignoreDockerignore {
  1833. ignores += ".dockerignore\n"
  1834. }
  1835. writeFile(".dockerignore", ignores)
  1836. }
  1837. result := icmd.RunCmd(icmd.Cmd{
  1838. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir},
  1839. Stdin: strings.NewReader(
  1840. `FROM busybox
  1841. COPY . /baz`),
  1842. })
  1843. result.Assert(c, icmd.Success)
  1844. result = cli.DockerCmd(c, "run", "--rm", name, "ls", "-A", "/baz")
  1845. if hasDockerignore && !ignoreDockerignore {
  1846. c.Assert(result.Stdout(), checker.Equals, ".dockerignore\nfoo\n")
  1847. } else {
  1848. c.Assert(result.Stdout(), checker.Equals, "foo\n")
  1849. }
  1850. }
  1851. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
  1852. testRequires(c, DaemonIsLinux)
  1853. name := "testbuildimg"
  1854. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox:latest
  1855. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  1856. VOLUME /test`))
  1857. out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  1858. if expected := "drw-------"; !strings.Contains(out, expected) {
  1859. c.Fatalf("expected %s received %s", expected, out)
  1860. }
  1861. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  1862. c.Fatalf("expected %s received %s", expected, out)
  1863. }
  1864. }
  1865. // testing #1405 - config.Cmd does not get cleaned up if
  1866. // utilizing cache
  1867. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
  1868. name := "testbuildcmdcleanup"
  1869. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1870. RUN echo "hello"`))
  1871. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1872. build.WithFile("Dockerfile", `FROM busybox
  1873. RUN echo "hello"
  1874. ADD foo /foo
  1875. ENTRYPOINT ["/bin/echo"]`),
  1876. build.WithFile("foo", "hello")))
  1877. res := inspectField(c, name, "Config.Cmd")
  1878. // Cmd must be cleaned up
  1879. if res != "[]" {
  1880. c.Fatalf("Cmd %s, expected nil", res)
  1881. }
  1882. }
  1883. func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) {
  1884. name := "testbuildaddnotfound"
  1885. expected := "foo: no such file or directory"
  1886. if testEnv.DaemonPlatform() == "windows" {
  1887. expected = "foo: The system cannot find the file specified"
  1888. }
  1889. buildImage(name, build.WithBuildContext(c,
  1890. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  1891. ADD foo /usr/local/bar`),
  1892. build.WithFile("bar", "hello"))).Assert(c, icmd.Expected{
  1893. ExitCode: 1,
  1894. Err: expected,
  1895. })
  1896. }
  1897. func (s *DockerSuite) TestBuildInheritance(c *check.C) {
  1898. testRequires(c, DaemonIsLinux)
  1899. name := "testbuildinheritance"
  1900. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1901. EXPOSE 2375`))
  1902. ports1 := inspectField(c, name, "Config.ExposedPorts")
  1903. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1904. ENTRYPOINT ["/bin/echo"]`, name)))
  1905. res := inspectField(c, name, "Config.Entrypoint")
  1906. if expected := "[/bin/echo]"; res != expected {
  1907. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1908. }
  1909. ports2 := inspectField(c, name, "Config.ExposedPorts")
  1910. if ports1 != ports2 {
  1911. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  1912. }
  1913. }
  1914. func (s *DockerSuite) TestBuildFails(c *check.C) {
  1915. name := "testbuildfails"
  1916. buildImage(name, build.WithDockerfile(`FROM busybox
  1917. RUN sh -c "exit 23"`)).Assert(c, icmd.Expected{
  1918. ExitCode: 23,
  1919. Err: "returned a non-zero code: 23",
  1920. })
  1921. }
  1922. func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
  1923. name := "testbuildonbuild"
  1924. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1925. ONBUILD RUN touch foobar`))
  1926. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1927. RUN [ -f foobar ]`, name)))
  1928. }
  1929. // gh #2446
  1930. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
  1931. makeLink := `ln -s /foo /bar`
  1932. if testEnv.DaemonPlatform() == "windows" {
  1933. makeLink = `mklink /D C:\bar C:\foo`
  1934. }
  1935. name := "testbuildaddtosymlinkdest"
  1936. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1937. build.WithFile("Dockerfile", `
  1938. FROM busybox
  1939. RUN sh -c "mkdir /foo"
  1940. RUN `+makeLink+`
  1941. ADD foo /bar/
  1942. RUN sh -c "[ -f /bar/foo ]"
  1943. RUN sh -c "[ -f /foo/foo ]"`),
  1944. build.WithFile("foo", "hello"),
  1945. ))
  1946. }
  1947. func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) {
  1948. name := "testbuildescapewhitespace"
  1949. buildImageSuccessfully(c, name, build.WithDockerfile(`
  1950. # ESCAPE=\
  1951. FROM busybox
  1952. MAINTAINER "Docker \
  1953. IO <io@\
  1954. docker.com>"
  1955. `))
  1956. res := inspectField(c, name, "Author")
  1957. if res != "\"Docker IO <io@docker.com>\"" {
  1958. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  1959. }
  1960. }
  1961. func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
  1962. // Verify that strings that look like ints are still passed as strings
  1963. name := "testbuildstringing"
  1964. buildImageSuccessfully(c, name, build.WithDockerfile(`
  1965. FROM busybox
  1966. MAINTAINER 123`))
  1967. out, _ := dockerCmd(c, "inspect", name)
  1968. if !strings.Contains(out, "\"123\"") {
  1969. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  1970. }
  1971. }
  1972. func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
  1973. name := "testbuilddockerignore"
  1974. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1975. build.WithFile("Dockerfile", `
  1976. FROM busybox
  1977. ADD . /bla
  1978. RUN sh -c "[[ -f /bla/src/x.go ]]"
  1979. RUN sh -c "[[ -f /bla/Makefile ]]"
  1980. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  1981. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  1982. RUN sh -c "[[ ! -e /bla/README.md ]]"
  1983. RUN sh -c "[[ ! -e /bla/dir/foo ]]"
  1984. RUN sh -c "[[ ! -e /bla/foo ]]"
  1985. RUN sh -c "[[ ! -e /bla/.git ]]"
  1986. RUN sh -c "[[ ! -e v.cc ]]"
  1987. RUN sh -c "[[ ! -e src/v.cc ]]"
  1988. RUN sh -c "[[ ! -e src/_vendor/v.cc ]]"`),
  1989. build.WithFile("Makefile", "all:"),
  1990. build.WithFile(".git/HEAD", "ref: foo"),
  1991. build.WithFile("src/x.go", "package main"),
  1992. build.WithFile("src/_vendor/v.go", "package main"),
  1993. build.WithFile("src/_vendor/v.cc", "package main"),
  1994. build.WithFile("src/v.cc", "package main"),
  1995. build.WithFile("v.cc", "package main"),
  1996. build.WithFile("dir/foo", ""),
  1997. build.WithFile(".gitignore", ""),
  1998. build.WithFile("README.md", "readme"),
  1999. build.WithFile(".dockerignore", `
  2000. .git
  2001. pkg
  2002. .gitignore
  2003. src/_vendor
  2004. *.md
  2005. **/*.cc
  2006. dir`),
  2007. ))
  2008. }
  2009. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
  2010. name := "testbuilddockerignorecleanpaths"
  2011. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2012. build.WithFile("Dockerfile", `
  2013. FROM busybox
  2014. ADD . /tmp/
  2015. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)"`),
  2016. build.WithFile("foo", "foo"),
  2017. build.WithFile("foo2", "foo2"),
  2018. build.WithFile("dir1/foo", "foo in dir1"),
  2019. build.WithFile(".dockerignore", "./foo\ndir1//foo\n./dir1/../foo2"),
  2020. ))
  2021. }
  2022. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) {
  2023. name := "testbuilddockerignoreexceptions"
  2024. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2025. build.WithFile("Dockerfile", `
  2026. FROM busybox
  2027. ADD . /bla
  2028. RUN sh -c "[[ -f /bla/src/x.go ]]"
  2029. RUN sh -c "[[ -f /bla/Makefile ]]"
  2030. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  2031. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  2032. RUN sh -c "[[ ! -e /bla/README.md ]]"
  2033. RUN sh -c "[[ -e /bla/dir/dir/foo ]]"
  2034. RUN sh -c "[[ ! -e /bla/dir/foo1 ]]"
  2035. RUN sh -c "[[ -f /bla/dir/e ]]"
  2036. RUN sh -c "[[ -f /bla/dir/e-dir/foo ]]"
  2037. RUN sh -c "[[ ! -e /bla/foo ]]"
  2038. RUN sh -c "[[ ! -e /bla/.git ]]"
  2039. RUN sh -c "[[ -e /bla/dir/a.cc ]]"`),
  2040. build.WithFile("Makefile", "all:"),
  2041. build.WithFile(".git/HEAD", "ref: foo"),
  2042. build.WithFile("src/x.go", "package main"),
  2043. build.WithFile("src/_vendor/v.go", "package main"),
  2044. build.WithFile("dir/foo", ""),
  2045. build.WithFile("dir/foo1", ""),
  2046. build.WithFile("dir/dir/f1", ""),
  2047. build.WithFile("dir/dir/foo", ""),
  2048. build.WithFile("dir/e", ""),
  2049. build.WithFile("dir/e-dir/foo", ""),
  2050. build.WithFile(".gitignore", ""),
  2051. build.WithFile("README.md", "readme"),
  2052. build.WithFile("dir/a.cc", "hello"),
  2053. build.WithFile(".dockerignore", `
  2054. .git
  2055. pkg
  2056. .gitignore
  2057. src/_vendor
  2058. *.md
  2059. dir
  2060. !dir/e*
  2061. !dir/dir/foo
  2062. **/*.cc
  2063. !**/*.cc`),
  2064. ))
  2065. }
  2066. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
  2067. name := "testbuilddockerignoredockerfile"
  2068. dockerfile := `
  2069. FROM busybox
  2070. ADD . /tmp/
  2071. RUN sh -c "! ls /tmp/Dockerfile"
  2072. RUN ls /tmp/.dockerignore`
  2073. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2074. build.WithFile("Dockerfile", dockerfile),
  2075. build.WithFile(".dockerignore", "Dockerfile\n"),
  2076. ))
  2077. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2078. build.WithFile("Dockerfile", dockerfile),
  2079. build.WithFile(".dockerignore", "./Dockerfile\n"),
  2080. ))
  2081. }
  2082. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
  2083. name := "testbuilddockerignoredockerfile"
  2084. dockerfile := `
  2085. FROM busybox
  2086. ADD . /tmp/
  2087. RUN ls /tmp/Dockerfile
  2088. RUN sh -c "! ls /tmp/MyDockerfile"
  2089. RUN ls /tmp/.dockerignore`
  2090. buildImageSuccessfully(c, name, cli.WithFlags("-f", "MyDockerfile"), build.WithBuildContext(c,
  2091. build.WithFile("Dockerfile", "Should not use me"),
  2092. build.WithFile("MyDockerfile", dockerfile),
  2093. build.WithFile(".dockerignore", "MyDockerfile\n"),
  2094. ))
  2095. buildImageSuccessfully(c, name, cli.WithFlags("-f", "MyDockerfile"), build.WithBuildContext(c,
  2096. build.WithFile("Dockerfile", "Should not use me"),
  2097. build.WithFile("MyDockerfile", dockerfile),
  2098. build.WithFile(".dockerignore", "./MyDockerfile\n"),
  2099. ))
  2100. }
  2101. func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
  2102. name := "testbuilddockerignoredockerignore"
  2103. dockerfile := `
  2104. FROM busybox
  2105. ADD . /tmp/
  2106. RUN sh -c "! ls /tmp/.dockerignore"
  2107. RUN ls /tmp/Dockerfile`
  2108. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2109. build.WithFile("Dockerfile", dockerfile),
  2110. build.WithFile(".dockerignore", ".dockerignore\n"),
  2111. ))
  2112. }
  2113. func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
  2114. name := "testbuilddockerignoretouchdockerfile"
  2115. dockerfile := `
  2116. FROM busybox
  2117. ADD . /tmp/`
  2118. ctx := fakecontext.New(c, "",
  2119. fakecontext.WithDockerfile(dockerfile),
  2120. fakecontext.WithFiles(map[string]string{
  2121. ".dockerignore": "Dockerfile\n",
  2122. }))
  2123. defer ctx.Close()
  2124. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2125. id1 := getIDByName(c, name)
  2126. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2127. id2 := getIDByName(c, name)
  2128. if id1 != id2 {
  2129. c.Fatalf("Didn't use the cache - 1")
  2130. }
  2131. // Now make sure touching Dockerfile doesn't invalidate the cache
  2132. if err := ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2133. c.Fatalf("Didn't add Dockerfile: %s", err)
  2134. }
  2135. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2136. id2 = getIDByName(c, name)
  2137. if id1 != id2 {
  2138. c.Fatalf("Didn't use the cache - 2")
  2139. }
  2140. // One more time but just 'touch' it instead of changing the content
  2141. if err := ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2142. c.Fatalf("Didn't add Dockerfile: %s", err)
  2143. }
  2144. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2145. id2 = getIDByName(c, name)
  2146. if id1 != id2 {
  2147. c.Fatalf("Didn't use the cache - 3")
  2148. }
  2149. }
  2150. func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
  2151. name := "testbuilddockerignorewholedir"
  2152. dockerfile := `
  2153. FROM busybox
  2154. COPY . /
  2155. RUN sh -c "[[ ! -e /.gitignore ]]"
  2156. RUN sh -c "[[ ! -e /Makefile ]]"`
  2157. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2158. build.WithFile("Dockerfile", dockerfile),
  2159. build.WithFile(".dockerignore", "*\n"),
  2160. build.WithFile("Makefile", "all:"),
  2161. build.WithFile(".gitignore", ""),
  2162. ))
  2163. }
  2164. func (s *DockerSuite) TestBuildDockerignoringOnlyDotfiles(c *check.C) {
  2165. name := "testbuilddockerignorewholedir"
  2166. dockerfile := `
  2167. FROM busybox
  2168. COPY . /
  2169. RUN sh -c "[[ ! -e /.gitignore ]]"
  2170. RUN sh -c "[[ -f /Makefile ]]"`
  2171. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2172. build.WithFile("Dockerfile", dockerfile),
  2173. build.WithFile(".dockerignore", ".*"),
  2174. build.WithFile("Makefile", "all:"),
  2175. build.WithFile(".gitignore", ""),
  2176. ))
  2177. }
  2178. func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) {
  2179. name := "testbuilddockerignorebadexclusion"
  2180. buildImage(name, build.WithBuildContext(c,
  2181. build.WithFile("Dockerfile", `
  2182. FROM busybox
  2183. COPY . /
  2184. RUN sh -c "[[ ! -e /.gitignore ]]"
  2185. RUN sh -c "[[ -f /Makefile ]]"`),
  2186. build.WithFile("Makefile", "all:"),
  2187. build.WithFile(".gitignore", ""),
  2188. build.WithFile(".dockerignore", "!\n"),
  2189. )).Assert(c, icmd.Expected{
  2190. ExitCode: 1,
  2191. Err: "Error checking context: 'illegal exclusion pattern: \"!\"",
  2192. })
  2193. }
  2194. func (s *DockerSuite) TestBuildDockerignoringWildTopDir(c *check.C) {
  2195. dockerfile := `
  2196. FROM busybox
  2197. COPY . /
  2198. RUN sh -c "[[ ! -e /.dockerignore ]]"
  2199. RUN sh -c "[[ ! -e /Dockerfile ]]"
  2200. RUN sh -c "[[ ! -e /file1 ]]"
  2201. RUN sh -c "[[ ! -e /dir ]]"`
  2202. // All of these should result in ignoring all files
  2203. for _, variant := range []string{"**", "**/", "**/**", "*"} {
  2204. buildImageSuccessfully(c, "noname", build.WithBuildContext(c,
  2205. build.WithFile("Dockerfile", dockerfile),
  2206. build.WithFile("file1", ""),
  2207. build.WithFile("dir/file1", ""),
  2208. build.WithFile(".dockerignore", variant),
  2209. ))
  2210. dockerCmd(c, "rmi", "noname")
  2211. }
  2212. }
  2213. func (s *DockerSuite) TestBuildDockerignoringWildDirs(c *check.C) {
  2214. dockerfile := `
  2215. FROM busybox
  2216. COPY . /
  2217. #RUN sh -c "[[ -e /.dockerignore ]]"
  2218. RUN sh -c "[[ -e /Dockerfile ]] && \
  2219. [[ ! -e /file0 ]] && \
  2220. [[ ! -e /dir1/file0 ]] && \
  2221. [[ ! -e /dir2/file0 ]] && \
  2222. [[ ! -e /file1 ]] && \
  2223. [[ ! -e /dir1/file1 ]] && \
  2224. [[ ! -e /dir1/dir2/file1 ]] && \
  2225. [[ ! -e /dir1/file2 ]] && \
  2226. [[ -e /dir1/dir2/file2 ]] && \
  2227. [[ ! -e /dir1/dir2/file4 ]] && \
  2228. [[ ! -e /dir1/dir2/file5 ]] && \
  2229. [[ ! -e /dir1/dir2/file6 ]] && \
  2230. [[ ! -e /dir1/dir3/file7 ]] && \
  2231. [[ ! -e /dir1/dir3/file8 ]] && \
  2232. [[ -e /dir1/dir3 ]] && \
  2233. [[ -e /dir1/dir4 ]] && \
  2234. [[ ! -e 'dir1/dir5/fileAA' ]] && \
  2235. [[ -e 'dir1/dir5/fileAB' ]] && \
  2236. [[ -e 'dir1/dir5/fileB' ]]" # "." in pattern means nothing
  2237. RUN echo all done!`
  2238. dockerignore := `
  2239. **/file0
  2240. **/*file1
  2241. **/dir1/file2
  2242. dir1/**/file4
  2243. **/dir2/file5
  2244. **/dir1/dir2/file6
  2245. dir1/dir3/**
  2246. **/dir4/**
  2247. **/file?A
  2248. **/file\?B
  2249. **/dir5/file.
  2250. `
  2251. buildImageSuccessfully(c, "noname", build.WithBuildContext(c,
  2252. build.WithFile("Dockerfile", dockerfile),
  2253. build.WithFile(".dockerignore", dockerignore),
  2254. build.WithFile("dir1/file0", ""),
  2255. build.WithFile("dir1/dir2/file0", ""),
  2256. build.WithFile("file1", ""),
  2257. build.WithFile("dir1/file1", ""),
  2258. build.WithFile("dir1/dir2/file1", ""),
  2259. build.WithFile("dir1/file2", ""),
  2260. build.WithFile("dir1/dir2/file2", ""), // remains
  2261. build.WithFile("dir1/dir2/file4", ""),
  2262. build.WithFile("dir1/dir2/file5", ""),
  2263. build.WithFile("dir1/dir2/file6", ""),
  2264. build.WithFile("dir1/dir3/file7", ""),
  2265. build.WithFile("dir1/dir3/file8", ""),
  2266. build.WithFile("dir1/dir4/file9", ""),
  2267. build.WithFile("dir1/dir5/fileAA", ""),
  2268. build.WithFile("dir1/dir5/fileAB", ""),
  2269. build.WithFile("dir1/dir5/fileB", ""),
  2270. ))
  2271. }
  2272. func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
  2273. testRequires(c, DaemonIsLinux)
  2274. name := "testbuildlinebreak"
  2275. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2276. RUN sh -c 'echo root:testpass \
  2277. > /tmp/passwd'
  2278. RUN mkdir -p /var/run/sshd
  2279. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  2280. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`))
  2281. }
  2282. func (s *DockerSuite) TestBuildEOLInLine(c *check.C) {
  2283. testRequires(c, DaemonIsLinux)
  2284. name := "testbuildeolinline"
  2285. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2286. RUN sh -c 'echo root:testpass > /tmp/passwd'
  2287. RUN echo "foo \n bar"; echo "baz"
  2288. RUN mkdir -p /var/run/sshd
  2289. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  2290. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`))
  2291. }
  2292. func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) {
  2293. testRequires(c, DaemonIsLinux)
  2294. name := "testbuildcomments"
  2295. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2296. # This is an ordinary comment.
  2297. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  2298. RUN [ ! -x /hello.sh ]
  2299. # comment with line break \
  2300. RUN chmod +x /hello.sh
  2301. RUN [ -x /hello.sh ]
  2302. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  2303. RUN [ "$(/hello.sh)" = "hello world" ]`))
  2304. }
  2305. func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) {
  2306. testRequires(c, DaemonIsLinux)
  2307. name := "testbuildusers"
  2308. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2309. # Make sure our defaults work
  2310. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  2311. # 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)
  2312. USER root
  2313. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  2314. # Setup dockerio user and group
  2315. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd && \
  2316. echo 'dockerio:x:1001:' >> /etc/group
  2317. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  2318. USER dockerio
  2319. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2320. # Switch back to root and double check that worked exactly as we might expect it to
  2321. USER root
  2322. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ] && \
  2323. # Add a "supplementary" group for our dockerio user
  2324. echo 'supplementary:x:1002:dockerio' >> /etc/group
  2325. # ... and then go verify that we get it like we expect
  2326. USER dockerio
  2327. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  2328. USER 1001
  2329. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  2330. # super test the new "user:group" syntax
  2331. USER dockerio:dockerio
  2332. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2333. USER 1001:dockerio
  2334. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2335. USER dockerio:1001
  2336. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2337. USER 1001:1001
  2338. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2339. USER dockerio:supplementary
  2340. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2341. USER dockerio:1002
  2342. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2343. USER 1001:supplementary
  2344. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2345. USER 1001:1002
  2346. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2347. # make sure unknown uid/gid still works properly
  2348. USER 1042:1043
  2349. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`))
  2350. }
  2351. // FIXME(vdemeester) rename this test (and probably "merge" it with the one below TestBuildEnvUsage2)
  2352. func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
  2353. // /docker/world/hello is not owned by the correct user
  2354. testRequires(c, NotUserNamespace)
  2355. testRequires(c, DaemonIsLinux)
  2356. name := "testbuildenvusage"
  2357. dockerfile := `FROM busybox
  2358. ENV HOME /root
  2359. ENV PATH $HOME/bin:$PATH
  2360. ENV PATH /tmp:$PATH
  2361. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  2362. ENV FOO /foo/baz
  2363. ENV BAR /bar
  2364. ENV BAZ $BAR
  2365. ENV FOOPATH $PATH:$FOO
  2366. RUN [ "$BAR" = "$BAZ" ]
  2367. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  2368. ENV FROM hello/docker/world
  2369. ENV TO /docker/world/hello
  2370. ADD $FROM $TO
  2371. RUN [ "$(cat $TO)" = "hello" ]
  2372. ENV abc=def
  2373. ENV ghi=$abc
  2374. RUN [ "$ghi" = "def" ]
  2375. `
  2376. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2377. build.WithFile("Dockerfile", dockerfile),
  2378. build.WithFile("hello/docker/world", "hello"),
  2379. ))
  2380. }
  2381. // FIXME(vdemeester) rename this test (and probably "merge" it with the one above TestBuildEnvUsage)
  2382. func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
  2383. // /docker/world/hello is not owned by the correct user
  2384. testRequires(c, NotUserNamespace)
  2385. testRequires(c, DaemonIsLinux)
  2386. name := "testbuildenvusage2"
  2387. dockerfile := `FROM busybox
  2388. ENV abc=def def="hello world"
  2389. RUN [ "$abc,$def" = "def,hello world" ]
  2390. ENV def=hello\ world v1=abc v2="hi there" v3='boogie nights' v4="with'quotes too"
  2391. RUN [ "$def,$v1,$v2,$v3,$v4" = "hello world,abc,hi there,boogie nights,with'quotes too" ]
  2392. ENV abc=zzz FROM=hello/docker/world
  2393. ENV abc=zzz TO=/docker/world/hello
  2394. ADD $FROM $TO
  2395. RUN [ "$abc,$(cat $TO)" = "zzz,hello" ]
  2396. ENV abc 'yyy'
  2397. RUN [ $abc = 'yyy' ]
  2398. ENV abc=
  2399. RUN [ "$abc" = "" ]
  2400. # use grep to make sure if the builder substitutes \$foo by mistake
  2401. # we don't get a false positive
  2402. ENV abc=\$foo
  2403. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  2404. ENV abc \$foo
  2405. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  2406. ENV abc=\'foo\' abc2=\"foo\"
  2407. RUN [ "$abc,$abc2" = "'foo',\"foo\"" ]
  2408. ENV abc "foo"
  2409. RUN [ "$abc" = "foo" ]
  2410. ENV abc 'foo'
  2411. RUN [ "$abc" = 'foo' ]
  2412. ENV abc \'foo\'
  2413. RUN [ "$abc" = "'foo'" ]
  2414. ENV abc \"foo\"
  2415. RUN [ "$abc" = '"foo"' ]
  2416. ENV abc=ABC
  2417. RUN [ "$abc" = "ABC" ]
  2418. ENV def1=${abc:-DEF} def2=${ccc:-DEF}
  2419. ENV def3=${ccc:-${def2}xx} def4=${abc:+ALT} def5=${def2:+${abc}:} def6=${ccc:-\$abc:} def7=${ccc:-\${abc}:}
  2420. RUN [ "$def1,$def2,$def3,$def4,$def5,$def6,$def7" = 'ABC,DEF,DEFxx,ALT,ABC:,$abc:,${abc:}' ]
  2421. ENV mypath=${mypath:+$mypath:}/home
  2422. ENV mypath=${mypath:+$mypath:}/away
  2423. RUN [ "$mypath" = '/home:/away' ]
  2424. ENV e1=bar
  2425. ENV e2=$e1 e3=$e11 e4=\$e1 e5=\$e11
  2426. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  2427. ENV ee1 bar
  2428. ENV ee2 $ee1
  2429. ENV ee3 $ee11
  2430. ENV ee4 \$ee1
  2431. ENV ee5 \$ee11
  2432. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  2433. ENV eee1="foo" eee2='foo'
  2434. ENV eee3 "foo"
  2435. ENV eee4 'foo'
  2436. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  2437. `
  2438. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2439. build.WithFile("Dockerfile", dockerfile),
  2440. build.WithFile("hello/docker/world", "hello"),
  2441. ))
  2442. }
  2443. func (s *DockerSuite) TestBuildAddScript(c *check.C) {
  2444. testRequires(c, DaemonIsLinux)
  2445. name := "testbuildaddscript"
  2446. dockerfile := `
  2447. FROM busybox
  2448. ADD test /test
  2449. RUN ["chmod","+x","/test"]
  2450. RUN ["/test"]
  2451. RUN [ "$(cat /testfile)" = 'test!' ]`
  2452. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2453. build.WithFile("Dockerfile", dockerfile),
  2454. build.WithFile("test", "#!/bin/sh\necho 'test!' > /testfile"),
  2455. ))
  2456. }
  2457. func (s *DockerSuite) TestBuildAddTar(c *check.C) {
  2458. // /test/foo is not owned by the correct user
  2459. testRequires(c, NotUserNamespace)
  2460. name := "testbuildaddtar"
  2461. ctx := func() *fakecontext.Fake {
  2462. dockerfile := `
  2463. FROM busybox
  2464. ADD test.tar /
  2465. RUN cat /test/foo | grep Hi
  2466. ADD test.tar /test.tar
  2467. RUN cat /test.tar/test/foo | grep Hi
  2468. ADD test.tar /unlikely-to-exist
  2469. RUN cat /unlikely-to-exist/test/foo | grep Hi
  2470. ADD test.tar /unlikely-to-exist-trailing-slash/
  2471. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  2472. RUN sh -c "mkdir /existing-directory" #sh -c is needed on Windows to use the correct mkdir
  2473. ADD test.tar /existing-directory
  2474. RUN cat /existing-directory/test/foo | grep Hi
  2475. ADD test.tar /existing-directory-trailing-slash/
  2476. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  2477. tmpDir, err := ioutil.TempDir("", "fake-context")
  2478. c.Assert(err, check.IsNil)
  2479. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2480. if err != nil {
  2481. c.Fatalf("failed to create test.tar archive: %v", err)
  2482. }
  2483. defer testTar.Close()
  2484. tw := tar.NewWriter(testTar)
  2485. if err := tw.WriteHeader(&tar.Header{
  2486. Name: "test/foo",
  2487. Size: 2,
  2488. }); err != nil {
  2489. c.Fatalf("failed to write tar file header: %v", err)
  2490. }
  2491. if _, err := tw.Write([]byte("Hi")); err != nil {
  2492. c.Fatalf("failed to write tar file content: %v", err)
  2493. }
  2494. if err := tw.Close(); err != nil {
  2495. c.Fatalf("failed to close tar archive: %v", err)
  2496. }
  2497. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2498. c.Fatalf("failed to open destination dockerfile: %v", err)
  2499. }
  2500. return fakecontext.New(c, tmpDir)
  2501. }()
  2502. defer ctx.Close()
  2503. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2504. }
  2505. func (s *DockerSuite) TestBuildAddBrokenTar(c *check.C) {
  2506. name := "testbuildaddbrokentar"
  2507. ctx := func() *fakecontext.Fake {
  2508. dockerfile := `
  2509. FROM busybox
  2510. ADD test.tar /`
  2511. tmpDir, err := ioutil.TempDir("", "fake-context")
  2512. c.Assert(err, check.IsNil)
  2513. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2514. if err != nil {
  2515. c.Fatalf("failed to create test.tar archive: %v", err)
  2516. }
  2517. defer testTar.Close()
  2518. tw := tar.NewWriter(testTar)
  2519. if err := tw.WriteHeader(&tar.Header{
  2520. Name: "test/foo",
  2521. Size: 2,
  2522. }); err != nil {
  2523. c.Fatalf("failed to write tar file header: %v", err)
  2524. }
  2525. if _, err := tw.Write([]byte("Hi")); err != nil {
  2526. c.Fatalf("failed to write tar file content: %v", err)
  2527. }
  2528. if err := tw.Close(); err != nil {
  2529. c.Fatalf("failed to close tar archive: %v", err)
  2530. }
  2531. // Corrupt the tar by removing one byte off the end
  2532. stat, err := testTar.Stat()
  2533. if err != nil {
  2534. c.Fatalf("failed to stat tar archive: %v", err)
  2535. }
  2536. if err := testTar.Truncate(stat.Size() - 1); err != nil {
  2537. c.Fatalf("failed to truncate tar archive: %v", err)
  2538. }
  2539. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2540. c.Fatalf("failed to open destination dockerfile: %v", err)
  2541. }
  2542. return fakecontext.New(c, tmpDir)
  2543. }()
  2544. defer ctx.Close()
  2545. buildImage(name, build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  2546. ExitCode: 1,
  2547. })
  2548. }
  2549. func (s *DockerSuite) TestBuildAddNonTar(c *check.C) {
  2550. name := "testbuildaddnontar"
  2551. // Should not try to extract test.tar
  2552. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2553. build.WithFile("Dockerfile", `
  2554. FROM busybox
  2555. ADD test.tar /
  2556. RUN test -f /test.tar`),
  2557. build.WithFile("test.tar", "not_a_tar_file"),
  2558. ))
  2559. }
  2560. func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
  2561. // /test/foo is not owned by the correct user
  2562. testRequires(c, NotUserNamespace)
  2563. testRequires(c, DaemonIsLinux)
  2564. name := "testbuildaddtarxz"
  2565. ctx := func() *fakecontext.Fake {
  2566. dockerfile := `
  2567. FROM busybox
  2568. ADD test.tar.xz /
  2569. RUN cat /test/foo | grep Hi`
  2570. tmpDir, err := ioutil.TempDir("", "fake-context")
  2571. c.Assert(err, check.IsNil)
  2572. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2573. if err != nil {
  2574. c.Fatalf("failed to create test.tar archive: %v", err)
  2575. }
  2576. defer testTar.Close()
  2577. tw := tar.NewWriter(testTar)
  2578. if err := tw.WriteHeader(&tar.Header{
  2579. Name: "test/foo",
  2580. Size: 2,
  2581. }); err != nil {
  2582. c.Fatalf("failed to write tar file header: %v", err)
  2583. }
  2584. if _, err := tw.Write([]byte("Hi")); err != nil {
  2585. c.Fatalf("failed to write tar file content: %v", err)
  2586. }
  2587. if err := tw.Close(); err != nil {
  2588. c.Fatalf("failed to close tar archive: %v", err)
  2589. }
  2590. icmd.RunCmd(icmd.Cmd{
  2591. Command: []string{"xz", "-k", "test.tar"},
  2592. Dir: tmpDir,
  2593. }).Assert(c, icmd.Success)
  2594. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2595. c.Fatalf("failed to open destination dockerfile: %v", err)
  2596. }
  2597. return fakecontext.New(c, tmpDir)
  2598. }()
  2599. defer ctx.Close()
  2600. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2601. }
  2602. func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
  2603. testRequires(c, DaemonIsLinux)
  2604. name := "testbuildaddtarxzgz"
  2605. ctx := func() *fakecontext.Fake {
  2606. dockerfile := `
  2607. FROM busybox
  2608. ADD test.tar.xz.gz /
  2609. RUN ls /test.tar.xz.gz`
  2610. tmpDir, err := ioutil.TempDir("", "fake-context")
  2611. c.Assert(err, check.IsNil)
  2612. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2613. if err != nil {
  2614. c.Fatalf("failed to create test.tar archive: %v", err)
  2615. }
  2616. defer testTar.Close()
  2617. tw := tar.NewWriter(testTar)
  2618. if err := tw.WriteHeader(&tar.Header{
  2619. Name: "test/foo",
  2620. Size: 2,
  2621. }); err != nil {
  2622. c.Fatalf("failed to write tar file header: %v", err)
  2623. }
  2624. if _, err := tw.Write([]byte("Hi")); err != nil {
  2625. c.Fatalf("failed to write tar file content: %v", err)
  2626. }
  2627. if err := tw.Close(); err != nil {
  2628. c.Fatalf("failed to close tar archive: %v", err)
  2629. }
  2630. icmd.RunCmd(icmd.Cmd{
  2631. Command: []string{"xz", "-k", "test.tar"},
  2632. Dir: tmpDir,
  2633. }).Assert(c, icmd.Success)
  2634. icmd.RunCmd(icmd.Cmd{
  2635. Command: []string{"gzip", "test.tar.xz"},
  2636. Dir: tmpDir,
  2637. })
  2638. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2639. c.Fatalf("failed to open destination dockerfile: %v", err)
  2640. }
  2641. return fakecontext.New(c, tmpDir)
  2642. }()
  2643. defer ctx.Close()
  2644. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2645. }
  2646. func (s *DockerSuite) TestBuildFromGit(c *check.C) {
  2647. name := "testbuildfromgit"
  2648. git := fakegit.New(c, "repo", map[string]string{
  2649. "Dockerfile": `FROM busybox
  2650. ADD first /first
  2651. RUN [ -f /first ]
  2652. MAINTAINER docker`,
  2653. "first": "test git data",
  2654. }, true)
  2655. defer git.Close()
  2656. buildImageSuccessfully(c, name, build.WithContextPath(git.RepoURL))
  2657. res := inspectField(c, name, "Author")
  2658. if res != "docker" {
  2659. c.Fatalf("Maintainer should be docker, got %s", res)
  2660. }
  2661. }
  2662. func (s *DockerSuite) TestBuildFromGitWithContext(c *check.C) {
  2663. name := "testbuildfromgit"
  2664. git := fakegit.New(c, "repo", map[string]string{
  2665. "docker/Dockerfile": `FROM busybox
  2666. ADD first /first
  2667. RUN [ -f /first ]
  2668. MAINTAINER docker`,
  2669. "docker/first": "test git data",
  2670. }, true)
  2671. defer git.Close()
  2672. buildImageSuccessfully(c, name, build.WithContextPath(fmt.Sprintf("%s#master:docker", git.RepoURL)))
  2673. res := inspectField(c, name, "Author")
  2674. if res != "docker" {
  2675. c.Fatalf("Maintainer should be docker, got %s", res)
  2676. }
  2677. }
  2678. func (s *DockerSuite) TestBuildFromGitwithF(c *check.C) {
  2679. name := "testbuildfromgitwithf"
  2680. git := fakegit.New(c, "repo", map[string]string{
  2681. "myApp/myDockerfile": `FROM busybox
  2682. RUN echo hi from Dockerfile`,
  2683. }, true)
  2684. defer git.Close()
  2685. buildImage(name, cli.WithFlags("-f", "myApp/myDockerfile"), build.WithContextPath(git.RepoURL)).Assert(c, icmd.Expected{
  2686. Out: "hi from Dockerfile",
  2687. })
  2688. }
  2689. func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
  2690. name := "testbuildfromremotetarball"
  2691. buffer := new(bytes.Buffer)
  2692. tw := tar.NewWriter(buffer)
  2693. defer tw.Close()
  2694. dockerfile := []byte(`FROM busybox
  2695. MAINTAINER docker`)
  2696. if err := tw.WriteHeader(&tar.Header{
  2697. Name: "Dockerfile",
  2698. Size: int64(len(dockerfile)),
  2699. }); err != nil {
  2700. c.Fatalf("failed to write tar file header: %v", err)
  2701. }
  2702. if _, err := tw.Write(dockerfile); err != nil {
  2703. c.Fatalf("failed to write tar file content: %v", err)
  2704. }
  2705. if err := tw.Close(); err != nil {
  2706. c.Fatalf("failed to close tar archive: %v", err)
  2707. }
  2708. server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
  2709. "testT.tar": buffer,
  2710. }))
  2711. defer server.Close()
  2712. cli.BuildCmd(c, name, build.WithContextPath(server.URL()+"/testT.tar"))
  2713. res := inspectField(c, name, "Author")
  2714. if res != "docker" {
  2715. c.Fatalf("Maintainer should be docker, got %s", res)
  2716. }
  2717. }
  2718. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
  2719. name := "testbuildcmdcleanuponentrypoint"
  2720. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  2721. CMD ["test"]
  2722. ENTRYPOINT ["echo"]`))
  2723. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  2724. ENTRYPOINT ["cat"]`, name)))
  2725. res := inspectField(c, name, "Config.Cmd")
  2726. if res != "[]" {
  2727. c.Fatalf("Cmd %s, expected nil", res)
  2728. }
  2729. res = inspectField(c, name, "Config.Entrypoint")
  2730. if expected := "[cat]"; res != expected {
  2731. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2732. }
  2733. }
  2734. func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
  2735. name := "testbuildclearcmd"
  2736. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  2737. ENTRYPOINT ["/bin/bash"]
  2738. CMD []`))
  2739. res := inspectFieldJSON(c, name, "Config.Cmd")
  2740. if res != "[]" {
  2741. c.Fatalf("Cmd %s, expected %s", res, "[]")
  2742. }
  2743. }
  2744. func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
  2745. // Skip on Windows. Base image on Windows has a CMD set in the image.
  2746. testRequires(c, DaemonIsLinux)
  2747. name := "testbuildemptycmd"
  2748. buildImageSuccessfully(c, name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n"))
  2749. res := inspectFieldJSON(c, name, "Config.Cmd")
  2750. if res != "null" {
  2751. c.Fatalf("Cmd %s, expected %s", res, "null")
  2752. }
  2753. }
  2754. func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
  2755. name := "testbuildonbuildparent"
  2756. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nONBUILD RUN echo foo\n"))
  2757. buildImage(name, build.WithDockerfile("FROM "+name+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2758. Out: "# Executing 1 build trigger",
  2759. })
  2760. }
  2761. // FIXME(vdemeester) should be a unit test
  2762. func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
  2763. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  2764. buildImage(name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2765. ExitCode: 125,
  2766. Err: "invalid reference format",
  2767. })
  2768. }
  2769. func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
  2770. name := "testbuildcmdshc"
  2771. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD echo cmd\n"))
  2772. res := inspectFieldJSON(c, name, "Config.Cmd")
  2773. expected := `["/bin/sh","-c","echo cmd"]`
  2774. if testEnv.DaemonPlatform() == "windows" {
  2775. expected = `["cmd","/S","/C","echo cmd"]`
  2776. }
  2777. if res != expected {
  2778. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2779. }
  2780. }
  2781. func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
  2782. // Test to make sure that when we strcat arrays we take into account
  2783. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  2784. // look the same
  2785. name := "testbuildcmdspaces"
  2786. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo hi\"]\n"))
  2787. id1 := getIDByName(c, name)
  2788. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"hi\"]\n"))
  2789. id2 := getIDByName(c, name)
  2790. if id1 == id2 {
  2791. c.Fatal("Should not have resulted in the same CMD")
  2792. }
  2793. // Now do the same with ENTRYPOINT
  2794. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT [\"echo hi\"]\n"))
  2795. id1 = getIDByName(c, name)
  2796. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n"))
  2797. id2 = getIDByName(c, name)
  2798. if id1 == id2 {
  2799. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  2800. }
  2801. }
  2802. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
  2803. name := "testbuildcmdjson"
  2804. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"cmd\"]"))
  2805. res := inspectFieldJSON(c, name, "Config.Cmd")
  2806. expected := `["echo","cmd"]`
  2807. if res != expected {
  2808. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2809. }
  2810. }
  2811. func (s *DockerSuite) TestBuildEntrypointCanBeOverridenByChild(c *check.C) {
  2812. buildImageSuccessfully(c, "parent", build.WithDockerfile(`
  2813. FROM busybox
  2814. ENTRYPOINT exit 130
  2815. `))
  2816. icmd.RunCommand(dockerBinary, "run", "parent").Assert(c, icmd.Expected{
  2817. ExitCode: 130,
  2818. })
  2819. buildImageSuccessfully(c, "child", build.WithDockerfile(`
  2820. FROM parent
  2821. ENTRYPOINT exit 5
  2822. `))
  2823. icmd.RunCommand(dockerBinary, "run", "child").Assert(c, icmd.Expected{
  2824. ExitCode: 5,
  2825. })
  2826. }
  2827. func (s *DockerSuite) TestBuildEntrypointCanBeOverridenByChildInspect(c *check.C) {
  2828. var (
  2829. name = "testbuildepinherit"
  2830. name2 = "testbuildepinherit2"
  2831. expected = `["/bin/sh","-c","echo quux"]`
  2832. )
  2833. if testEnv.DaemonPlatform() == "windows" {
  2834. expected = `["cmd","/S","/C","echo quux"]`
  2835. }
  2836. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT /foo/bar"))
  2837. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name)))
  2838. res := inspectFieldJSON(c, name2, "Config.Entrypoint")
  2839. if res != expected {
  2840. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  2841. }
  2842. icmd.RunCommand(dockerBinary, "run", name2).Assert(c, icmd.Expected{
  2843. Out: "quux",
  2844. })
  2845. }
  2846. func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
  2847. name := "testbuildentrypoint"
  2848. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2849. ENTRYPOINT echo`))
  2850. dockerCmd(c, "run", "--rm", name)
  2851. }
  2852. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
  2853. testRequires(c, DaemonIsLinux)
  2854. name := "testbuildexoticshellinterpolation"
  2855. buildImageSuccessfully(c, name, build.WithDockerfile(`
  2856. FROM busybox
  2857. ENV SOME_VAR a.b.c
  2858. RUN [ "$SOME_VAR" = 'a.b.c' ]
  2859. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  2860. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  2861. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  2862. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  2863. RUN [ "${SOME_VAR##*.}" = 'c' ]
  2864. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  2865. RUN [ "${#SOME_VAR}" = '5' ]
  2866. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  2867. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  2868. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  2869. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  2870. `))
  2871. }
  2872. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
  2873. // This testcase is supposed to generate an error because the
  2874. // JSON array we're passing in on the CMD uses single quotes instead
  2875. // of double quotes (per the JSON spec). This means we interpret it
  2876. // as a "string" instead of "JSON array" and pass it on to "sh -c" and
  2877. // it should barf on it.
  2878. name := "testbuildsinglequotefails"
  2879. expectedExitCode := 2
  2880. if testEnv.DaemonPlatform() == "windows" {
  2881. expectedExitCode = 127
  2882. }
  2883. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2884. CMD [ '/bin/sh', '-c', 'echo hi' ]`))
  2885. icmd.RunCommand(dockerBinary, "run", "--rm", name).Assert(c, icmd.Expected{
  2886. ExitCode: expectedExitCode,
  2887. })
  2888. }
  2889. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  2890. name := "testbuildverboseout"
  2891. expected := "\n123\n"
  2892. if testEnv.DaemonPlatform() == "windows" {
  2893. expected = "\n123\r\n"
  2894. }
  2895. buildImage(name, build.WithDockerfile(`FROM busybox
  2896. RUN echo 123`)).Assert(c, icmd.Expected{
  2897. Out: expected,
  2898. })
  2899. }
  2900. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  2901. name := "testbuildwithtabs"
  2902. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nRUN echo\tone\t\ttwo"))
  2903. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  2904. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  2905. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2906. if testEnv.DaemonPlatform() == "windows" {
  2907. expected1 = `["cmd","/S","/C","echo\tone\t\ttwo"]`
  2908. expected2 = `["cmd","/S","/C","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2909. }
  2910. if res != expected1 && res != expected2 {
  2911. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  2912. }
  2913. }
  2914. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  2915. name := "testbuildlabel"
  2916. expected := `{"License":"GPL","Vendor":"Acme"}`
  2917. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2918. LABEL Vendor=Acme
  2919. LABEL License GPL`))
  2920. res := inspectFieldJSON(c, name, "Config.Labels")
  2921. if res != expected {
  2922. c.Fatalf("Labels %s, expected %s", res, expected)
  2923. }
  2924. }
  2925. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  2926. name := "testbuildlabelcache"
  2927. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2928. LABEL Vendor=Acme`))
  2929. id1 := getIDByName(c, name)
  2930. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2931. LABEL Vendor=Acme`))
  2932. id2 := getIDByName(c, name)
  2933. if id1 != id2 {
  2934. c.Fatalf("Build 2 should have worked & used cache(%s,%s)", id1, id2)
  2935. }
  2936. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2937. LABEL Vendor=Acme1`))
  2938. id2 = getIDByName(c, name)
  2939. if id1 == id2 {
  2940. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s)", id1, id2)
  2941. }
  2942. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2943. LABEL Vendor Acme`))
  2944. id2 = getIDByName(c, name)
  2945. if id1 != id2 {
  2946. c.Fatalf("Build 4 should have worked & used cache(%s,%s)", id1, id2)
  2947. }
  2948. // Now make sure the cache isn't used by mistake
  2949. buildImageSuccessfully(c, name, build.WithoutCache, build.WithDockerfile(`FROM busybox
  2950. LABEL f1=b1 f2=b2`))
  2951. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2952. LABEL f1=b1 f2=b2`))
  2953. id2 = getIDByName(c, name)
  2954. if id1 == id2 {
  2955. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s)", id1, id2)
  2956. }
  2957. }
  2958. func (s *DockerSuite) TestBuildNotVerboseSuccess(c *check.C) {
  2959. // This test makes sure that -q works correctly when build is successful:
  2960. // stdout has only the image ID (long image ID) and stderr is empty.
  2961. outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$")
  2962. buildFlags := cli.WithFlags("-q")
  2963. tt := []struct {
  2964. Name string
  2965. BuildFunc func(string) *icmd.Result
  2966. }{
  2967. {
  2968. Name: "quiet_build_stdin_success",
  2969. BuildFunc: func(name string) *icmd.Result {
  2970. return buildImage(name, buildFlags, build.WithDockerfile("FROM busybox"))
  2971. },
  2972. },
  2973. {
  2974. Name: "quiet_build_ctx_success",
  2975. BuildFunc: func(name string) *icmd.Result {
  2976. return buildImage(name, buildFlags, build.WithBuildContext(c,
  2977. build.WithFile("Dockerfile", "FROM busybox"),
  2978. build.WithFile("quiet_build_success_fctx", "test"),
  2979. ))
  2980. },
  2981. },
  2982. {
  2983. Name: "quiet_build_git_success",
  2984. BuildFunc: func(name string) *icmd.Result {
  2985. git := fakegit.New(c, "repo", map[string]string{
  2986. "Dockerfile": "FROM busybox",
  2987. }, true)
  2988. return buildImage(name, buildFlags, build.WithContextPath(git.RepoURL))
  2989. },
  2990. },
  2991. }
  2992. for _, te := range tt {
  2993. result := te.BuildFunc(te.Name)
  2994. result.Assert(c, icmd.Success)
  2995. if outRegexp.Find([]byte(result.Stdout())) == nil {
  2996. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, result.Stdout())
  2997. }
  2998. if result.Stderr() != "" {
  2999. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, result.Stderr())
  3000. }
  3001. }
  3002. }
  3003. func (s *DockerSuite) TestBuildNotVerboseFailureWithNonExistImage(c *check.C) {
  3004. // This test makes sure that -q works correctly when build fails by
  3005. // comparing between the stderr output in quiet mode and in stdout
  3006. // and stderr output in verbose mode
  3007. testRequires(c, Network)
  3008. testName := "quiet_build_not_exists_image"
  3009. dockerfile := "FROM busybox11"
  3010. quietResult := buildImage(testName, cli.WithFlags("-q"), build.WithDockerfile(dockerfile))
  3011. quietResult.Assert(c, icmd.Expected{
  3012. ExitCode: 1,
  3013. })
  3014. result := buildImage(testName, build.WithDockerfile(dockerfile))
  3015. result.Assert(c, icmd.Expected{
  3016. ExitCode: 1,
  3017. })
  3018. if quietResult.Stderr() != result.Combined() {
  3019. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", testName, quietResult.Stderr(), result.Combined()))
  3020. }
  3021. }
  3022. func (s *DockerSuite) TestBuildNotVerboseFailure(c *check.C) {
  3023. // This test makes sure that -q works correctly when build fails by
  3024. // comparing between the stderr output in quiet mode and in stdout
  3025. // and stderr output in verbose mode
  3026. testCases := []struct {
  3027. testName string
  3028. dockerfile string
  3029. }{
  3030. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  3031. {"quiet_build_unknown_instr", "FROMD busybox"},
  3032. }
  3033. for _, tc := range testCases {
  3034. quietResult := buildImage(tc.testName, cli.WithFlags("-q"), build.WithDockerfile(tc.dockerfile))
  3035. quietResult.Assert(c, icmd.Expected{
  3036. ExitCode: 1,
  3037. })
  3038. result := buildImage(tc.testName, build.WithDockerfile(tc.dockerfile))
  3039. result.Assert(c, icmd.Expected{
  3040. ExitCode: 1,
  3041. })
  3042. if quietResult.Stderr() != result.Combined() {
  3043. 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()))
  3044. }
  3045. }
  3046. }
  3047. func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *check.C) {
  3048. // This test ensures that when given a wrong URL, stderr in quiet mode and
  3049. // stderr in verbose mode are identical.
  3050. // TODO(vdemeester) with cobra, stdout has a carriage return too much so this test should not check stdout
  3051. URL := "http://something.invalid"
  3052. name := "quiet_build_wrong_remote"
  3053. quietResult := buildImage(name, cli.WithFlags("-q"), build.WithContextPath(URL))
  3054. quietResult.Assert(c, icmd.Expected{
  3055. ExitCode: 1,
  3056. })
  3057. result := buildImage(name, build.WithContextPath(URL))
  3058. result.Assert(c, icmd.Expected{
  3059. ExitCode: 1,
  3060. })
  3061. if strings.TrimSpace(quietResult.Stderr()) != strings.TrimSpace(result.Combined()) {
  3062. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", name, quietResult.Stderr(), result.Combined()))
  3063. }
  3064. }
  3065. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  3066. // This test just makes sure that no non-error output goes
  3067. // to stderr
  3068. name := "testbuildstderr"
  3069. result := buildImage(name, build.WithDockerfile("FROM busybox\nRUN echo one"))
  3070. result.Assert(c, icmd.Success)
  3071. // Windows to non-Windows should have a security warning
  3072. if runtime.GOOS == "windows" && testEnv.DaemonPlatform() != "windows" && !strings.Contains(result.Stdout(), "SECURITY WARNING:") {
  3073. c.Fatalf("Stdout contains unexpected output: %q", result.Stdout())
  3074. }
  3075. // Stderr should always be empty
  3076. if result.Stderr() != "" {
  3077. c.Fatalf("Stderr should have been empty, instead it's: %q", result.Stderr())
  3078. }
  3079. }
  3080. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  3081. testRequires(c, UnixCli, DaemonIsLinux) // test uses chown: not available on windows
  3082. name := "testbuildchownsinglefile"
  3083. ctx := fakecontext.New(c, "",
  3084. fakecontext.WithDockerfile(`
  3085. FROM busybox
  3086. COPY test /
  3087. RUN ls -l /test
  3088. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3089. `),
  3090. fakecontext.WithFiles(map[string]string{
  3091. "test": "test",
  3092. }))
  3093. defer ctx.Close()
  3094. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  3095. c.Fatal(err)
  3096. }
  3097. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  3098. }
  3099. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  3100. name := "testbuildsymlinkbreakout"
  3101. tmpdir, err := ioutil.TempDir("", name)
  3102. c.Assert(err, check.IsNil)
  3103. defer os.RemoveAll(tmpdir)
  3104. ctx := filepath.Join(tmpdir, "context")
  3105. if err := os.MkdirAll(ctx, 0755); err != nil {
  3106. c.Fatal(err)
  3107. }
  3108. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  3109. from busybox
  3110. add symlink.tar /
  3111. add inject /symlink/
  3112. `), 0644); err != nil {
  3113. c.Fatal(err)
  3114. }
  3115. inject := filepath.Join(ctx, "inject")
  3116. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  3117. c.Fatal(err)
  3118. }
  3119. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  3120. if err != nil {
  3121. c.Fatal(err)
  3122. }
  3123. w := tar.NewWriter(f)
  3124. w.WriteHeader(&tar.Header{
  3125. Name: "symlink2",
  3126. Typeflag: tar.TypeSymlink,
  3127. Linkname: "/../../../../../../../../../../../../../../",
  3128. Uid: os.Getuid(),
  3129. Gid: os.Getgid(),
  3130. })
  3131. w.WriteHeader(&tar.Header{
  3132. Name: "symlink",
  3133. Typeflag: tar.TypeSymlink,
  3134. Linkname: filepath.Join("symlink2", tmpdir),
  3135. Uid: os.Getuid(),
  3136. Gid: os.Getgid(),
  3137. })
  3138. w.Close()
  3139. f.Close()
  3140. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(fakecontext.New(c, ctx)))
  3141. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  3142. c.Fatal("symlink breakout - inject")
  3143. } else if !os.IsNotExist(err) {
  3144. c.Fatalf("unexpected error: %v", err)
  3145. }
  3146. }
  3147. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  3148. // /usr/local/sbin/xz gets permission denied for the user
  3149. testRequires(c, NotUserNamespace)
  3150. testRequires(c, DaemonIsLinux)
  3151. name := "testbuildxzhost"
  3152. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3153. build.WithFile("Dockerfile", `
  3154. FROM busybox
  3155. ADD xz /usr/local/sbin/
  3156. RUN chmod 755 /usr/local/sbin/xz
  3157. ADD test.xz /
  3158. RUN [ ! -e /injected ]`),
  3159. 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"),
  3160. build.WithFile("xz", "#!/bin/sh\ntouch /injected"),
  3161. ))
  3162. }
  3163. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  3164. // /foo/file gets permission denied for the user
  3165. testRequires(c, NotUserNamespace)
  3166. testRequires(c, DaemonIsLinux) // TODO Windows: Issue #20127
  3167. var (
  3168. name = "testbuildvolumescontent"
  3169. expected = "some text"
  3170. volName = "/foo"
  3171. )
  3172. if testEnv.DaemonPlatform() == "windows" {
  3173. volName = "C:/foo"
  3174. }
  3175. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3176. build.WithFile("Dockerfile", `
  3177. FROM busybox
  3178. COPY content /foo/file
  3179. VOLUME `+volName+`
  3180. CMD cat /foo/file`),
  3181. build.WithFile("content", expected),
  3182. ))
  3183. out, _ := dockerCmd(c, "run", "--rm", name)
  3184. if out != expected {
  3185. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  3186. }
  3187. }
  3188. // FIXME(vdemeester) part of this should be unit test, other part should be clearer
  3189. func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
  3190. ctx := fakecontext.New(c, "", fakecontext.WithFiles(map[string]string{
  3191. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  3192. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  3193. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  3194. "dFile": "FROM busybox\nRUN echo from dFile",
  3195. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  3196. }))
  3197. defer ctx.Close()
  3198. cli.Docker(cli.Args("build", "-t", "test1", "."), cli.InDir(ctx.Dir)).Assert(c, icmd.Expected{
  3199. Out: "from Dockerfile",
  3200. })
  3201. cli.Docker(cli.Args("build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", "."), cli.InDir(ctx.Dir)).Assert(c, icmd.Expected{
  3202. Out: "from files/Dockerfile",
  3203. })
  3204. cli.Docker(cli.Args("build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", "."), cli.InDir(ctx.Dir)).Assert(c, icmd.Expected{
  3205. Out: "from files/dFile",
  3206. })
  3207. cli.Docker(cli.Args("build", "--file=dFile", "-t", "test4", "."), cli.InDir(ctx.Dir)).Assert(c, icmd.Expected{
  3208. Out: "from dFile",
  3209. })
  3210. dirWithNoDockerfile, err := ioutil.TempDir(os.TempDir(), "test5")
  3211. c.Assert(err, check.IsNil)
  3212. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  3213. if _, err = os.Create(nonDockerfileFile); err != nil {
  3214. c.Fatal(err)
  3215. }
  3216. cli.Docker(cli.Args("build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", "."), cli.InDir(ctx.Dir)).Assert(c, icmd.Expected{
  3217. ExitCode: 1,
  3218. Err: fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile),
  3219. })
  3220. cli.Docker(cli.Args("build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", ".."), cli.InDir(filepath.Join(ctx.Dir, "files"))).Assert(c, icmd.Expected{
  3221. Out: "from Dockerfile",
  3222. })
  3223. 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{
  3224. Out: "from files/Dockerfile",
  3225. })
  3226. cli.Docker(cli.Args("build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", "."), cli.InDir(filepath.Join(ctx.Dir, "files"))).Assert(c, icmd.Expected{
  3227. ExitCode: 1,
  3228. Err: "must be within the build context",
  3229. })
  3230. tmpDir := os.TempDir()
  3231. cli.Docker(cli.Args("build", "-t", "test9", ctx.Dir), cli.InDir(tmpDir)).Assert(c, icmd.Expected{
  3232. Out: "from Dockerfile",
  3233. })
  3234. cli.Docker(cli.Args("build", "-f", "dFile2", "-t", "test10", "."), cli.InDir(filepath.Join(ctx.Dir, "files"))).Assert(c, icmd.Expected{
  3235. Out: "from files/dFile2",
  3236. })
  3237. }
  3238. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  3239. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  3240. testRequires(c, DaemonIsLinux)
  3241. // If Dockerfile is not present, use dockerfile
  3242. buildImage("test1", build.WithBuildContext(c,
  3243. build.WithFile("dockerfile", `FROM busybox
  3244. RUN echo from dockerfile`),
  3245. )).Assert(c, icmd.Expected{
  3246. Out: "from dockerfile",
  3247. })
  3248. // Prefer Dockerfile in place of dockerfile
  3249. buildImage("test1", build.WithBuildContext(c,
  3250. build.WithFile("dockerfile", `FROM busybox
  3251. RUN echo from dockerfile`),
  3252. build.WithFile("Dockerfile", `FROM busybox
  3253. RUN echo from Dockerfile`),
  3254. )).Assert(c, icmd.Expected{
  3255. Out: "from Dockerfile",
  3256. })
  3257. }
  3258. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  3259. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{"baz": `FROM busybox
  3260. RUN echo from baz
  3261. COPY * /tmp/
  3262. RUN find /tmp/`}))
  3263. defer server.Close()
  3264. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3265. RUN echo from Dockerfile`))
  3266. defer ctx.Close()
  3267. // Make sure that -f is ignored and that we don't use the Dockerfile
  3268. // that's in the current dir
  3269. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", server.URL()+"/baz"), func(cmd *icmd.Cmd) func() {
  3270. cmd.Dir = ctx.Dir
  3271. return nil
  3272. })
  3273. if !strings.Contains(result.Combined(), "from baz") ||
  3274. strings.Contains(result.Combined(), "/tmp/baz") ||
  3275. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3276. c.Fatalf("Missing proper output: %s", result.Combined())
  3277. }
  3278. }
  3279. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  3280. testRequires(c, DaemonIsLinux) // TODO Windows: This test is flaky; no idea why
  3281. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3282. RUN echo "from Dockerfile"`))
  3283. defer ctx.Close()
  3284. // Make sure that -f is ignored and that we don't use the Dockerfile
  3285. // that's in the current dir
  3286. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", "-"), func(cmd *icmd.Cmd) func() {
  3287. cmd.Dir = ctx.Dir
  3288. cmd.Stdin = strings.NewReader(`FROM busybox
  3289. RUN echo "from baz"
  3290. COPY * /tmp/
  3291. RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`)
  3292. return nil
  3293. })
  3294. if !strings.Contains(result.Combined(), "from baz") ||
  3295. strings.Contains(result.Combined(), "/tmp/baz") ||
  3296. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3297. c.Fatalf("Missing proper output: %s", result.Combined())
  3298. }
  3299. }
  3300. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  3301. name := "testbuildfromofficial"
  3302. fromNames := []string{
  3303. "busybox",
  3304. "docker.io/busybox",
  3305. "index.docker.io/busybox",
  3306. "library/busybox",
  3307. "docker.io/library/busybox",
  3308. "index.docker.io/library/busybox",
  3309. }
  3310. for idx, fromName := range fromNames {
  3311. imgName := fmt.Sprintf("%s%d", name, idx)
  3312. buildImageSuccessfully(c, imgName, build.WithDockerfile("FROM "+fromName))
  3313. dockerCmd(c, "rmi", imgName)
  3314. }
  3315. }
  3316. func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
  3317. testRequires(c, UnixCli, DaemonIsLinux) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  3318. name := "testbuilddockerfileoutsidecontext"
  3319. tmpdir, err := ioutil.TempDir("", name)
  3320. c.Assert(err, check.IsNil)
  3321. defer os.RemoveAll(tmpdir)
  3322. ctx := filepath.Join(tmpdir, "context")
  3323. if err := os.MkdirAll(ctx, 0755); err != nil {
  3324. c.Fatal(err)
  3325. }
  3326. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  3327. c.Fatal(err)
  3328. }
  3329. wd, err := os.Getwd()
  3330. if err != nil {
  3331. c.Fatal(err)
  3332. }
  3333. defer os.Chdir(wd)
  3334. if err := os.Chdir(ctx); err != nil {
  3335. c.Fatal(err)
  3336. }
  3337. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  3338. c.Fatal(err)
  3339. }
  3340. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  3341. c.Fatal(err)
  3342. }
  3343. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  3344. c.Fatal(err)
  3345. }
  3346. for _, dockerfilePath := range []string{
  3347. filepath.Join("..", "outsideDockerfile"),
  3348. filepath.Join(ctx, "dockerfile1"),
  3349. filepath.Join(ctx, "dockerfile2"),
  3350. } {
  3351. result := dockerCmdWithResult("build", "-t", name, "--no-cache", "-f", dockerfilePath, ".")
  3352. c.Assert(result, icmd.Matches, icmd.Expected{
  3353. Err: "must be within the build context",
  3354. ExitCode: 1,
  3355. })
  3356. deleteImages(name)
  3357. }
  3358. os.Chdir(tmpdir)
  3359. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  3360. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  3361. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx)
  3362. if err == nil {
  3363. c.Fatalf("Expected error. Out: %s", out)
  3364. }
  3365. }
  3366. // FIXME(vdemeester) should be a unit test
  3367. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  3368. // Test to make sure that leading/trailing spaces on a command
  3369. // doesn't change the error msg we get
  3370. name := "testspaces"
  3371. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM busybox\nCOPY\n"))
  3372. defer ctx.Close()
  3373. result1 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx))
  3374. result1.Assert(c, icmd.Expected{
  3375. ExitCode: 1,
  3376. })
  3377. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  3378. result2 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx))
  3379. result2.Assert(c, icmd.Expected{
  3380. ExitCode: 1,
  3381. })
  3382. removeLogTimestamps := func(s string) string {
  3383. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  3384. }
  3385. // Skip over the times
  3386. e1 := removeLogTimestamps(result1.Error.Error())
  3387. e2 := removeLogTimestamps(result2.Error.Error())
  3388. // Ignore whitespace since that's what were verifying doesn't change stuff
  3389. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3390. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
  3391. }
  3392. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  3393. result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3394. result2.Assert(c, icmd.Expected{
  3395. ExitCode: 1,
  3396. })
  3397. // Skip over the times
  3398. e1 = removeLogTimestamps(result1.Error.Error())
  3399. e2 = removeLogTimestamps(result2.Error.Error())
  3400. // Ignore whitespace since that's what were verifying doesn't change stuff
  3401. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3402. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
  3403. }
  3404. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  3405. result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3406. result2.Assert(c, icmd.Expected{
  3407. ExitCode: 1,
  3408. })
  3409. // Skip over the times
  3410. e1 = removeLogTimestamps(result1.Error.Error())
  3411. e2 = removeLogTimestamps(result2.Error.Error())
  3412. // Ignore whitespace since that's what were verifying doesn't change stuff
  3413. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3414. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
  3415. }
  3416. }
  3417. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  3418. // Test to make sure that spaces in quotes aren't lost
  3419. name := "testspacesquotes"
  3420. dockerfile := `FROM busybox
  3421. RUN echo " \
  3422. foo "`
  3423. expected := "\n foo \n"
  3424. // Windows uses the builtin echo, which preserves quotes
  3425. if testEnv.DaemonPlatform() == "windows" {
  3426. expected = "\" foo \""
  3427. }
  3428. buildImage(name, build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3429. Out: expected,
  3430. })
  3431. }
  3432. // #4393
  3433. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  3434. testRequires(c, DaemonIsLinux) // TODO Windows: This should error out
  3435. buildImage("docker-test-errcreatevolumewithfile", build.WithDockerfile(`
  3436. FROM busybox
  3437. RUN touch /foo
  3438. VOLUME /foo
  3439. `)).Assert(c, icmd.Expected{
  3440. ExitCode: 1,
  3441. Err: "file exists",
  3442. })
  3443. }
  3444. // FIXME(vdemeester) should be a unit test
  3445. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  3446. // Test to make sure that all Dockerfile commands (except the ones listed
  3447. // in skipCmds) will generate an error if no args are provided.
  3448. // Note: INSERT is deprecated so we exclude it because of that.
  3449. skipCmds := map[string]struct{}{
  3450. "CMD": {},
  3451. "RUN": {},
  3452. "ENTRYPOINT": {},
  3453. "INSERT": {},
  3454. }
  3455. if testEnv.DaemonPlatform() == "windows" {
  3456. skipCmds = map[string]struct{}{
  3457. "CMD": {},
  3458. "RUN": {},
  3459. "ENTRYPOINT": {},
  3460. "INSERT": {},
  3461. "STOPSIGNAL": {},
  3462. "ARG": {},
  3463. "USER": {},
  3464. "EXPOSE": {},
  3465. }
  3466. }
  3467. for cmd := range command.Commands {
  3468. cmd = strings.ToUpper(cmd)
  3469. if _, ok := skipCmds[cmd]; ok {
  3470. continue
  3471. }
  3472. var dockerfile string
  3473. if cmd == "FROM" {
  3474. dockerfile = cmd
  3475. } else {
  3476. // Add FROM to make sure we don't complain about it missing
  3477. dockerfile = "FROM busybox\n" + cmd
  3478. }
  3479. buildImage("args", build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3480. ExitCode: 1,
  3481. Err: cmd + " requires",
  3482. })
  3483. }
  3484. }
  3485. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  3486. testRequires(c, DaemonIsLinux)
  3487. buildImage("sc", build.WithDockerfile("FROM scratch")).Assert(c, icmd.Expected{
  3488. ExitCode: 1,
  3489. Err: "No image was generated",
  3490. })
  3491. }
  3492. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  3493. buildImageSuccessfully(c, "sc", build.WithBuildContext(c,
  3494. build.WithFile("Dockerfile", "FROM busybox\n"),
  3495. build.WithFile("..gitme", ""),
  3496. ))
  3497. }
  3498. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  3499. testRequires(c, DaemonIsLinux) // No hello-world Windows image
  3500. name := "testbuildrunonejson"
  3501. buildImage(name, build.WithDockerfile(`FROM hello-world:frozen
  3502. RUN [ "/hello" ]`)).Assert(c, icmd.Expected{
  3503. Out: "Hello from Docker",
  3504. })
  3505. }
  3506. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  3507. name := "testbuildemptystringvolume"
  3508. buildImage(name, build.WithDockerfile(`
  3509. FROM busybox
  3510. ENV foo=""
  3511. VOLUME $foo
  3512. `)).Assert(c, icmd.Expected{
  3513. ExitCode: 1,
  3514. })
  3515. }
  3516. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  3517. testRequires(c, SameHostDaemon, DaemonIsLinux)
  3518. cgroupParent := "test"
  3519. data, err := ioutil.ReadFile("/proc/self/cgroup")
  3520. if err != nil {
  3521. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  3522. }
  3523. selfCgroupPaths := testutil.ParseCgroupPaths(string(data))
  3524. _, found := selfCgroupPaths["memory"]
  3525. if !found {
  3526. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  3527. }
  3528. result := buildImage("buildcgroupparent",
  3529. cli.WithFlags("--cgroup-parent", cgroupParent),
  3530. build.WithDockerfile(`
  3531. FROM busybox
  3532. RUN cat /proc/self/cgroup
  3533. `))
  3534. result.Assert(c, icmd.Success)
  3535. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), result.Combined())
  3536. c.Assert(err, check.IsNil)
  3537. if !m {
  3538. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, result.Combined())
  3539. }
  3540. }
  3541. // FIXME(vdemeester) could be a unit test
  3542. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  3543. // Check to make sure our build output prints the Dockerfile cmd
  3544. // property - there was a bug that caused it to be duplicated on the
  3545. // Step X line
  3546. name := "testbuildnodupoutput"
  3547. result := buildImage(name, build.WithDockerfile(`
  3548. FROM busybox
  3549. RUN env`))
  3550. result.Assert(c, icmd.Success)
  3551. exp := "\nStep 2/2 : RUN env\n"
  3552. if !strings.Contains(result.Combined(), exp) {
  3553. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3554. }
  3555. }
  3556. // GH15826
  3557. // FIXME(vdemeester) could be a unit test
  3558. func (s *DockerSuite) TestBuildStartsFromOne(c *check.C) {
  3559. // Explicit check to ensure that build starts from step 1 rather than 0
  3560. name := "testbuildstartsfromone"
  3561. result := buildImage(name, build.WithDockerfile(`FROM busybox`))
  3562. result.Assert(c, icmd.Success)
  3563. exp := "\nStep 1/1 : FROM busybox\n"
  3564. if !strings.Contains(result.Combined(), exp) {
  3565. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3566. }
  3567. }
  3568. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  3569. // Test to make sure the bad command is quoted with just "s and
  3570. // not as a Go []string
  3571. name := "testbuildbadrunerrmsg"
  3572. shell := "/bin/sh -c"
  3573. exitCode := 127
  3574. if testEnv.DaemonPlatform() == "windows" {
  3575. shell = "cmd /S /C"
  3576. // architectural - Windows has to start the container to determine the exe is bad, Linux does not
  3577. exitCode = 1
  3578. }
  3579. exp := fmt.Sprintf(`The command '%s badEXE a1 \& a2 a3' returned a non-zero code: %d`, shell, exitCode)
  3580. buildImage(name, build.WithDockerfile(`
  3581. FROM busybox
  3582. RUN badEXE a1 \& a2 a3`)).Assert(c, icmd.Expected{
  3583. ExitCode: exitCode,
  3584. Err: exp,
  3585. })
  3586. }
  3587. func (s *DockerTrustSuite) TestTrustedBuild(c *check.C) {
  3588. repoName := s.setupTrustedImage(c, "trusted-build")
  3589. dockerFile := fmt.Sprintf(`
  3590. FROM %s
  3591. RUN []
  3592. `, repoName)
  3593. name := "testtrustedbuild"
  3594. buildImage(name, trustedBuild, build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  3595. Out: fmt.Sprintf("FROM %s@sha", repoName[:len(repoName)-7]),
  3596. })
  3597. // We should also have a tag reference for the image.
  3598. dockerCmd(c, "inspect", repoName)
  3599. // We should now be able to remove the tag reference.
  3600. dockerCmd(c, "rmi", repoName)
  3601. }
  3602. func (s *DockerTrustSuite) TestTrustedBuildUntrustedTag(c *check.C) {
  3603. repoName := fmt.Sprintf("%v/dockercli/build-untrusted-tag:latest", privateRegistryURL)
  3604. dockerFile := fmt.Sprintf(`
  3605. FROM %s
  3606. RUN []
  3607. `, repoName)
  3608. name := "testtrustedbuilduntrustedtag"
  3609. buildImage(name, trustedBuild, build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  3610. ExitCode: 1,
  3611. Err: "does not have trust data for",
  3612. })
  3613. }
  3614. func (s *DockerTrustSuite) TestBuildContextDirIsSymlink(c *check.C) {
  3615. testRequires(c, DaemonIsLinux)
  3616. tempDir, err := ioutil.TempDir("", "test-build-dir-is-symlink-")
  3617. c.Assert(err, check.IsNil)
  3618. defer os.RemoveAll(tempDir)
  3619. // Make a real context directory in this temp directory with a simple
  3620. // Dockerfile.
  3621. realContextDirname := filepath.Join(tempDir, "context")
  3622. if err := os.Mkdir(realContextDirname, os.FileMode(0755)); err != nil {
  3623. c.Fatal(err)
  3624. }
  3625. if err = ioutil.WriteFile(
  3626. filepath.Join(realContextDirname, "Dockerfile"),
  3627. []byte(`
  3628. FROM busybox
  3629. RUN echo hello world
  3630. `),
  3631. os.FileMode(0644),
  3632. ); err != nil {
  3633. c.Fatal(err)
  3634. }
  3635. // Make a symlink to the real context directory.
  3636. contextSymlinkName := filepath.Join(tempDir, "context_link")
  3637. if err := os.Symlink(realContextDirname, contextSymlinkName); err != nil {
  3638. c.Fatal(err)
  3639. }
  3640. // Executing the build with the symlink as the specified context should
  3641. // *not* fail.
  3642. dockerCmd(c, "build", contextSymlinkName)
  3643. }
  3644. func (s *DockerTrustSuite) TestTrustedBuildTagFromReleasesRole(c *check.C) {
  3645. testRequires(c, NotaryHosting)
  3646. latestTag := s.setupTrustedImage(c, "trusted-build-releases-role")
  3647. repoName := strings.TrimSuffix(latestTag, ":latest")
  3648. // Now create the releases role
  3649. s.notaryCreateDelegation(c, repoName, "targets/releases", s.not.keys[0].Public)
  3650. s.notaryImportKey(c, repoName, "targets/releases", s.not.keys[0].Private)
  3651. s.notaryPublish(c, repoName)
  3652. // push a different tag to the releases role
  3653. otherTag := fmt.Sprintf("%s:other", repoName)
  3654. cli.DockerCmd(c, "tag", "busybox", otherTag)
  3655. cli.Docker(cli.Args("push", otherTag), trustedCmd).Assert(c, icmd.Success)
  3656. s.assertTargetInRoles(c, repoName, "other", "targets/releases")
  3657. s.assertTargetNotInRoles(c, repoName, "other", "targets")
  3658. cli.DockerCmd(c, "rmi", otherTag)
  3659. dockerFile := fmt.Sprintf(`
  3660. FROM %s
  3661. RUN []
  3662. `, otherTag)
  3663. name := "testtrustedbuildreleasesrole"
  3664. cli.BuildCmd(c, name, trustedCmd, build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  3665. Out: fmt.Sprintf("FROM %s@sha", repoName),
  3666. })
  3667. }
  3668. func (s *DockerTrustSuite) TestTrustedBuildTagIgnoresOtherDelegationRoles(c *check.C) {
  3669. testRequires(c, NotaryHosting)
  3670. latestTag := s.setupTrustedImage(c, "trusted-build-releases-role")
  3671. repoName := strings.TrimSuffix(latestTag, ":latest")
  3672. // Now create a non-releases delegation role
  3673. s.notaryCreateDelegation(c, repoName, "targets/other", s.not.keys[0].Public)
  3674. s.notaryImportKey(c, repoName, "targets/other", s.not.keys[0].Private)
  3675. s.notaryPublish(c, repoName)
  3676. // push a different tag to the other role
  3677. otherTag := fmt.Sprintf("%s:other", repoName)
  3678. cli.DockerCmd(c, "tag", "busybox", otherTag)
  3679. cli.Docker(cli.Args("push", otherTag), trustedCmd).Assert(c, icmd.Success)
  3680. s.assertTargetInRoles(c, repoName, "other", "targets/other")
  3681. s.assertTargetNotInRoles(c, repoName, "other", "targets")
  3682. cli.DockerCmd(c, "rmi", otherTag)
  3683. dockerFile := fmt.Sprintf(`
  3684. FROM %s
  3685. RUN []
  3686. `, otherTag)
  3687. name := "testtrustedbuildotherrole"
  3688. cli.Docker(cli.Build(name), trustedCmd, build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  3689. ExitCode: 1,
  3690. })
  3691. }
  3692. // Issue #15634: COPY fails when path starts with "null"
  3693. func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *check.C) {
  3694. name := "testbuildnullstringinaddcopyvolume"
  3695. volName := "nullvolume"
  3696. if testEnv.DaemonPlatform() == "windows" {
  3697. volName = `C:\\nullvolume`
  3698. }
  3699. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3700. build.WithFile("Dockerfile", `
  3701. FROM busybox
  3702. ADD null /
  3703. COPY nullfile /
  3704. VOLUME `+volName+`
  3705. `),
  3706. build.WithFile("null", "test1"),
  3707. build.WithFile("nullfile", "test2"),
  3708. ))
  3709. }
  3710. func (s *DockerSuite) TestBuildStopSignal(c *check.C) {
  3711. testRequires(c, DaemonIsLinux) // Windows does not support STOPSIGNAL yet
  3712. imgName := "test_build_stop_signal"
  3713. buildImageSuccessfully(c, imgName, build.WithDockerfile(`FROM busybox
  3714. STOPSIGNAL SIGKILL`))
  3715. res := inspectFieldJSON(c, imgName, "Config.StopSignal")
  3716. if res != `"SIGKILL"` {
  3717. c.Fatalf("Signal %s, expected SIGKILL", res)
  3718. }
  3719. containerName := "test-container-stop-signal"
  3720. dockerCmd(c, "run", "-d", "--name", containerName, imgName, "top")
  3721. res = inspectFieldJSON(c, containerName, "Config.StopSignal")
  3722. if res != `"SIGKILL"` {
  3723. c.Fatalf("Signal %s, expected SIGKILL", res)
  3724. }
  3725. }
  3726. func (s *DockerSuite) TestBuildBuildTimeArg(c *check.C) {
  3727. imgName := "bldargtest"
  3728. envKey := "foo"
  3729. envVal := "bar"
  3730. var dockerfile string
  3731. if testEnv.DaemonPlatform() == "windows" {
  3732. // Bugs in Windows busybox port - use the default base image and native cmd stuff
  3733. dockerfile = fmt.Sprintf(`FROM `+minimalBaseImage()+`
  3734. ARG %s
  3735. RUN echo %%%s%%
  3736. CMD setlocal enableextensions && if defined %s (echo %%%s%%)`, envKey, envKey, envKey, envKey)
  3737. } else {
  3738. dockerfile = fmt.Sprintf(`FROM busybox
  3739. ARG %s
  3740. RUN echo $%s
  3741. CMD echo $%s`, envKey, envKey, envKey)
  3742. }
  3743. buildImage(imgName,
  3744. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3745. build.WithDockerfile(dockerfile),
  3746. ).Assert(c, icmd.Expected{
  3747. Out: envVal,
  3748. })
  3749. containerName := "bldargCont"
  3750. out, _ := dockerCmd(c, "run", "--name", containerName, imgName)
  3751. out = strings.Trim(out, " \r\n'")
  3752. if out != "" {
  3753. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3754. }
  3755. }
  3756. func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *check.C) {
  3757. imgName := "bldargtest"
  3758. envKey := "foo"
  3759. envVal := "bar"
  3760. envDef := "bar1"
  3761. dockerfile := fmt.Sprintf(`FROM busybox
  3762. ARG %s=%s`, envKey, envDef)
  3763. buildImage(imgName,
  3764. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3765. build.WithDockerfile(dockerfile),
  3766. ).Assert(c, icmd.Expected{
  3767. Out: envVal,
  3768. })
  3769. out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
  3770. outputTabs := strings.Split(out, "\n")[1]
  3771. if !strings.Contains(outputTabs, envDef) {
  3772. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  3773. }
  3774. }
  3775. func (s *DockerSuite) TestBuildTimeArgHistoryExclusions(c *check.C) {
  3776. imgName := "bldargtest"
  3777. envKey := "foo"
  3778. envVal := "bar"
  3779. proxy := "HTTP_PROXY=http://user:password@proxy.example.com"
  3780. explicitProxyKey := "http_proxy"
  3781. explicitProxyVal := "http://user:password@someproxy.example.com"
  3782. dockerfile := fmt.Sprintf(`FROM busybox
  3783. ARG %s
  3784. ARG %s
  3785. RUN echo "Testing Build Args!"`, envKey, explicitProxyKey)
  3786. buildImage := func(imgName string) string {
  3787. cli.BuildCmd(c, imgName,
  3788. cli.WithFlags("--build-arg", "https_proxy=https://proxy.example.com",
  3789. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3790. "--build-arg", fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal),
  3791. "--build-arg", proxy),
  3792. build.WithDockerfile(dockerfile),
  3793. )
  3794. return getIDByName(c, imgName)
  3795. }
  3796. origID := buildImage(imgName)
  3797. result := cli.DockerCmd(c, "history", "--no-trunc", imgName)
  3798. out := result.Stdout()
  3799. if strings.Contains(out, proxy) {
  3800. c.Fatalf("failed to exclude proxy settings from history!")
  3801. }
  3802. if strings.Contains(out, "https_proxy") {
  3803. c.Fatalf("failed to exclude proxy settings from history!")
  3804. }
  3805. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", envKey, envVal)})
  3806. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal)})
  3807. cacheID := buildImage(imgName + "-two")
  3808. c.Assert(origID, checker.Equals, cacheID)
  3809. }
  3810. func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) {
  3811. imgName := "bldargtest"
  3812. envKey := "foo"
  3813. envVal := "bar"
  3814. dockerfile := fmt.Sprintf(`FROM busybox
  3815. ARG %s
  3816. RUN echo $%s`, envKey, envKey)
  3817. buildImageSuccessfully(c, imgName,
  3818. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3819. build.WithDockerfile(dockerfile),
  3820. )
  3821. origImgID := getIDByName(c, imgName)
  3822. imgNameCache := "bldargtestcachehit"
  3823. buildImageSuccessfully(c, imgNameCache,
  3824. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3825. build.WithDockerfile(dockerfile),
  3826. )
  3827. newImgID := getIDByName(c, imgName)
  3828. if newImgID != origImgID {
  3829. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  3830. }
  3831. }
  3832. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *check.C) {
  3833. imgName := "bldargtest"
  3834. envKey := "foo"
  3835. envVal := "bar"
  3836. extraEnvKey := "foo1"
  3837. extraEnvVal := "bar1"
  3838. dockerfile := fmt.Sprintf(`FROM busybox
  3839. ARG %s
  3840. ARG %s
  3841. RUN echo $%s`, envKey, extraEnvKey, envKey)
  3842. buildImageSuccessfully(c, imgName,
  3843. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3844. build.WithDockerfile(dockerfile),
  3845. )
  3846. origImgID := getIDByName(c, imgName)
  3847. imgNameCache := "bldargtestcachemiss"
  3848. buildImageSuccessfully(c, imgNameCache,
  3849. cli.WithFlags(
  3850. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3851. "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal),
  3852. ),
  3853. build.WithDockerfile(dockerfile),
  3854. )
  3855. newImgID := getIDByName(c, imgNameCache)
  3856. if newImgID == origImgID {
  3857. c.Fatalf("build used cache, expected a miss!")
  3858. }
  3859. }
  3860. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *check.C) {
  3861. imgName := "bldargtest"
  3862. envKey := "foo"
  3863. envVal := "bar"
  3864. newEnvVal := "bar1"
  3865. dockerfile := fmt.Sprintf(`FROM busybox
  3866. ARG %s
  3867. RUN echo $%s`, envKey, envKey)
  3868. buildImageSuccessfully(c, imgName,
  3869. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3870. build.WithDockerfile(dockerfile),
  3871. )
  3872. origImgID := getIDByName(c, imgName)
  3873. imgNameCache := "bldargtestcachemiss"
  3874. buildImageSuccessfully(c, imgNameCache,
  3875. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal)),
  3876. build.WithDockerfile(dockerfile),
  3877. )
  3878. newImgID := getIDByName(c, imgNameCache)
  3879. if newImgID == origImgID {
  3880. c.Fatalf("build used cache, expected a miss!")
  3881. }
  3882. }
  3883. func (s *DockerSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *check.C) {
  3884. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3885. imgName := "bldargtest"
  3886. envKey := "foo"
  3887. envVal := "bar"
  3888. envValOveride := "barOverride"
  3889. dockerfile := fmt.Sprintf(`FROM busybox
  3890. ARG %s
  3891. ENV %s %s
  3892. RUN echo $%s
  3893. CMD echo $%s
  3894. `, envKey, envKey, envValOveride, envKey, envKey)
  3895. result := buildImage(imgName,
  3896. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3897. build.WithDockerfile(dockerfile),
  3898. )
  3899. result.Assert(c, icmd.Success)
  3900. if strings.Count(result.Combined(), envValOveride) != 2 {
  3901. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOveride)
  3902. }
  3903. containerName := "bldargCont"
  3904. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  3905. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  3906. }
  3907. }
  3908. // FIXME(vdemeester) might be useful to merge with the one above ?
  3909. func (s *DockerSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *check.C) {
  3910. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3911. imgName := "bldargtest"
  3912. envKey := "foo"
  3913. envVal := "bar"
  3914. envValOveride := "barOverride"
  3915. dockerfile := fmt.Sprintf(`FROM busybox
  3916. ENV %s %s
  3917. ARG %s
  3918. RUN echo $%s
  3919. CMD echo $%s
  3920. `, envKey, envValOveride, envKey, envKey, envKey)
  3921. result := buildImage(imgName,
  3922. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3923. build.WithDockerfile(dockerfile),
  3924. )
  3925. result.Assert(c, icmd.Success)
  3926. if strings.Count(result.Combined(), envValOveride) != 2 {
  3927. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOveride)
  3928. }
  3929. containerName := "bldargCont"
  3930. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  3931. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  3932. }
  3933. }
  3934. func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *check.C) {
  3935. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3936. imgName := "bldvarstest"
  3937. wdVar := "WDIR"
  3938. wdVal := "/tmp/"
  3939. addVar := "AFILE"
  3940. addVal := "addFile"
  3941. copyVar := "CFILE"
  3942. copyVal := "copyFile"
  3943. envVar := "foo"
  3944. envVal := "bar"
  3945. exposeVar := "EPORT"
  3946. exposeVal := "9999"
  3947. userVar := "USER"
  3948. userVal := "testUser"
  3949. volVar := "VOL"
  3950. volVal := "/testVol/"
  3951. buildImageSuccessfully(c, imgName,
  3952. cli.WithFlags(
  3953. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  3954. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  3955. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  3956. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  3957. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  3958. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  3959. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  3960. ),
  3961. build.WithBuildContext(c,
  3962. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  3963. ARG %s
  3964. WORKDIR ${%s}
  3965. ARG %s
  3966. ADD ${%s} testDir/
  3967. ARG %s
  3968. COPY $%s testDir/
  3969. ARG %s
  3970. ENV %s=${%s}
  3971. ARG %s
  3972. EXPOSE $%s
  3973. ARG %s
  3974. USER $%s
  3975. ARG %s
  3976. VOLUME ${%s}`,
  3977. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  3978. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar)),
  3979. build.WithFile(addVal, "some stuff"),
  3980. build.WithFile(copyVal, "some stuff"),
  3981. ),
  3982. )
  3983. res := inspectField(c, imgName, "Config.WorkingDir")
  3984. c.Check(res, check.Equals, filepath.ToSlash(wdVal))
  3985. var resArr []string
  3986. inspectFieldAndUnmarshall(c, imgName, "Config.Env", &resArr)
  3987. found := false
  3988. for _, v := range resArr {
  3989. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  3990. found = true
  3991. break
  3992. }
  3993. }
  3994. if !found {
  3995. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  3996. envVar, envVal, resArr)
  3997. }
  3998. var resMap map[string]interface{}
  3999. inspectFieldAndUnmarshall(c, imgName, "Config.ExposedPorts", &resMap)
  4000. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  4001. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  4002. }
  4003. res = inspectField(c, imgName, "Config.User")
  4004. if res != userVal {
  4005. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  4006. }
  4007. inspectFieldAndUnmarshall(c, imgName, "Config.Volumes", &resMap)
  4008. if _, ok := resMap[volVal]; !ok {
  4009. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  4010. }
  4011. }
  4012. func (s *DockerSuite) TestBuildBuildTimeArgExpansionOverride(c *check.C) {
  4013. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4014. imgName := "bldvarstest"
  4015. envKey := "foo"
  4016. envVal := "bar"
  4017. envKey1 := "foo1"
  4018. envValOveride := "barOverride"
  4019. dockerfile := fmt.Sprintf(`FROM busybox
  4020. ARG %s
  4021. ENV %s %s
  4022. ENV %s ${%s}
  4023. RUN echo $%s
  4024. CMD echo $%s`, envKey, envKey, envValOveride, envKey1, envKey, envKey1, envKey1)
  4025. result := buildImage(imgName,
  4026. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  4027. build.WithDockerfile(dockerfile),
  4028. )
  4029. result.Assert(c, icmd.Success)
  4030. if strings.Count(result.Combined(), envValOveride) != 2 {
  4031. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOveride)
  4032. }
  4033. containerName := "bldargCont"
  4034. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  4035. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  4036. }
  4037. }
  4038. func (s *DockerSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *check.C) {
  4039. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4040. imgName := "bldargtest"
  4041. envKey := "foo"
  4042. envVal := "bar"
  4043. dockerfile := fmt.Sprintf(`FROM busybox
  4044. RUN echo $%s
  4045. ARG %s
  4046. CMD echo $%s`, envKey, envKey, envKey)
  4047. result := buildImage(imgName,
  4048. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  4049. build.WithDockerfile(dockerfile),
  4050. )
  4051. result.Assert(c, icmd.Success)
  4052. if strings.Contains(result.Combined(), envVal) {
  4053. c.Fatalf("able to access environment variable in output: %q expected to be missing", result.Combined())
  4054. }
  4055. containerName := "bldargCont"
  4056. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  4057. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  4058. }
  4059. }
  4060. func (s *DockerSuite) TestBuildBuildTimeArgBuiltinArg(c *check.C) {
  4061. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  4062. imgName := "bldargtest"
  4063. envKey := "HTTP_PROXY"
  4064. envVal := "bar"
  4065. dockerfile := fmt.Sprintf(`FROM busybox
  4066. RUN echo $%s
  4067. CMD echo $%s`, envKey, envKey)
  4068. result := buildImage(imgName,
  4069. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  4070. build.WithDockerfile(dockerfile),
  4071. )
  4072. result.Assert(c, icmd.Success)
  4073. if !strings.Contains(result.Combined(), envVal) {
  4074. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envVal)
  4075. }
  4076. containerName := "bldargCont"
  4077. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  4078. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  4079. }
  4080. }
  4081. func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *check.C) {
  4082. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4083. imgName := "bldargtest"
  4084. envKey := "foo"
  4085. envVal := "bar"
  4086. envValOveride := "barOverride"
  4087. dockerfile := fmt.Sprintf(`FROM busybox
  4088. ARG %s=%s
  4089. ENV %s $%s
  4090. RUN echo $%s
  4091. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  4092. result := buildImage(imgName,
  4093. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envValOveride)),
  4094. build.WithDockerfile(dockerfile),
  4095. )
  4096. result.Assert(c, icmd.Success)
  4097. if strings.Count(result.Combined(), envValOveride) != 1 {
  4098. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOveride)
  4099. }
  4100. containerName := "bldargCont"
  4101. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  4102. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  4103. }
  4104. }
  4105. func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *check.C) {
  4106. imgName := "bldargtest"
  4107. envKey := "foo"
  4108. envVal := "bar"
  4109. dockerfile := fmt.Sprintf(`FROM busybox
  4110. RUN echo $%s
  4111. CMD echo $%s`, envKey, envKey)
  4112. warnStr := "[Warning] One or more build-args"
  4113. buildImage(imgName,
  4114. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  4115. build.WithDockerfile(dockerfile),
  4116. ).Assert(c, icmd.Expected{
  4117. Out: warnStr,
  4118. })
  4119. }
  4120. func (s *DockerSuite) TestBuildBuildTimeArgEnv(c *check.C) {
  4121. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4122. dockerfile := `FROM busybox
  4123. ARG FOO1=fromfile
  4124. ARG FOO2=fromfile
  4125. ARG FOO3=fromfile
  4126. ARG FOO4=fromfile
  4127. ARG FOO5
  4128. ARG FOO6
  4129. ARG FO10
  4130. RUN env
  4131. RUN [ "$FOO1" == "fromcmd" ]
  4132. RUN [ "$FOO2" == "" ]
  4133. RUN [ "$FOO3" == "fromenv" ]
  4134. RUN [ "$FOO4" == "fromfile" ]
  4135. RUN [ "$FOO5" == "fromcmd" ]
  4136. # The following should not exist at all in the env
  4137. RUN [ "$(env | grep FOO6)" == "" ]
  4138. RUN [ "$(env | grep FOO7)" == "" ]
  4139. RUN [ "$(env | grep FOO8)" == "" ]
  4140. RUN [ "$(env | grep FOO9)" == "" ]
  4141. RUN [ "$FO10" == "" ]
  4142. `
  4143. result := buildImage("testbuildtimeargenv",
  4144. cli.WithFlags(
  4145. "--build-arg", fmt.Sprintf("FOO1=fromcmd"),
  4146. "--build-arg", fmt.Sprintf("FOO2="),
  4147. "--build-arg", fmt.Sprintf("FOO3"), // set in env
  4148. "--build-arg", fmt.Sprintf("FOO4"), // not set in env
  4149. "--build-arg", fmt.Sprintf("FOO5=fromcmd"),
  4150. // FOO6 is not set at all
  4151. "--build-arg", fmt.Sprintf("FOO7=fromcmd"), // should produce a warning
  4152. "--build-arg", fmt.Sprintf("FOO8="), // should produce a warning
  4153. "--build-arg", fmt.Sprintf("FOO9"), // should produce a warning
  4154. "--build-arg", fmt.Sprintf("FO10"), // not set in env, empty value
  4155. ),
  4156. cli.WithEnvironmentVariables(append(os.Environ(),
  4157. "FOO1=fromenv",
  4158. "FOO2=fromenv",
  4159. "FOO3=fromenv")...),
  4160. build.WithBuildContext(c,
  4161. build.WithFile("Dockerfile", dockerfile),
  4162. ),
  4163. )
  4164. result.Assert(c, icmd.Success)
  4165. // Now check to make sure we got a warning msg about unused build-args
  4166. i := strings.Index(result.Combined(), "[Warning]")
  4167. if i < 0 {
  4168. c.Fatalf("Missing the build-arg warning in %q", result.Combined())
  4169. }
  4170. out := result.Combined()[i:] // "out" should contain just the warning message now
  4171. // These were specified on a --build-arg but no ARG was in the Dockerfile
  4172. c.Assert(out, checker.Contains, "FOO7")
  4173. c.Assert(out, checker.Contains, "FOO8")
  4174. c.Assert(out, checker.Contains, "FOO9")
  4175. }
  4176. func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *check.C) {
  4177. imgName := "bldargtest"
  4178. envKey := "foo"
  4179. envKey1 := "foo1"
  4180. envKey2 := "foo2"
  4181. envKey3 := "foo3"
  4182. dockerfile := fmt.Sprintf(`FROM busybox
  4183. ARG %s=""
  4184. ARG %s=''
  4185. ARG %s="''"
  4186. ARG %s='""'
  4187. RUN [ "$%s" != "$%s" ]
  4188. RUN [ "$%s" != "$%s" ]
  4189. RUN [ "$%s" != "$%s" ]
  4190. RUN [ "$%s" != "$%s" ]
  4191. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  4192. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  4193. envKey2, envKey3)
  4194. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4195. }
  4196. func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *check.C) {
  4197. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4198. imgName := "bldargtest"
  4199. envKey := "foo"
  4200. envKey1 := "foo1"
  4201. envKey2 := "foo2"
  4202. dockerfile := fmt.Sprintf(`FROM busybox
  4203. ARG %s=
  4204. ARG %s=""
  4205. ARG %s=''
  4206. RUN [ "$%s" == "$%s" ]
  4207. RUN [ "$%s" == "$%s" ]
  4208. RUN [ "$%s" == "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  4209. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4210. }
  4211. func (s *DockerSuite) TestBuildBuildTimeArgDefintionWithNoEnvInjection(c *check.C) {
  4212. imgName := "bldargtest"
  4213. envKey := "foo"
  4214. dockerfile := fmt.Sprintf(`FROM busybox
  4215. ARG %s
  4216. RUN env`, envKey)
  4217. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4218. result.Assert(c, icmd.Success)
  4219. if strings.Count(result.Combined(), envKey) != 1 {
  4220. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", result.Combined())
  4221. }
  4222. }
  4223. func (s *DockerSuite) TestBuildBuildTimeArgMultipleFrom(c *check.C) {
  4224. imgName := "multifrombldargtest"
  4225. dockerfile := `FROM busybox
  4226. ARG foo=abc
  4227. LABEL multifromtest=1
  4228. RUN env > /out
  4229. FROM busybox
  4230. ARG bar=def
  4231. RUN env > /out`
  4232. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4233. result.Assert(c, icmd.Success)
  4234. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4235. parentID := strings.TrimSpace(result.Stdout())
  4236. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4237. c.Assert(result.Stdout(), checker.Contains, "foo=abc")
  4238. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4239. c.Assert(result.Stdout(), checker.Not(checker.Contains), "foo")
  4240. c.Assert(result.Stdout(), checker.Contains, "bar=def")
  4241. }
  4242. func (s *DockerSuite) TestBuildBuildTimeFromArgMultipleFrom(c *check.C) {
  4243. imgName := "multifrombldargtest"
  4244. dockerfile := `ARG tag=nosuchtag
  4245. FROM busybox:${tag}
  4246. LABEL multifromtest=1
  4247. RUN env > /out
  4248. FROM busybox:${tag}
  4249. ARG tag
  4250. RUN env > /out`
  4251. result := cli.BuildCmd(c, imgName,
  4252. build.WithDockerfile(dockerfile),
  4253. cli.WithFlags("--build-arg", fmt.Sprintf("tag=latest")))
  4254. result.Assert(c, icmd.Success)
  4255. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4256. parentID := strings.TrimSpace(result.Stdout())
  4257. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4258. c.Assert(result.Stdout(), checker.Not(checker.Contains), "tag")
  4259. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4260. c.Assert(result.Stdout(), checker.Contains, "tag=latest")
  4261. }
  4262. func (s *DockerSuite) TestBuildBuildTimeUnusedArgMultipleFrom(c *check.C) {
  4263. imgName := "multifromunusedarg"
  4264. dockerfile := `FROM busybox
  4265. ARG foo
  4266. FROM busybox
  4267. ARG bar
  4268. RUN env > /out`
  4269. result := cli.BuildCmd(c, imgName,
  4270. build.WithDockerfile(dockerfile),
  4271. cli.WithFlags("--build-arg", fmt.Sprintf("baz=abc")))
  4272. result.Assert(c, icmd.Success)
  4273. c.Assert(result.Combined(), checker.Contains, "[Warning]")
  4274. c.Assert(result.Combined(), checker.Contains, "[baz] were not consumed")
  4275. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4276. c.Assert(result.Stdout(), checker.Not(checker.Contains), "bar")
  4277. c.Assert(result.Stdout(), checker.Not(checker.Contains), "baz")
  4278. }
  4279. func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) {
  4280. volName := "testname:/foo"
  4281. if testEnv.DaemonPlatform() == "windows" {
  4282. volName = "testname:C:\\foo"
  4283. }
  4284. dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops")
  4285. dockerFile := `FROM busybox
  4286. VOLUME ` + volName + `
  4287. RUN ls /foo/oops
  4288. `
  4289. buildImage("test", build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  4290. ExitCode: 1,
  4291. })
  4292. }
  4293. func (s *DockerSuite) TestBuildTagEvent(c *check.C) {
  4294. since := daemonUnixTime(c)
  4295. dockerFile := `FROM busybox
  4296. RUN echo events
  4297. `
  4298. buildImageSuccessfully(c, "test", build.WithDockerfile(dockerFile))
  4299. until := daemonUnixTime(c)
  4300. out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image")
  4301. events := strings.Split(strings.TrimSpace(out), "\n")
  4302. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  4303. var foundTag bool
  4304. for _, a := range actions {
  4305. if a == "tag" {
  4306. foundTag = true
  4307. break
  4308. }
  4309. }
  4310. c.Assert(foundTag, checker.True, check.Commentf("No tag event found:\n%s", out))
  4311. }
  4312. // #15780
  4313. func (s *DockerSuite) TestBuildMultipleTags(c *check.C) {
  4314. dockerfile := `
  4315. FROM busybox
  4316. MAINTAINER test-15780
  4317. `
  4318. buildImageSuccessfully(c, "tag1", cli.WithFlags("-t", "tag2:v2", "-t", "tag1:latest", "-t", "tag1"), build.WithDockerfile(dockerfile))
  4319. id1 := getIDByName(c, "tag1")
  4320. id2 := getIDByName(c, "tag2:v2")
  4321. c.Assert(id1, check.Equals, id2)
  4322. }
  4323. // #17290
  4324. func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) {
  4325. name := "testbuildbrokensymlink"
  4326. ctx := fakecontext.New(c, "",
  4327. fakecontext.WithDockerfile(`
  4328. FROM busybox
  4329. COPY . ./`),
  4330. fakecontext.WithFiles(map[string]string{
  4331. "foo": "bar",
  4332. }))
  4333. defer ctx.Close()
  4334. err := os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  4335. c.Assert(err, checker.IsNil)
  4336. // warm up cache
  4337. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4338. // add new file to context, should invalidate cache
  4339. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644)
  4340. c.Assert(err, checker.IsNil)
  4341. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4342. if strings.Contains(result.Combined(), "Using cache") {
  4343. c.Fatal("2nd build used cache on ADD, it shouldn't")
  4344. }
  4345. }
  4346. func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) {
  4347. name := "testbuildbrokensymlink"
  4348. ctx := fakecontext.New(c, "",
  4349. fakecontext.WithDockerfile(`
  4350. FROM busybox
  4351. COPY asymlink target`),
  4352. fakecontext.WithFiles(map[string]string{
  4353. "foo": "bar",
  4354. }))
  4355. defer ctx.Close()
  4356. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4357. c.Assert(err, checker.IsNil)
  4358. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4359. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4360. c.Assert(out, checker.Matches, "bar")
  4361. // change target file should invalidate cache
  4362. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4363. c.Assert(err, checker.IsNil)
  4364. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4365. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4366. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4367. c.Assert(out, checker.Matches, "baz")
  4368. }
  4369. func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) {
  4370. name := "testbuildbrokensymlink"
  4371. ctx := fakecontext.New(c, "",
  4372. fakecontext.WithDockerfile(`
  4373. FROM busybox
  4374. COPY asymlink /`),
  4375. fakecontext.WithFiles(map[string]string{
  4376. "foo/abc": "bar",
  4377. "foo/def": "baz",
  4378. }))
  4379. defer ctx.Close()
  4380. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4381. c.Assert(err, checker.IsNil)
  4382. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4383. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4384. c.Assert(out, checker.Matches, "barbaz")
  4385. // change target file should invalidate cache
  4386. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644)
  4387. c.Assert(err, checker.IsNil)
  4388. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4389. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4390. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4391. c.Assert(out, checker.Matches, "barbax")
  4392. }
  4393. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  4394. // not from the target file.
  4395. func (s *DockerSuite) TestBuildSymlinkBasename(c *check.C) {
  4396. name := "testbuildbrokensymlink"
  4397. ctx := fakecontext.New(c, "",
  4398. fakecontext.WithDockerfile(`
  4399. FROM busybox
  4400. COPY asymlink /`),
  4401. fakecontext.WithFiles(map[string]string{
  4402. "foo": "bar",
  4403. }))
  4404. defer ctx.Close()
  4405. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4406. c.Assert(err, checker.IsNil)
  4407. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4408. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "asymlink").Combined()
  4409. c.Assert(out, checker.Matches, "bar")
  4410. }
  4411. // #17827
  4412. func (s *DockerSuite) TestBuildCacheRootSource(c *check.C) {
  4413. name := "testbuildrootsource"
  4414. ctx := fakecontext.New(c, "",
  4415. fakecontext.WithDockerfile(`
  4416. FROM busybox
  4417. COPY / /data`),
  4418. fakecontext.WithFiles(map[string]string{
  4419. "foo": "bar",
  4420. }))
  4421. defer ctx.Close()
  4422. // warm up cache
  4423. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4424. // change file, should invalidate cache
  4425. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4426. c.Assert(err, checker.IsNil)
  4427. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4428. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4429. }
  4430. // #19375
  4431. func (s *DockerSuite) TestBuildFailsGitNotCallable(c *check.C) {
  4432. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4433. build.WithContextPath("github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4434. ExitCode: 1,
  4435. Err: "unable to prepare context: unable to find 'git': ",
  4436. })
  4437. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4438. build.WithContextPath("https://github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4439. ExitCode: 1,
  4440. Err: "unable to prepare context: unable to find 'git': ",
  4441. })
  4442. }
  4443. // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir
  4444. func (s *DockerSuite) TestBuildWorkdirWindowsPath(c *check.C) {
  4445. testRequires(c, DaemonIsWindows)
  4446. name := "testbuildworkdirwindowspath"
  4447. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4448. FROM `+testEnv.MinimalBaseImage()+`
  4449. RUN mkdir C:\\work
  4450. WORKDIR C:\\work
  4451. RUN if "%CD%" NEQ "C:\work" exit -1
  4452. `))
  4453. }
  4454. func (s *DockerSuite) TestBuildLabel(c *check.C) {
  4455. name := "testbuildlabel"
  4456. testLabel := "foo"
  4457. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4458. build.WithDockerfile(`
  4459. FROM `+minimalBaseImage()+`
  4460. LABEL default foo
  4461. `))
  4462. var labels map[string]string
  4463. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4464. if _, ok := labels[testLabel]; !ok {
  4465. c.Fatal("label not found in image")
  4466. }
  4467. }
  4468. func (s *DockerSuite) TestBuildLabelOneNode(c *check.C) {
  4469. name := "testbuildlabel"
  4470. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=bar"),
  4471. build.WithDockerfile("FROM busybox"))
  4472. var labels map[string]string
  4473. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4474. v, ok := labels["foo"]
  4475. if !ok {
  4476. c.Fatal("label `foo` not found in image")
  4477. }
  4478. c.Assert(v, checker.Equals, "bar")
  4479. }
  4480. func (s *DockerSuite) TestBuildLabelCacheCommit(c *check.C) {
  4481. name := "testbuildlabelcachecommit"
  4482. testLabel := "foo"
  4483. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4484. FROM `+minimalBaseImage()+`
  4485. LABEL default foo
  4486. `))
  4487. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4488. build.WithDockerfile(`
  4489. FROM `+minimalBaseImage()+`
  4490. LABEL default foo
  4491. `))
  4492. var labels map[string]string
  4493. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4494. if _, ok := labels[testLabel]; !ok {
  4495. c.Fatal("label not found in image")
  4496. }
  4497. }
  4498. func (s *DockerSuite) TestBuildLabelMultiple(c *check.C) {
  4499. name := "testbuildlabelmultiple"
  4500. testLabels := map[string]string{
  4501. "foo": "bar",
  4502. "123": "456",
  4503. }
  4504. labelArgs := []string{}
  4505. for k, v := range testLabels {
  4506. labelArgs = append(labelArgs, "--label", k+"="+v)
  4507. }
  4508. buildImageSuccessfully(c, name, cli.WithFlags(labelArgs...),
  4509. build.WithDockerfile(`
  4510. FROM `+minimalBaseImage()+`
  4511. LABEL default foo
  4512. `))
  4513. var labels map[string]string
  4514. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4515. for k, v := range testLabels {
  4516. if x, ok := labels[k]; !ok || x != v {
  4517. c.Fatalf("label %s=%s not found in image", k, v)
  4518. }
  4519. }
  4520. }
  4521. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *check.C) {
  4522. dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4523. baseImage := privateRegistryURL + "/baseimage"
  4524. buildImageSuccessfully(c, baseImage, build.WithDockerfile(`
  4525. FROM busybox
  4526. ENV env1 val1
  4527. `))
  4528. dockerCmd(c, "push", baseImage)
  4529. dockerCmd(c, "rmi", baseImage)
  4530. buildImageSuccessfully(c, baseImage, build.WithDockerfile(fmt.Sprintf(`
  4531. FROM %s
  4532. ENV env2 val2
  4533. `, baseImage)))
  4534. }
  4535. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *check.C) {
  4536. osPath := os.Getenv("PATH")
  4537. defer os.Setenv("PATH", osPath)
  4538. workingDir, err := os.Getwd()
  4539. c.Assert(err, checker.IsNil)
  4540. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  4541. c.Assert(err, checker.IsNil)
  4542. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  4543. os.Setenv("PATH", testPath)
  4544. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  4545. tmp, err := ioutil.TempDir("", "integration-cli-")
  4546. c.Assert(err, checker.IsNil)
  4547. externalAuthConfig := `{ "credsStore": "shell-test" }`
  4548. configPath := filepath.Join(tmp, "config.json")
  4549. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  4550. c.Assert(err, checker.IsNil)
  4551. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4552. b, err := ioutil.ReadFile(configPath)
  4553. c.Assert(err, checker.IsNil)
  4554. c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":")
  4555. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  4556. dockerCmd(c, "--config", tmp, "push", repoName)
  4557. // make sure the image is pulled when building
  4558. dockerCmd(c, "rmi", repoName)
  4559. icmd.RunCmd(icmd.Cmd{
  4560. Command: []string{dockerBinary, "--config", tmp, "build", "-"},
  4561. Stdin: strings.NewReader(fmt.Sprintf("FROM %s", repoName)),
  4562. }).Assert(c, icmd.Success)
  4563. }
  4564. // Test cases in #22036
  4565. func (s *DockerSuite) TestBuildLabelsOverride(c *check.C) {
  4566. // Command line option labels will always override
  4567. name := "scratchy"
  4568. expected := `{"bar":"from-flag","foo":"from-flag"}`
  4569. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4570. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4571. LABEL foo=from-dockerfile`))
  4572. res := inspectFieldJSON(c, name, "Config.Labels")
  4573. if res != expected {
  4574. c.Fatalf("Labels %s, expected %s", res, expected)
  4575. }
  4576. name = "from"
  4577. expected = `{"foo":"from-dockerfile"}`
  4578. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4579. LABEL foo from-dockerfile`))
  4580. res = inspectFieldJSON(c, name, "Config.Labels")
  4581. if res != expected {
  4582. c.Fatalf("Labels %s, expected %s", res, expected)
  4583. }
  4584. // Command line option label will override even via `FROM`
  4585. name = "new"
  4586. expected = `{"bar":"from-dockerfile2","foo":"new"}`
  4587. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=new"),
  4588. build.WithDockerfile(`FROM from
  4589. LABEL bar from-dockerfile2`))
  4590. res = inspectFieldJSON(c, name, "Config.Labels")
  4591. if res != expected {
  4592. c.Fatalf("Labels %s, expected %s", res, expected)
  4593. }
  4594. // Command line option without a value set (--label foo, --label bar=)
  4595. // will be treated as --label foo="", --label bar=""
  4596. name = "scratchy2"
  4597. expected = `{"bar":"","foo":""}`
  4598. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo", "--label", "bar="),
  4599. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4600. LABEL foo=from-dockerfile`))
  4601. res = inspectFieldJSON(c, name, "Config.Labels")
  4602. if res != expected {
  4603. c.Fatalf("Labels %s, expected %s", res, expected)
  4604. }
  4605. // Command line option without a value set (--label foo, --label bar=)
  4606. // will be treated as --label foo="", --label bar=""
  4607. // This time is for inherited images
  4608. name = "new2"
  4609. expected = `{"bar":"","foo":""}`
  4610. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=", "--label", "bar"),
  4611. build.WithDockerfile(`FROM from
  4612. LABEL bar from-dockerfile2`))
  4613. res = inspectFieldJSON(c, name, "Config.Labels")
  4614. if res != expected {
  4615. c.Fatalf("Labels %s, expected %s", res, expected)
  4616. }
  4617. // Command line option labels with only `FROM`
  4618. name = "scratchy"
  4619. expected = `{"bar":"from-flag","foo":"from-flag"}`
  4620. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4621. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4622. res = inspectFieldJSON(c, name, "Config.Labels")
  4623. if res != expected {
  4624. c.Fatalf("Labels %s, expected %s", res, expected)
  4625. }
  4626. // Command line option labels with env var
  4627. name = "scratchz"
  4628. expected = `{"bar":"$PATH"}`
  4629. buildImageSuccessfully(c, name, cli.WithFlags("--label", "bar=$PATH"),
  4630. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4631. res = inspectFieldJSON(c, name, "Config.Labels")
  4632. if res != expected {
  4633. c.Fatalf("Labels %s, expected %s", res, expected)
  4634. }
  4635. }
  4636. // Test case for #22855
  4637. func (s *DockerSuite) TestBuildDeleteCommittedFile(c *check.C) {
  4638. name := "test-delete-committed-file"
  4639. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4640. RUN echo test > file
  4641. RUN test -e file
  4642. RUN rm file
  4643. RUN sh -c "! test -e file"`))
  4644. }
  4645. // #20083
  4646. func (s *DockerSuite) TestBuildDockerignoreComment(c *check.C) {
  4647. // TODO Windows: Figure out why this test is flakey on TP5. If you add
  4648. // something like RUN sleep 5, or even RUN ls /tmp after the ADD line,
  4649. // it is more reliable, but that's not a good fix.
  4650. testRequires(c, DaemonIsLinux)
  4651. name := "testbuilddockerignorecleanpaths"
  4652. dockerfile := `
  4653. FROM busybox
  4654. ADD . /tmp/
  4655. RUN sh -c "(ls -la /tmp/#1)"
  4656. RUN sh -c "(! ls -la /tmp/#2)"
  4657. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (ls /tmp/dir1/foo)"`
  4658. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4659. build.WithFile("Dockerfile", dockerfile),
  4660. build.WithFile("foo", "foo"),
  4661. build.WithFile("foo2", "foo2"),
  4662. build.WithFile("dir1/foo", "foo in dir1"),
  4663. build.WithFile("#1", "# file 1"),
  4664. build.WithFile("#2", "# file 2"),
  4665. build.WithFile(".dockerignore", `# Visual C++ cache files
  4666. # because we have git ;-)
  4667. # The above comment is from #20083
  4668. foo
  4669. #dir1/foo
  4670. foo2
  4671. # The following is considered as comment as # is at the beginning
  4672. #1
  4673. # The following is not considered as comment as # is not at the beginning
  4674. #2
  4675. `)))
  4676. }
  4677. // Test case for #23221
  4678. func (s *DockerSuite) TestBuildWithUTF8BOM(c *check.C) {
  4679. name := "test-with-utf8-bom"
  4680. dockerfile := []byte(`FROM busybox`)
  4681. bomDockerfile := append([]byte{0xEF, 0xBB, 0xBF}, dockerfile...)
  4682. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4683. build.WithFile("Dockerfile", string(bomDockerfile)),
  4684. ))
  4685. }
  4686. // Test case for UTF-8 BOM in .dockerignore, related to #23221
  4687. func (s *DockerSuite) TestBuildWithUTF8BOMDockerignore(c *check.C) {
  4688. name := "test-with-utf8-bom-dockerignore"
  4689. dockerfile := `
  4690. FROM busybox
  4691. ADD . /tmp/
  4692. RUN ls -la /tmp
  4693. RUN sh -c "! ls /tmp/Dockerfile"
  4694. RUN ls /tmp/.dockerignore`
  4695. dockerignore := []byte("./Dockerfile\n")
  4696. bomDockerignore := append([]byte{0xEF, 0xBB, 0xBF}, dockerignore...)
  4697. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4698. build.WithFile("Dockerfile", dockerfile),
  4699. build.WithFile(".dockerignore", string(bomDockerignore)),
  4700. ))
  4701. }
  4702. // #22489 Shell test to confirm config gets updated correctly
  4703. func (s *DockerSuite) TestBuildShellUpdatesConfig(c *check.C) {
  4704. name := "testbuildshellupdatesconfig"
  4705. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4706. SHELL ["foo", "-bar"]`))
  4707. expected := `["foo","-bar","#(nop) ","SHELL [foo -bar]"]`
  4708. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  4709. if res != expected {
  4710. c.Fatalf("%s, expected %s", res, expected)
  4711. }
  4712. res = inspectFieldJSON(c, name, "ContainerConfig.Shell")
  4713. if res != `["foo","-bar"]` {
  4714. c.Fatalf(`%s, expected ["foo","-bar"]`, res)
  4715. }
  4716. }
  4717. // #22489 Changing the shell multiple times and CMD after.
  4718. func (s *DockerSuite) TestBuildShellMultiple(c *check.C) {
  4719. name := "testbuildshellmultiple"
  4720. result := buildImage(name, build.WithDockerfile(`FROM busybox
  4721. RUN echo defaultshell
  4722. SHELL ["echo"]
  4723. RUN echoshell
  4724. SHELL ["ls"]
  4725. RUN -l
  4726. CMD -l`))
  4727. result.Assert(c, icmd.Success)
  4728. // Must contain 'defaultshell' twice
  4729. if len(strings.Split(result.Combined(), "defaultshell")) != 3 {
  4730. c.Fatalf("defaultshell should have appeared twice in %s", result.Combined())
  4731. }
  4732. // Must contain 'echoshell' twice
  4733. if len(strings.Split(result.Combined(), "echoshell")) != 3 {
  4734. c.Fatalf("echoshell should have appeared twice in %s", result.Combined())
  4735. }
  4736. // Must contain "total " (part of ls -l)
  4737. if !strings.Contains(result.Combined(), "total ") {
  4738. c.Fatalf("%s should have contained 'total '", result.Combined())
  4739. }
  4740. // A container started from the image uses the shell-form CMD.
  4741. // Last shell is ls. CMD is -l. So should contain 'total '.
  4742. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4743. if !strings.Contains(outrun, "total ") {
  4744. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4745. }
  4746. }
  4747. // #22489. Changed SHELL with ENTRYPOINT
  4748. func (s *DockerSuite) TestBuildShellEntrypoint(c *check.C) {
  4749. name := "testbuildshellentrypoint"
  4750. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4751. SHELL ["ls"]
  4752. ENTRYPOINT -l`))
  4753. // A container started from the image uses the shell-form ENTRYPOINT.
  4754. // Shell is ls. ENTRYPOINT is -l. So should contain 'total '.
  4755. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4756. if !strings.Contains(outrun, "total ") {
  4757. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4758. }
  4759. }
  4760. // #22489 Shell test to confirm shell is inherited in a subsequent build
  4761. func (s *DockerSuite) TestBuildShellInherited(c *check.C) {
  4762. name1 := "testbuildshellinherited1"
  4763. buildImageSuccessfully(c, name1, build.WithDockerfile(`FROM busybox
  4764. SHELL ["ls"]`))
  4765. name2 := "testbuildshellinherited2"
  4766. buildImage(name2, build.WithDockerfile(`FROM `+name1+`
  4767. RUN -l`)).Assert(c, icmd.Expected{
  4768. // ls -l has "total " followed by some number in it, ls without -l does not.
  4769. Out: "total ",
  4770. })
  4771. }
  4772. // #22489 Shell test to confirm non-JSON doesn't work
  4773. func (s *DockerSuite) TestBuildShellNotJSON(c *check.C) {
  4774. name := "testbuildshellnotjson"
  4775. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4776. sHeLl exec -form`, // Casing explicit to ensure error is upper-cased.
  4777. )).Assert(c, icmd.Expected{
  4778. ExitCode: 1,
  4779. Err: "SHELL requires the arguments to be in JSON form",
  4780. })
  4781. }
  4782. // #22489 Windows shell test to confirm native is powershell if executing a PS command
  4783. // This would error if the default shell were still cmd.
  4784. func (s *DockerSuite) TestBuildShellWindowsPowershell(c *check.C) {
  4785. testRequires(c, DaemonIsWindows)
  4786. name := "testbuildshellpowershell"
  4787. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4788. SHELL ["powershell", "-command"]
  4789. RUN Write-Host John`)).Assert(c, icmd.Expected{
  4790. Out: "\nJohn\n",
  4791. })
  4792. }
  4793. // Verify that escape is being correctly applied to words when escape directive is not \.
  4794. // Tests WORKDIR, ADD
  4795. func (s *DockerSuite) TestBuildEscapeNotBackslashWordTest(c *check.C) {
  4796. testRequires(c, DaemonIsWindows)
  4797. name := "testbuildescapenotbackslashwordtesta"
  4798. buildImage(name, build.WithDockerfile(`# escape= `+"`"+`
  4799. FROM `+minimalBaseImage()+`
  4800. WORKDIR c:\windows
  4801. RUN dir /w`)).Assert(c, icmd.Expected{
  4802. Out: "[System32]",
  4803. })
  4804. name = "testbuildescapenotbackslashwordtestb"
  4805. buildImage(name, build.WithDockerfile(`# escape= `+"`"+`
  4806. FROM `+minimalBaseImage()+`
  4807. SHELL ["powershell.exe"]
  4808. WORKDIR c:\foo
  4809. ADD Dockerfile c:\foo\
  4810. RUN dir Dockerfile`)).Assert(c, icmd.Expected{
  4811. Out: "-a----",
  4812. })
  4813. }
  4814. // #22868. Make sure shell-form CMD is marked as escaped in the config of the image
  4815. func (s *DockerSuite) TestBuildCmdShellArgsEscaped(c *check.C) {
  4816. testRequires(c, DaemonIsWindows)
  4817. name := "testbuildcmdshellescaped"
  4818. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4819. FROM `+minimalBaseImage()+`
  4820. CMD "ipconfig"
  4821. `))
  4822. res := inspectFieldJSON(c, name, "Config.ArgsEscaped")
  4823. if res != "true" {
  4824. c.Fatalf("CMD did not update Config.ArgsEscaped on image: %v", res)
  4825. }
  4826. dockerCmd(c, "run", "--name", "inspectme", name)
  4827. dockerCmd(c, "wait", "inspectme")
  4828. res = inspectFieldJSON(c, name, "Config.Cmd")
  4829. if res != `["cmd","/S","/C","\"ipconfig\""]` {
  4830. c.Fatalf("CMD was not escaped Config.Cmd: got %v", res)
  4831. }
  4832. }
  4833. // Test case for #24912.
  4834. func (s *DockerSuite) TestBuildStepsWithProgress(c *check.C) {
  4835. name := "testbuildstepswithprogress"
  4836. totalRun := 5
  4837. result := buildImage(name, build.WithDockerfile("FROM busybox\n"+strings.Repeat("RUN echo foo\n", totalRun)))
  4838. result.Assert(c, icmd.Success)
  4839. c.Assert(result.Combined(), checker.Contains, fmt.Sprintf("Step 1/%d : FROM busybox", 1+totalRun))
  4840. for i := 2; i <= 1+totalRun; i++ {
  4841. c.Assert(result.Combined(), checker.Contains, fmt.Sprintf("Step %d/%d : RUN echo foo", i, 1+totalRun))
  4842. }
  4843. }
  4844. func (s *DockerSuite) TestBuildWithFailure(c *check.C) {
  4845. name := "testbuildwithfailure"
  4846. // First test case can only detect `nobody` in runtime so all steps will show up
  4847. dockerfile := "FROM busybox\nRUN nobody"
  4848. result := buildImage(name, build.WithDockerfile(dockerfile))
  4849. c.Assert(result.Error, checker.NotNil)
  4850. c.Assert(result.Stdout(), checker.Contains, "Step 1/2 : FROM busybox")
  4851. c.Assert(result.Stdout(), checker.Contains, "Step 2/2 : RUN nobody")
  4852. // Second test case `FFOM` should have been detected before build runs so no steps
  4853. dockerfile = "FFOM nobody\nRUN nobody"
  4854. result = buildImage(name, build.WithDockerfile(dockerfile))
  4855. c.Assert(result.Error, checker.NotNil)
  4856. c.Assert(result.Stdout(), checker.Not(checker.Contains), "Step 1/2 : FROM busybox")
  4857. c.Assert(result.Stdout(), checker.Not(checker.Contains), "Step 2/2 : RUN nobody")
  4858. }
  4859. func (s *DockerSuite) TestBuildCacheFromEqualDiffIDsLength(c *check.C) {
  4860. dockerfile := `
  4861. FROM busybox
  4862. RUN echo "test"
  4863. ENTRYPOINT ["sh"]`
  4864. ctx := fakecontext.New(c, "",
  4865. fakecontext.WithDockerfile(dockerfile),
  4866. fakecontext.WithFiles(map[string]string{
  4867. "Dockerfile": dockerfile,
  4868. }))
  4869. defer ctx.Close()
  4870. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4871. id1 := getIDByName(c, "build1")
  4872. // rebuild with cache-from
  4873. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4874. id2 := getIDByName(c, "build2")
  4875. c.Assert(id1, checker.Equals, id2)
  4876. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 2)
  4877. }
  4878. func (s *DockerSuite) TestBuildCacheFrom(c *check.C) {
  4879. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4880. dockerfile := `
  4881. FROM busybox
  4882. ENV FOO=bar
  4883. ADD baz /
  4884. RUN touch bax`
  4885. ctx := fakecontext.New(c, "",
  4886. fakecontext.WithDockerfile(dockerfile),
  4887. fakecontext.WithFiles(map[string]string{
  4888. "Dockerfile": dockerfile,
  4889. "baz": "baz",
  4890. }))
  4891. defer ctx.Close()
  4892. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4893. id1 := getIDByName(c, "build1")
  4894. // rebuild with cache-from
  4895. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4896. id2 := getIDByName(c, "build2")
  4897. c.Assert(id1, checker.Equals, id2)
  4898. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4899. cli.DockerCmd(c, "rmi", "build2")
  4900. // no cache match with unknown source
  4901. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=nosuchtag"), build.WithExternalBuildContext(ctx))
  4902. id2 = getIDByName(c, "build2")
  4903. c.Assert(id1, checker.Not(checker.Equals), id2)
  4904. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 0)
  4905. cli.DockerCmd(c, "rmi", "build2")
  4906. // clear parent images
  4907. tempDir, err := ioutil.TempDir("", "test-build-cache-from-")
  4908. if err != nil {
  4909. c.Fatalf("failed to create temporary directory: %s", tempDir)
  4910. }
  4911. defer os.RemoveAll(tempDir)
  4912. tempFile := filepath.Join(tempDir, "img.tar")
  4913. cli.DockerCmd(c, "save", "-o", tempFile, "build1")
  4914. cli.DockerCmd(c, "rmi", "build1")
  4915. cli.DockerCmd(c, "load", "-i", tempFile)
  4916. parentID := cli.DockerCmd(c, "inspect", "-f", "{{.Parent}}", "build1").Combined()
  4917. c.Assert(strings.TrimSpace(parentID), checker.Equals, "")
  4918. // cache still applies without parents
  4919. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4920. id2 = getIDByName(c, "build2")
  4921. c.Assert(id1, checker.Equals, id2)
  4922. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4923. history1 := cli.DockerCmd(c, "history", "-q", "build2").Combined()
  4924. // Retry, no new intermediate images
  4925. result = cli.BuildCmd(c, "build3", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4926. id3 := getIDByName(c, "build3")
  4927. c.Assert(id1, checker.Equals, id3)
  4928. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4929. history2 := cli.DockerCmd(c, "history", "-q", "build3").Combined()
  4930. c.Assert(history1, checker.Equals, history2)
  4931. cli.DockerCmd(c, "rmi", "build2")
  4932. cli.DockerCmd(c, "rmi", "build3")
  4933. cli.DockerCmd(c, "rmi", "build1")
  4934. cli.DockerCmd(c, "load", "-i", tempFile)
  4935. // Modify file, everything up to last command and layers are reused
  4936. dockerfile = `
  4937. FROM busybox
  4938. ENV FOO=bar
  4939. ADD baz /
  4940. RUN touch newfile`
  4941. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(dockerfile), 0644)
  4942. c.Assert(err, checker.IsNil)
  4943. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4944. id2 = getIDByName(c, "build2")
  4945. c.Assert(id1, checker.Not(checker.Equals), id2)
  4946. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 2)
  4947. layers1Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build1").Combined()
  4948. layers2Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build2").Combined()
  4949. var layers1 []string
  4950. var layers2 []string
  4951. c.Assert(json.Unmarshal([]byte(layers1Str), &layers1), checker.IsNil)
  4952. c.Assert(json.Unmarshal([]byte(layers2Str), &layers2), checker.IsNil)
  4953. c.Assert(len(layers1), checker.Equals, len(layers2))
  4954. for i := 0; i < len(layers1)-1; i++ {
  4955. c.Assert(layers1[i], checker.Equals, layers2[i])
  4956. }
  4957. c.Assert(layers1[len(layers1)-1], checker.Not(checker.Equals), layers2[len(layers1)-1])
  4958. }
  4959. func (s *DockerSuite) TestBuildCacheMultipleFrom(c *check.C) {
  4960. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4961. dockerfile := `
  4962. FROM busybox
  4963. ADD baz /
  4964. FROM busybox
  4965. ADD baz /`
  4966. ctx := fakecontext.New(c, "",
  4967. fakecontext.WithDockerfile(dockerfile),
  4968. fakecontext.WithFiles(map[string]string{
  4969. "Dockerfile": dockerfile,
  4970. "baz": "baz",
  4971. }))
  4972. defer ctx.Close()
  4973. result := cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4974. // second part of dockerfile was a repeat of first so should be cached
  4975. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 1)
  4976. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4977. // now both parts of dockerfile should be cached
  4978. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 2)
  4979. }
  4980. func (s *DockerSuite) TestBuildNetNone(c *check.C) {
  4981. testRequires(c, DaemonIsLinux)
  4982. name := "testbuildnetnone"
  4983. buildImage(name, cli.WithFlags("--network=none"), build.WithDockerfile(`
  4984. FROM busybox
  4985. RUN ping -c 1 8.8.8.8
  4986. `)).Assert(c, icmd.Expected{
  4987. ExitCode: 1,
  4988. Out: "unreachable",
  4989. })
  4990. }
  4991. func (s *DockerSuite) TestBuildNetContainer(c *check.C) {
  4992. testRequires(c, DaemonIsLinux)
  4993. id, _ := dockerCmd(c, "run", "--hostname", "foobar", "-d", "busybox", "nc", "-ll", "-p", "1234", "-e", "hostname")
  4994. name := "testbuildnetcontainer"
  4995. buildImageSuccessfully(c, name, cli.WithFlags("--network=container:"+strings.TrimSpace(id)),
  4996. build.WithDockerfile(`
  4997. FROM busybox
  4998. RUN nc localhost 1234 > /otherhost
  4999. `))
  5000. host, _ := dockerCmd(c, "run", "testbuildnetcontainer", "cat", "/otherhost")
  5001. c.Assert(strings.TrimSpace(host), check.Equals, "foobar")
  5002. }
  5003. func (s *DockerSuite) TestBuildWithExtraHost(c *check.C) {
  5004. testRequires(c, DaemonIsLinux)
  5005. name := "testbuildwithextrahost"
  5006. buildImageSuccessfully(c, name,
  5007. cli.WithFlags(
  5008. "--add-host", "foo:127.0.0.1",
  5009. "--add-host", "bar:127.0.0.1",
  5010. ),
  5011. build.WithDockerfile(`
  5012. FROM busybox
  5013. RUN ping -c 1 foo
  5014. RUN ping -c 1 bar
  5015. `))
  5016. }
  5017. func (s *DockerSuite) TestBuildWithExtraHostInvalidFormat(c *check.C) {
  5018. testRequires(c, DaemonIsLinux)
  5019. dockerfile := `
  5020. FROM busybox
  5021. RUN ping -c 1 foo`
  5022. testCases := []struct {
  5023. testName string
  5024. dockerfile string
  5025. buildFlag string
  5026. }{
  5027. {"extra_host_missing_ip", dockerfile, "--add-host=foo"},
  5028. {"extra_host_missing_ip_with_delimeter", dockerfile, "--add-host=foo:"},
  5029. {"extra_host_missing_hostname", dockerfile, "--add-host=:127.0.0.1"},
  5030. {"extra_host_invalid_ipv4", dockerfile, "--add-host=foo:101.10.2"},
  5031. {"extra_host_invalid_ipv6", dockerfile, "--add-host=foo:2001::1::3F"},
  5032. }
  5033. for _, tc := range testCases {
  5034. result := buildImage(tc.testName, cli.WithFlags(tc.buildFlag), build.WithDockerfile(tc.dockerfile))
  5035. result.Assert(c, icmd.Expected{
  5036. ExitCode: 125,
  5037. })
  5038. }
  5039. }
  5040. func (s *DockerSuite) TestBuildSquashParent(c *check.C) {
  5041. testRequires(c, ExperimentalDaemon)
  5042. dockerFile := `
  5043. FROM busybox
  5044. RUN echo hello > /hello
  5045. RUN echo world >> /hello
  5046. RUN echo hello > /remove_me
  5047. ENV HELLO world
  5048. RUN rm /remove_me
  5049. `
  5050. // build and get the ID that we can use later for history comparison
  5051. name := "test"
  5052. buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
  5053. origID := getIDByName(c, name)
  5054. // build with squash
  5055. buildImageSuccessfully(c, name, cli.WithFlags("--squash"), build.WithDockerfile(dockerFile))
  5056. id := getIDByName(c, name)
  5057. out, _ := dockerCmd(c, "run", "--rm", id, "/bin/sh", "-c", "cat /hello")
  5058. c.Assert(strings.TrimSpace(out), checker.Equals, "hello\nworld")
  5059. dockerCmd(c, "run", "--rm", id, "/bin/sh", "-c", "[ ! -f /remove_me ]")
  5060. dockerCmd(c, "run", "--rm", id, "/bin/sh", "-c", `[ "$(echo $HELLO)" == "world" ]`)
  5061. // make sure the ID produced is the ID of the tag we specified
  5062. inspectID := inspectImage(c, "test", ".ID")
  5063. c.Assert(inspectID, checker.Equals, id)
  5064. origHistory, _ := dockerCmd(c, "history", origID)
  5065. testHistory, _ := dockerCmd(c, "history", "test")
  5066. splitOrigHistory := strings.Split(strings.TrimSpace(origHistory), "\n")
  5067. splitTestHistory := strings.Split(strings.TrimSpace(testHistory), "\n")
  5068. c.Assert(len(splitTestHistory), checker.Equals, len(splitOrigHistory)+1)
  5069. out = inspectImage(c, id, "len .RootFS.Layers")
  5070. c.Assert(strings.TrimSpace(out), checker.Equals, "2")
  5071. }
  5072. func (s *DockerSuite) TestBuildContChar(c *check.C) {
  5073. name := "testbuildcontchar"
  5074. buildImage(name, build.WithDockerfile(`FROM busybox\`)).Assert(c, icmd.Expected{
  5075. Out: "Step 1/1 : FROM busybox",
  5076. })
  5077. result := buildImage(name, build.WithDockerfile(`FROM busybox
  5078. RUN echo hi \`))
  5079. result.Assert(c, icmd.Success)
  5080. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  5081. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi\n")
  5082. result = buildImage(name, build.WithDockerfile(`FROM busybox
  5083. RUN echo hi \\`))
  5084. result.Assert(c, icmd.Success)
  5085. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  5086. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi \\\n")
  5087. result = buildImage(name, build.WithDockerfile(`FROM busybox
  5088. RUN echo hi \\\`))
  5089. result.Assert(c, icmd.Success)
  5090. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  5091. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi \\\\\n")
  5092. }
  5093. func (s *DockerSuite) TestBuildCopyFromPreviousRootFS(c *check.C) {
  5094. dockerfile := `
  5095. FROM busybox AS first
  5096. COPY foo bar
  5097. FROM busybox
  5098. %s
  5099. COPY baz baz
  5100. RUN echo mno > baz/cc
  5101. FROM busybox
  5102. COPY bar /
  5103. COPY --from=1 baz sub/
  5104. COPY --from=0 bar baz
  5105. COPY --from=first bar bay`
  5106. ctx := fakecontext.New(c, "",
  5107. fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, "")),
  5108. fakecontext.WithFiles(map[string]string{
  5109. "foo": "abc",
  5110. "bar": "def",
  5111. "baz/aa": "ghi",
  5112. "baz/bb": "jkl",
  5113. }))
  5114. defer ctx.Close()
  5115. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5116. out := cli.DockerCmd(c, "run", "build1", "cat", "bar").Combined()
  5117. c.Assert(strings.TrimSpace(out), check.Equals, "def")
  5118. out = cli.DockerCmd(c, "run", "build1", "cat", "sub/aa").Combined()
  5119. c.Assert(strings.TrimSpace(out), check.Equals, "ghi")
  5120. out = cli.DockerCmd(c, "run", "build1", "cat", "sub/cc").Combined()
  5121. c.Assert(strings.TrimSpace(out), check.Equals, "mno")
  5122. out = cli.DockerCmd(c, "run", "build1", "cat", "baz").Combined()
  5123. c.Assert(strings.TrimSpace(out), check.Equals, "abc")
  5124. out = cli.DockerCmd(c, "run", "build1", "cat", "bay").Combined()
  5125. c.Assert(strings.TrimSpace(out), check.Equals, "abc")
  5126. result := cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5127. // all commands should be cached
  5128. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 7)
  5129. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(fmt.Sprintf(dockerfile, "COPY baz/aa foo")), 0644)
  5130. c.Assert(err, checker.IsNil)
  5131. // changing file in parent block should not affect last block
  5132. result = cli.BuildCmd(c, "build3", build.WithExternalBuildContext(ctx))
  5133. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 5)
  5134. c.Assert(getIDByName(c, "build1"), checker.Equals, getIDByName(c, "build2"))
  5135. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("pqr"), 0644)
  5136. c.Assert(err, checker.IsNil)
  5137. // changing file in parent block should affect both first and last block
  5138. result = cli.BuildCmd(c, "build4", build.WithExternalBuildContext(ctx))
  5139. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 5)
  5140. out = cli.DockerCmd(c, "run", "build4", "cat", "bay").Combined()
  5141. c.Assert(strings.TrimSpace(out), check.Equals, "pqr")
  5142. out = cli.DockerCmd(c, "run", "build4", "cat", "baz").Combined()
  5143. c.Assert(strings.TrimSpace(out), check.Equals, "pqr")
  5144. }
  5145. func (s *DockerSuite) TestBuildCopyFromPreviousRootFSErrors(c *check.C) {
  5146. testCases := []struct {
  5147. dockerfile string
  5148. expectedError string
  5149. }{
  5150. {
  5151. dockerfile: `
  5152. FROM busybox
  5153. COPY --from=foo foo bar`,
  5154. expectedError: "invalid from flag value foo",
  5155. },
  5156. {
  5157. dockerfile: `
  5158. FROM busybox
  5159. COPY --from=0 foo bar`,
  5160. expectedError: "invalid from flag value 0 refers current build block",
  5161. },
  5162. {
  5163. dockerfile: `
  5164. FROM busybox AS foo
  5165. COPY --from=bar foo bar`,
  5166. expectedError: "invalid from flag value bar",
  5167. },
  5168. {
  5169. dockerfile: `
  5170. FROM busybox AS 1
  5171. COPY --from=1 foo bar`,
  5172. expectedError: "invalid name for build stage",
  5173. },
  5174. }
  5175. for _, tc := range testCases {
  5176. ctx := fakecontext.New(c, "",
  5177. fakecontext.WithDockerfile(tc.dockerfile),
  5178. fakecontext.WithFiles(map[string]string{
  5179. "foo": "abc",
  5180. }))
  5181. cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  5182. ExitCode: 1,
  5183. Err: tc.expectedError,
  5184. })
  5185. ctx.Close()
  5186. }
  5187. }
  5188. func (s *DockerSuite) TestBuildCopyFromPreviousFrom(c *check.C) {
  5189. dockerfile := `
  5190. FROM busybox
  5191. COPY foo bar`
  5192. ctx := fakecontext.New(c, "",
  5193. fakecontext.WithDockerfile(dockerfile),
  5194. fakecontext.WithFiles(map[string]string{
  5195. "foo": "abc",
  5196. }))
  5197. defer ctx.Close()
  5198. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5199. dockerfile = `
  5200. FROM build1:latest AS foo
  5201. FROM busybox
  5202. COPY --from=foo bar /
  5203. COPY foo /`
  5204. ctx = fakecontext.New(c, "",
  5205. fakecontext.WithDockerfile(dockerfile),
  5206. fakecontext.WithFiles(map[string]string{
  5207. "foo": "def",
  5208. }))
  5209. defer ctx.Close()
  5210. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5211. out := cli.DockerCmd(c, "run", "build2", "cat", "bar").Combined()
  5212. c.Assert(strings.TrimSpace(out), check.Equals, "abc")
  5213. out = cli.DockerCmd(c, "run", "build2", "cat", "foo").Combined()
  5214. c.Assert(strings.TrimSpace(out), check.Equals, "def")
  5215. }
  5216. func (s *DockerSuite) TestBuildCopyFromImplicitFrom(c *check.C) {
  5217. dockerfile := `
  5218. FROM busybox
  5219. COPY --from=busybox /etc/passwd /mypasswd
  5220. RUN cmp /etc/passwd /mypasswd`
  5221. if DaemonIsWindows() {
  5222. dockerfile = `
  5223. FROM busybox
  5224. COPY --from=busybox License.txt foo`
  5225. }
  5226. ctx := fakecontext.New(c, "",
  5227. fakecontext.WithDockerfile(dockerfile),
  5228. )
  5229. defer ctx.Close()
  5230. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5231. if DaemonIsWindows() {
  5232. out := cli.DockerCmd(c, "run", "build1", "cat", "License.txt").Combined()
  5233. c.Assert(len(out), checker.GreaterThan, 10)
  5234. out2 := cli.DockerCmd(c, "run", "build1", "cat", "foo").Combined()
  5235. c.Assert(out, check.Equals, out2)
  5236. }
  5237. }
  5238. func (s *DockerRegistrySuite) TestBuildCopyFromImplicitPullingFrom(c *check.C) {
  5239. repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL)
  5240. dockerfile := `
  5241. FROM busybox
  5242. COPY foo bar`
  5243. ctx := fakecontext.New(c, "",
  5244. fakecontext.WithDockerfile(dockerfile),
  5245. fakecontext.WithFiles(map[string]string{
  5246. "foo": "abc",
  5247. }))
  5248. defer ctx.Close()
  5249. cli.BuildCmd(c, repoName, build.WithExternalBuildContext(ctx))
  5250. cli.DockerCmd(c, "push", repoName)
  5251. cli.DockerCmd(c, "rmi", repoName)
  5252. dockerfile = `
  5253. FROM busybox
  5254. COPY --from=%s bar baz`
  5255. ctx = fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, repoName)))
  5256. defer ctx.Close()
  5257. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5258. cli.Docker(cli.Args("run", "build1", "cat", "baz")).Assert(c, icmd.Expected{Out: "abc"})
  5259. }
  5260. func (s *DockerSuite) TestBuildFromPreviousBlock(c *check.C) {
  5261. dockerfile := `
  5262. FROM busybox as foo
  5263. COPY foo /
  5264. FROM foo as foo1
  5265. RUN echo 1 >> foo
  5266. FROM foo as foO2
  5267. RUN echo 2 >> foo
  5268. FROM foo
  5269. COPY --from=foo1 foo f1
  5270. COPY --from=FOo2 foo f2
  5271. ` // foo2 case also tests that names are canse insensitive
  5272. ctx := fakecontext.New(c, "",
  5273. fakecontext.WithDockerfile(dockerfile),
  5274. fakecontext.WithFiles(map[string]string{
  5275. "foo": "bar",
  5276. }))
  5277. defer ctx.Close()
  5278. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5279. cli.Docker(cli.Args("run", "build1", "cat", "foo")).Assert(c, icmd.Expected{Out: "bar"})
  5280. cli.Docker(cli.Args("run", "build1", "cat", "f1")).Assert(c, icmd.Expected{Out: "bar1"})
  5281. cli.Docker(cli.Args("run", "build1", "cat", "f2")).Assert(c, icmd.Expected{Out: "bar2"})
  5282. }
  5283. func (s *DockerTrustSuite) TestCopyFromTrustedBuild(c *check.C) {
  5284. img1 := s.setupTrustedImage(c, "trusted-build1")
  5285. img2 := s.setupTrustedImage(c, "trusted-build2")
  5286. dockerFile := fmt.Sprintf(`
  5287. FROM %s AS build-base
  5288. RUN echo ok > /foo
  5289. FROM %s
  5290. COPY --from=build-base foo bar`, img1, img2)
  5291. name := "testcopyfromtrustedbuild"
  5292. r := buildImage(name, trustedBuild, build.WithDockerfile(dockerFile))
  5293. r.Assert(c, icmd.Expected{
  5294. Out: fmt.Sprintf("FROM %s@sha", img1[:len(img1)-7]),
  5295. })
  5296. r.Assert(c, icmd.Expected{
  5297. Out: fmt.Sprintf("FROM %s@sha", img2[:len(img2)-7]),
  5298. })
  5299. dockerCmdWithResult("run", name, "cat", "bar").Assert(c, icmd.Expected{Out: "ok"})
  5300. }
  5301. func (s *DockerSuite) TestBuildCopyFromPreviousFromWindows(c *check.C) {
  5302. testRequires(c, DaemonIsWindows)
  5303. dockerfile := `
  5304. FROM ` + testEnv.MinimalBaseImage() + `
  5305. COPY foo c:\\bar`
  5306. ctx := fakecontext.New(c, "",
  5307. fakecontext.WithDockerfile(dockerfile),
  5308. fakecontext.WithFiles(map[string]string{
  5309. "foo": "abc",
  5310. }))
  5311. defer ctx.Close()
  5312. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5313. dockerfile = `
  5314. FROM build1:latest
  5315. FROM ` + testEnv.MinimalBaseImage() + `
  5316. COPY --from=0 c:\\bar /
  5317. COPY foo /`
  5318. ctx = fakecontext.New(c, "",
  5319. fakecontext.WithDockerfile(dockerfile),
  5320. fakecontext.WithFiles(map[string]string{
  5321. "foo": "def",
  5322. }))
  5323. defer ctx.Close()
  5324. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5325. out := cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\bar").Combined()
  5326. c.Assert(strings.TrimSpace(out), check.Equals, "abc")
  5327. out = cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\foo").Combined()
  5328. c.Assert(strings.TrimSpace(out), check.Equals, "def")
  5329. }
  5330. func (s *DockerSuite) TestBuildCopyFromForbidWindowsSystemPaths(c *check.C) {
  5331. testRequires(c, DaemonIsWindows)
  5332. dockerfile := `
  5333. FROM ` + testEnv.MinimalBaseImage() + `
  5334. FROM ` + testEnv.MinimalBaseImage() + `
  5335. COPY --from=0 %s c:\\oscopy
  5336. `
  5337. exp := icmd.Expected{
  5338. ExitCode: 1,
  5339. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5340. }
  5341. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\"))).Assert(c, exp)
  5342. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "C:\\\\"))).Assert(c, exp)
  5343. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\windows"))).Assert(c, exp)
  5344. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\wInDows"))).Assert(c, exp)
  5345. }
  5346. func (s *DockerSuite) TestBuildCopyFromForbidWindowsRelativePaths(c *check.C) {
  5347. testRequires(c, DaemonIsWindows)
  5348. dockerfile := `
  5349. FROM ` + testEnv.MinimalBaseImage() + `
  5350. FROM ` + testEnv.MinimalBaseImage() + `
  5351. COPY --from=0 %s c:\\oscopy
  5352. `
  5353. exp := icmd.Expected{
  5354. ExitCode: 1,
  5355. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5356. }
  5357. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:"))).Assert(c, exp)
  5358. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "."))).Assert(c, exp)
  5359. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "..\\\\"))).Assert(c, exp)
  5360. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, ".\\\\windows"))).Assert(c, exp)
  5361. buildImage("testforbidsystempaths5", build.WithDockerfile(fmt.Sprintf(dockerfile, "\\\\windows"))).Assert(c, exp)
  5362. }
  5363. func (s *DockerSuite) TestBuildCopyFromWindowsIsCaseInsensitive(c *check.C) {
  5364. testRequires(c, DaemonIsWindows)
  5365. dockerfile := `
  5366. FROM ` + testEnv.MinimalBaseImage() + `
  5367. COPY foo /
  5368. FROM ` + testEnv.MinimalBaseImage() + `
  5369. COPY --from=0 c:\\fOo c:\\copied
  5370. RUN type c:\\copied
  5371. `
  5372. cli.Docker(cli.Build("copyfrom-windows-insensitive"), build.WithBuildContext(c,
  5373. build.WithFile("Dockerfile", dockerfile),
  5374. build.WithFile("foo", "hello world"),
  5375. )).Assert(c, icmd.Expected{
  5376. ExitCode: 0,
  5377. Out: "hello world",
  5378. })
  5379. }
  5380. func (s *DockerSuite) TestBuildIntermediateTarget(c *check.C) {
  5381. dockerfile := `
  5382. FROM busybox AS build-env
  5383. CMD ["/dev"]
  5384. FROM busybox
  5385. CMD ["/dist"]
  5386. `
  5387. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  5388. defer ctx.Close()
  5389. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5390. cli.WithFlags("--target", "build-env"))
  5391. //res := inspectFieldJSON(c, "build1", "Config.Cmd")
  5392. res := cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5393. c.Assert(strings.TrimSpace(res), checker.Equals, `["/dev"]`)
  5394. result := cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx),
  5395. cli.WithFlags("--target", "nosuchtarget"))
  5396. result.Assert(c, icmd.Expected{
  5397. ExitCode: 1,
  5398. Err: "failed to reach build target",
  5399. })
  5400. }
  5401. // TestBuildOpaqueDirectory tests that a build succeeds which
  5402. // creates opaque directories.
  5403. // See https://github.com/docker/docker/issues/25244
  5404. func (s *DockerSuite) TestBuildOpaqueDirectory(c *check.C) {
  5405. testRequires(c, DaemonIsLinux)
  5406. dockerFile := `
  5407. FROM busybox
  5408. RUN mkdir /dir1 && touch /dir1/f1
  5409. RUN rm -rf /dir1 && mkdir /dir1 && touch /dir1/f2
  5410. RUN touch /dir1/f3
  5411. RUN [ -f /dir1/f2 ]
  5412. `
  5413. // Test that build succeeds, last command fails if opaque directory
  5414. // was not handled correctly
  5415. buildImageSuccessfully(c, "testopaquedirectory", build.WithDockerfile(dockerFile))
  5416. }
  5417. // Windows test for USER in dockerfile
  5418. func (s *DockerSuite) TestBuildWindowsUser(c *check.C) {
  5419. testRequires(c, DaemonIsWindows)
  5420. name := "testbuildwindowsuser"
  5421. buildImage(name, build.WithDockerfile(`FROM `+testEnv.MinimalBaseImage()+`
  5422. RUN net user user /add
  5423. USER user
  5424. RUN set username
  5425. `)).Assert(c, icmd.Expected{
  5426. Out: "USERNAME=user",
  5427. })
  5428. }
  5429. // Verifies if COPY file . when WORKDIR is set to a non-existing directory,
  5430. // the directory is created and the file is copied into the directory,
  5431. // as opposed to the file being copied as a file with the name of the
  5432. // directory. Fix for 27545 (found on Windows, but regression good for Linux too).
  5433. // Note 27545 was reverted in 28505, but a new fix was added subsequently in 28514.
  5434. func (s *DockerSuite) TestBuildCopyFileDotWithWorkdir(c *check.C) {
  5435. name := "testbuildcopyfiledotwithworkdir"
  5436. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  5437. build.WithFile("Dockerfile", `FROM busybox
  5438. WORKDIR /foo
  5439. COPY file .
  5440. RUN ["cat", "/foo/file"]
  5441. `),
  5442. build.WithFile("file", "content"),
  5443. ))
  5444. }
  5445. // Case-insensitive environment variables on Windows
  5446. func (s *DockerSuite) TestBuildWindowsEnvCaseInsensitive(c *check.C) {
  5447. testRequires(c, DaemonIsWindows)
  5448. name := "testbuildwindowsenvcaseinsensitive"
  5449. buildImageSuccessfully(c, name, build.WithDockerfile(`
  5450. FROM `+testEnv.MinimalBaseImage()+`
  5451. ENV FOO=bar foo=baz
  5452. `))
  5453. res := inspectFieldJSON(c, name, "Config.Env")
  5454. if res != `["foo=baz"]` { // Should not have FOO=bar in it - takes the last one processed. And only one entry as deduped.
  5455. c.Fatalf("Case insensitive environment variables on Windows failed. Got %s", res)
  5456. }
  5457. }
  5458. // Test case for 29667
  5459. func (s *DockerSuite) TestBuildWorkdirImageCmd(c *check.C) {
  5460. image := "testworkdirimagecmd"
  5461. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5462. FROM busybox
  5463. WORKDIR /foo/bar
  5464. `))
  5465. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  5466. // The Windows busybox image has a blank `cmd`
  5467. lookingFor := `["sh"]`
  5468. if testEnv.DaemonPlatform() == "windows" {
  5469. lookingFor = "null"
  5470. }
  5471. c.Assert(strings.TrimSpace(out), checker.Equals, lookingFor)
  5472. image = "testworkdirlabelimagecmd"
  5473. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5474. FROM busybox
  5475. WORKDIR /foo/bar
  5476. LABEL a=b
  5477. `))
  5478. out, _ = dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  5479. c.Assert(strings.TrimSpace(out), checker.Equals, lookingFor)
  5480. }
  5481. // Test case for 28902/28909
  5482. func (s *DockerSuite) TestBuildWorkdirCmd(c *check.C) {
  5483. testRequires(c, DaemonIsLinux)
  5484. name := "testbuildworkdircmd"
  5485. dockerFile := `
  5486. FROM busybox
  5487. WORKDIR /
  5488. `
  5489. buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
  5490. result := buildImage(name, build.WithDockerfile(dockerFile))
  5491. result.Assert(c, icmd.Success)
  5492. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 1)
  5493. }
  5494. // FIXME(vdemeester) should be a unit test
  5495. func (s *DockerSuite) TestBuildLineErrorOnBuild(c *check.C) {
  5496. name := "test_build_line_error_onbuild"
  5497. buildImage(name, build.WithDockerfile(`FROM busybox
  5498. ONBUILD
  5499. `)).Assert(c, icmd.Expected{
  5500. ExitCode: 1,
  5501. Err: "Dockerfile parse error line 2: ONBUILD requires at least one argument",
  5502. })
  5503. }
  5504. // FIXME(vdemeester) should be a unit test
  5505. func (s *DockerSuite) TestBuildLineErrorUnknownInstruction(c *check.C) {
  5506. name := "test_build_line_error_unknown_instruction"
  5507. cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox
  5508. RUN echo hello world
  5509. NOINSTRUCTION echo ba
  5510. RUN echo hello
  5511. ERROR
  5512. `)).Assert(c, icmd.Expected{
  5513. ExitCode: 1,
  5514. Err: "Dockerfile parse error line 3: unknown instruction: NOINSTRUCTION",
  5515. })
  5516. }
  5517. // FIXME(vdemeester) should be a unit test
  5518. func (s *DockerSuite) TestBuildLineErrorWithEmptyLines(c *check.C) {
  5519. name := "test_build_line_error_with_empty_lines"
  5520. cli.Docker(cli.Build(name), build.WithDockerfile(`
  5521. FROM busybox
  5522. RUN echo hello world
  5523. NOINSTRUCTION echo ba
  5524. CMD ["/bin/init"]
  5525. `)).Assert(c, icmd.Expected{
  5526. ExitCode: 1,
  5527. Err: "Dockerfile parse error line 6: unknown instruction: NOINSTRUCTION",
  5528. })
  5529. }
  5530. // FIXME(vdemeester) should be a unit test
  5531. func (s *DockerSuite) TestBuildLineErrorWithComments(c *check.C) {
  5532. name := "test_build_line_error_with_comments"
  5533. cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox
  5534. # This will print hello world
  5535. # and then ba
  5536. RUN echo hello world
  5537. NOINSTRUCTION echo ba
  5538. `)).Assert(c, icmd.Expected{
  5539. ExitCode: 1,
  5540. Err: "Dockerfile parse error line 5: unknown instruction: NOINSTRUCTION",
  5541. })
  5542. }
  5543. // #31957
  5544. func (s *DockerSuite) TestBuildSetCommandWithDefinedShell(c *check.C) {
  5545. buildImageSuccessfully(c, "build1", build.WithDockerfile(`
  5546. FROM busybox
  5547. SHELL ["/bin/sh", "-c"]
  5548. `))
  5549. buildImageSuccessfully(c, "build2", build.WithDockerfile(`
  5550. FROM build1
  5551. CMD echo foo
  5552. `))
  5553. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", "build2")
  5554. c.Assert(strings.TrimSpace(out), checker.Equals, `["/bin/sh","-c","echo foo"]`)
  5555. }