docker_cli_build_test.go 195 KB

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