docker_cli_build_test.go 203 KB

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