docker automation with dockerfiles (linux) - github pages · docker automation with dockerfiles...

59
Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom Linux-based Docker image from a Dockerfile.

Upload: trankien

Post on 20-Jan-2019

328 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

DockerAutomationwithDockerfiles(Linux)Friday,August4,20174:52PM

LearnhowtoautomatethebuildofacustomLinux-basedDockerimagefromaDockerfile.

Page 2: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

ThisworkshopwillshowyouhowtoautomatethebuildingandconfiguringofaLinux-basedDockerimagebyutilizingDockerfiles.YouwillconstructaDockerfilebymimickingaproductionenvironmentconfiguration.You'llalsolearnsomeoftheoptionsforaDockerfileconfiguration.

WhatYouWillLearnConstructingaDockerfileforLinux-basedBuildsVariousDockerfileConfigurationOptionsBuildingaDockerImagefromaDockerfile

IdealAudienceITManagersDevelopersandSoftwareArchitectsConfigurationandChangeManagersDevOpsEngineers

Page 3: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

ThisworkshopwillshowyouhowtoautomatethebuildingandconfiguringofaLinux-basedDockerimagebyutilizingDockerfiles.YouwillconstructaDockerfilebymimickingaproductionenvironmentconfiguration.You'llalsolearnsomeoftheoptionsforaDockerfileconfiguration.

TimeEstimate:45minutes

Overview

Page 4: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

SetupRequirementsThefollowingworkshopwillrequirethatyouuseaTelnet/SSHclientinordertoconnecttoaremotemachine.IfyoudonothaveaSSHclient,thenPuTTYwillworkfine.Dependingonyourenvironment,downloadtheexecutableinastandalonefile(.EXE)oraninstallablepackage(.MSI),eitherina32-bitor64-bit.

AdditionalRequirementsForthefollowingworkshop,youwillneedasubscription(trialorpaid)toMicrosoftAzure.Pleaseseethenextpageforhowtocreateatrialsubscription,ifnecessary.

Requirements

Page 5: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

AzureWeneedanactiveAzuresubscriptioninordertoperformthisworkshop.Thereareafewwaystoaccomplishthis.IfyoualreadyhaveanactiveAzuresubscription,youcanskiptheremainderofthispage.Otherwise,you'lleitherneedtouseanAzurePassorcreateatrialaccount.Theinstructionsforbotharebelow.

AzurePassIfyou'vebeenprovidedwithavoucher,formallyknownasanAzurePass,thenyoucanusethattocreateasubscription.InordertousetheAzurePass,directyourbrowsertohttps://www.microsoftazurepass.comand,followingtheprompts,usethecodeprovidedtocreateyoursubscription.

TrialSubscriptionDirectyourbrowsertohttps://azure.microsoft.com/en-us/free/andbeginbyclickingonthegreenbuttonthatreadsStartfree.

1. Inthefirstsection,completetheforminitsentirety.Makesureyouuseyourrealemailaddressfortheimportantnotifications.

2. Inthesecondsection,enterarealmobilephonenumbertoreceiveatextverificationnumber.Clicksendmessageandre-typethereceivedcode.

3. Enteravalidcreditcardnumber.NOTE:Youwillnotbecharged.Thisisforverificationofidentityonlyinordertocomplywithfederalregulations.Youraccountstatementmayseeatemporaryholdof$1.00fromMicrosoft,but,again,thisisforverificationonlyandwill"falloff"youraccountwithin2-3bankingdays.

4. AgreetoMicrosoft'sTermsandConditionsandclickSignUp.

Thismaytakeaminuteortwo,butyoushouldseeawelcomescreeninformingyouthatyoursubscriptionisready.LiketheOffice365trialabove,theAzuresubscriptionisgoodforupto$200ofresourcesfor30days.After30days,yoursubscription(andresources)willbesuspendedunlessyouconvertyourtrialsubscriptiontoapaidone.And,shouldyouchoosetodoso,youcanelecttouseadifferentcreditcardthantheoneyoujustentered.

AzureRegistration

Page 6: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Congratulations!You'venowcreatedanOffice365tenant;anAzuretenantandsubscription;and,havelinkedthetwotogether.

Page 7: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewThisworkshopcontainstworoutes-oneforconstructingaDockerfileinUbuntuandanotherforCentOS.Thestepsareprimarilythesame,buttheseparatesectionswereprovidedtominimizeconfusion.

Inthisworkshop,youwillfirstbuilda'production'webserverenvironmentontheactualvirtualmachine.YouwillthentakethosesamestepsandreplicatetheminaDockerfileforbuildingacontainerizedversionofyourVM.

Thestepsinthisworkshoparenotextremelytedious.However,theyarebrokenoutintoindividualpagesforacoupleofreasons.First,itistosimplifytheprocessandaidyouinyourcomprehension.Second,itisforthepurposeofyouseeingtheactualstepsofbuildingtheproductionvirtualmachinesothatyoucomprehendwhatyouaredoingasyouaddeachsteptotheDockerfile.

Introduction

Page 8: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

ObjectiveAllofourworkinthisworkshop,withtheexceptionofthesmallAzureconfigurationattheend,willbeperformedonasinglevirtualmachine.Let'sgetstartedcreatingthatVM.

CreateaResourceGroupInordertocreateresources,weneedaResourceGrouptoplacethemin.

1. Ifyouarenottherealready,goaheadandclickontheResourceGroups intheAzurePortaltoopentheResourceGroupsblade.

2. AtthetopoftheResourceGroupsblade,clickonAdd .Thiswillopenapanelthatasksforsomebasicconfigurationsettings.

3. Completetheconfigurationsettingswiththefollowing:

Resourcegroupname:azworkshops_dockerfile_ubuntu_demoSubscription:<chooseyoursubscription>Resourcegrouplocation:<chooseyourlocation>

4. <Optional>CheckPintodashboardatthebottomofthepanel.

5. ClickCreate.

6. Itshouldonlytakeasecondfortheresourcegrouptobecreated.Onceyouclickcreate,theconfigurationpanelclosesandreturnsyoutothelistofavailableresourcegroups.Yourrecentlycreatedgroupmaynotbevisibleinthelist.ClickingonRefresh atthetopoftheResourceGroupsbladeshoulddisplayyournewresourcegroup.

NOTE:Whenyoucreatearesourcegroup,youarepromptedtochoosealocation.Additionally,asyoucreateindividualresources,youwillalsobepromptedtochooselocations.Thelocationofresourcegroupsandtheirresourcescanbedifferent.Thisisbecauseresourcegroupsstoremetadatadescribingtheircontainedresources;and,duetosometypesofcompliancethatyourcompanymayadhereto,youmayneedtostorethatmetadatainadifferentlocationthantheresourcesthemselves.Forexample,ifyouareaUS-basedcompany,youmaychoosetokeepthemetadatastate-sidewhilecreatingresourcesinforeignregionstoreducelatencyfortheend-user.

CreateVirtualMachine

Page 9: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

CreateaVirtualMachineNowthatwehaveanavailableresourcegroup,let'screatetheactualUbuntuserver.

1. Ifyouarenottherealready,goaheadandnavigatetotheazworkshops_dockerfile_ubuntu_demoresourcegroup.

2. Atthetopofthebladeforourgroup,clickonAdd .ThiswilldisplaythebladefortheAzureMarketplaceallowingyoutodeployanumberofdifferentsolutions.

3. WeareinterestedindeployinganUbuntuserver.Therefore,intheSearchEverythingbox,typeinUbuntuServer.Thiswilldisplayacoupleofdifferentversions.SincewewanttodeploythelateststableversionofUbuntu,fromthedisplayedoptions,chooseUbuntuServer16.04LTS.

4. Thiswilldisplayabladeprovidingmoreinformationabouttheserverwehavechosen.Tocontinuecreatingtheserver,chooseCreate.

5. Wearenowpromptedwithsomeconfigurationoptions.Thereare3sectionsweneedtocompleteandthelastsectionisasummaryofourchosenoptions.

1. Basics

Name:dockerfile-ubuntuVMdisktype:SSDUsername:localadminAuthenticationtype:Password(NOTE:YoucanchooseSSHifyouarefamiliarwithhowtosetthisup.Ifyouarenot,wewilldothisinalaterworkshop.However,forthisworkshop,Passwordauthenticationissufficient.)Password:Pass@word1234Confirmpassword:<sameasabove>Subscription:<chooseyoursubscription>Resourcegroup:Useexisting-azworkshops_dockerfile_ubuntu_demoLocation:<choosealocation>

2. Size

DS1_V23. Settings

Usemanageddisks:No

Storageaccount:(clickonit&CreateNew)

Page 10: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Name:dfubuntudata<randomnumber>(ex.dfubuntudata123456)(NOTE:Thisnamemustbegloballyunique,soitcannotalreadybeused.)Performance:PremiumReplication:Locally-redundantstorage(LRS)

Virtualnetwork:<acceptdefault>(e.g.(new)azworkshops_dockerfile_ubuntu_demo-vnet)

Subnet:<acceptdefault>(e.g.default(172.16.1.0/24))

PublicIPaddress:<acceptdefault>(e.g.(new)dockerfile-ubuntu-ip)

Networksecuritygroup(firewall):<acceptdefault>(e.g.(new)dockerfile-ubuntu-nsg)

Extensions:Noextensions

Availabilityset:None

Bootdiagnostics:Enabled

GuestOSdiagnostics:Disabled

Diagnosticsstorageaccount:(clickonit&CreateNew)

Name:dfubuntudiags<randomnumber>(ex.dfubuntudiags123456)Performance:StandardReplication:Locally-redundantstorage(LRS)

4. Summary(justclickOKtocontinue)

Thismachineisrelativelysmall,butwithcontainers,itcanstilldeliversomeprettyimpressiveperformance.Oncescheduled,itmaytakeaminuteortwoforthemachinetobecreatedbyAzure.Onceithasbeencreated,Azureshouldopenthemachine'sstatusbladeautomatically.

ConnecttotheVirtualMachineOnceyourmachinehasbeencreated,wecanremotelyconnecttoitusingsecureshell(SSH).TheseinstructionsassumethatyoudonothavestrongfamiliaritywithSSHand/orthatyouhavenobuilt-inSSHclientinyourlocalOS.Forthisreason,wewillbeusingthePuTTYclientwedownloadedearlierfortheworkshop.However,ifyouaremorecomfortableusinganotherTelnet/SSHclient(e.g.MacOS,Linux,WindowsSub-Layer(WSL)),pleasefeelfreetouseit.

GetPublicIP1. Ifitisnotalreadyopen,navigatetotheOverviewbladeofyournewlycreatedvirtual

machine.

Page 11: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

2. Inthetopsectionoftheblade,intherightcolumn,youshouldseeaPublicIPaddresslisted.

3. CopytheIPaddress.

ConnectwithSSH1. OpenPuTTY.

2. Intheconfigurationwindow:

Hostname:<IPaddressfrompreviousstep>Port:22Connectiontype:SSH

Page 12: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

3. ClickOpen

4. Inthesecurityprompt,clickYes.

Page 13: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

5. YouwillthenconnecttotheremoteUbuntuserver.

6. Entertheusernameandpasswordfromabove(e.g.localadminandPass@word1234,respectively).

7. Youshouldthenseethe bash prompt:

localadmin@dockerfile-ubuntu:~$

Congratulations.YouhavesuccessfullycreatedandconnectedtoyourremoteUbuntuserverinAzure.YouarenowreadytoinstalltheDockerruntime.

Page 14: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewWehavejustcreatedourUbuntuserver.WenowneedtoapplyanyavailablesystemupdatesalongwithinstallingandconfiguringDockertobeginworkingwithcontainers.

InstallUpdatesJustlikeanyotheroperatingsystem,updatesareperiodicallyreleasedtosupportnewfeaturesandpatchanypotentialsecuritythreats.Wewillapplytheupdatesfirst.

1. Ifyouhavenotalready,connecttoyourremoteUbuntuserverandlogin.

2. Fromtheloginprompt,youmayseeastatusofavailableupdates.(Ifnot,don'tbetooalarmed-continuewiththesestepsanywayjusttobesure.)

3. Firstweneedtoensureourlistofsourcesforoursystemupdatesareup-to-date.Fromthe

InstallUpdates

Page 15: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

commandprompt,typethefollowing:

sudoapt-getupdate

4. Nowwecaninstallupdates.Fromthecommandprompt,typethefollowingtoautomaticallyinstallallavailableupdates:

sudoapt-getupgrade-y

5. Dependingonthenumberandsizeofavailableupdates,thisprocessmaytakeafewminutes.Nowwouldbeagoodtimetotakeabreak.

Page 16: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewInthisstep,wearegoingtoinstallDocker.Thisisoneofthestepsthatwillactuallynotbeperformedinsideofthecontainerimage.But,ofcourse,weneedDockeronthehostinordertoruncontainers.

InstallDockerWenowhaveanupdatedUbuntuoperatingsystem.WearereadytoinstallDocker.

1. WeneedtoaddtheGPGkeyfortheofficialDockerrepositorytothesystembecauseinthenextstepwewanttodownloadtheDocker'installer'directlyfromDockerandnotthedefaultUbuntuserverstoensurewegetthelatestversionoftheengine.Fromthecommandprompt,typethefollowing:

sudoapt-keyadv--keyserverhkp://p80.pool.sks-keyservers.net:80--recv-keys58118E89F3A912897C070ADBF76221572C52609D

Copy&PasteYoucanpastethisintoPuTTYbyright-clickingtheterminalscreen.

2. Now,weneedtotellUbuntuwheretheDockerrepositoryislocated.Fromthecommandprompt,type(orpaste)thefollowing:

sudoapt-add-repository'debhttps://apt.dockerproject.org/repoubuntu-xenialmain'

3. Onceagain,updatethepackagedatabasewiththeDockerpackagesfromthenewlyaddedrepository:

InstallDocker

Page 17: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

sudoapt-getupdate

4. MakesureyouareabouttoinstallfromtheDockerrepositoryinsteadofthedefaultUbunturepository:

apt-cachepolicydocker-engine

5. Youshouldseeoutputsimilartothefollowing(noticethat docker-engine isnotinstalledandthe docker-engine versionnumbermightbedifferent):

docker-engine:Installed:(none)Candidate:1.11.1-0~xenialVersiontable:1.11.1-0~xenial500500https://apt.dockerproject.org/repoubuntu-xenial/mainamd64Packages1.11.0-0~xenial500500https://apt.dockerproject.org/repoubuntu-xenial/mainamd64Packages

6. Finally,installDocker:

sudoapt-getinstall-ydocker-engine

7. InstallingtheDockerenginemaytakeanadditionalminuteortwo.

AdditionalConfigurationTosimplifyrunningandmanagingDocker,there'ssomeadditionalconfigurationthatweneedtoimplement.Whilethissectionisoptional,itisrecommendedtomakemanagingDockermucheasier.

EnsureDockerEngineisRunning1. Fromthecommandprompt,type:

sudosystemctlstatusdocker

2. Youshouldseesomethingsimilartothefollowing:

Page 18: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

●docker.service-DockerApplicationContainerEngineLoaded:loaded(/lib/systemd/system/docker.service;enabled;vendorpreset:enabled)Active:active(running)sinceSun2017-06-0422:38:16UTC;4min10sagoDocs:https://docs.docker.comMainPID:32844(dockerd)

3. Becausetheserviceisrunning,wecannowusethe docker commandlaterinthisworkshop.

EnableDockerEngineatStartupLet'smakesuretheDockerengineisconfiguredtorunonsystemstartup(andreboot).

1. Fromthecommandprompt,type:

sudosystemctlenabledocker

2. Youshouldseesomethingsimilartothefollowing:

Synchronizingstateofdocker.servicewithSysVinitwith/lib/systemd/systemd-sysv-install...Executing/lib/systemd/systemd-sysv-installenabledocker

ElevateYourPrivilegesBedefault,runningthe docker commandrequiresrootprivileges-thatis,youhavetoprefixthecommandwith sudo .Itcanalsoberunbyauserinthedockergroup,whichisautomaticallycreatedduringtheinstallofDocker.Ifyouattempttorunthe docker commandwithoutprefixingitwith sudo orwithoutbeinginthedockergroup,you'llgetanoutputlikethefollowing:

docker:CannotconnecttotheDockerdaemon.Isthedockerdaemonrunningonthishost?.See'dockerrun--help'.

Toavoidtyping sudo wheneveryourunthe docker command,addyourusernametothedockergroup:

sudousermod-aGdocker$(whoami)

Page 19: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Youwillthenneedtologoutandbackinforthechangestotakeeffect.

Ifyouneedtoaddanotherusertothe docker group(oneinwhichyouhavenotloggedinascurrently),simplyprovidethatusernameexplicitlyinthecommand:

sudousermod-aGdocker<username>

You'vesuccessfullyinstalledtheDockerengine.YouhavealsoconfiguredittorunatstartupandhaveaddedyourselftotheDockergroupsothatyouhavesufficientprivilegesforrunningDocker.

Page 20: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewNowthatwehavethehostmachineconfiguredforDocker,we'regoingtobeginbuildingourwebserver.Keepinmindthatthisvirtualmachineisservingtwopurposes:1)ourDockerhost;and,2)ourtemporarywebserveruntilourimageisbuilt.

InstallNode.jsNode.jsisaJavaScriptexecutionenginethatallowsustowriteserver-sideJavaScriptandutilizeitlikeanyotherexecutablefile.WithNode.js,wewillhostaverysimplewebserver.

DownloadandInstallNode.jsRuntimeTheNode.jsruntimeiswhatisresponsibleforhostingandexecutingourJavaScript.

Fromtheterminalprompt,type:

sudoapt-getinstall-ynodejs

DownloadandInstallNPMNPMisanabbreviationforNodePackageManager.NPMallowsustoinstallNode.jsdependenciesforourapplications.

Attheprompt,type:

sudoapt-getinstall-ynpm

CreateSymbolicLinkInLinux,asymboliclinkisnothingmorethana'virtualpointer'toafile.It'sawaytogiveafileanalias.Forus,wegoingtodotwothingswithasymboliclink.First,we'regoingtoget nodejs analias.Second,we'regoingtomaketheexecutablegloballyavailablesothatitcanbecalledfromanyfolder.

Attheprompt,enter:

InstallNode.js

Page 21: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

sudoln-s/usr/bin/nodejs/usr/bin/node

Thiswillcreateapointercalled node thatpointsto nodejs .WecanthenexecuteNode.jsviaeithercommand.However, node isthecommonnametouse.

VerifyInstallationLet'smakesureourinstallationwassuccessful.

Attheprompt,type:

node-vnpm-v

Youshouldreceiveversionnumbersforbothcommands.

AddBuildDependenciesSomeNode.jslibrarieshaveoutsidedependenciesthataren'tnecessarilyinstalledinUbuntubydefault.Let'sinstallthosenow.

Attheterminalprompt,type:

sudoapt-getinstallbuild-essential

We'venowsuccessfullycompletedtheinstallationofNode.jsandtheNodePackageManager.

Page 22: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewWe'vedownloadedmostofourdependencies.InthisstepwewilldownloadademowebsitefromGitHub,aremotesourcecoderepository.

ClonetheWebsite'Cloning'isthemethodinwhichyoudownloadaremoterepositorytoyourlocalmachine.Wearegoingtoclonethedemowebsitetothedefaultwebhostingfolderonoursystem.

Fromthecommandprompt,typethefollowing:

sudogitclonehttps://github.com/AzureWorkshops/samples-simple-nodejs-website.git/var/www

Youshouldseesomethingsimilartothefollowing:

Cloninginto'/var/www'...remote:Countingobjects:9,done.remote:Compressingobjects:100%(7/7),done.remote:Total9(delta0),reused6(delta0),pack-reused0Unpackingobjects:100%(9/9),done.Checkingconnectivity...done.

Thewebsitesourcecodehasnowbeendownloaded.

DownloadSampleWebsite

Page 23: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewEventhoughwe'veinstalledsystemdependencies,ourwebsitehasacoupleoflibrarydependenciesthatweneedtoinstall.We'llalsoensurethatthewebsiteisfunctioningcorrectly,beforeweproceedtobuildourDockerfile.

DownloadWebsiteDependenciesWe'llneedtoenterintothewebsite'smainfoldertoinstallthedependencies.

Typethefollowingintotheterminal:

cd/var/wwwsudonpmi

Youshouldseeanumberofprogressbarsdisplayedasdependenciesaredownloadedfollowedbywhatlookslikeafolderhierarchy.

TestOurWebsiteThefirstthingweneedtodoisrunourwebhostingserverwhichishandledbyNode.js.Ifweranthisnormallyfromthecommand-line,itwouldblockallotherinput.Wewouldthenhavetoopenasecondterminaltotestourwebsite.Instead,we'regoingtorunourwebserverinthebackgroundasadetachedprocess.

Attheterminalprompt,type:

sudonodeindex.js&

NOTE:Theampersandattheendofthelineinstructsthesystemtorunthepreceedingcommandinthebackground.WhenweconstructourDockerfile,wewillomittheampersandsothattheprocessrunsintheforegroundandcreatesalong-runningprocessthatkeepsourcontainer'alive'.

DownloadDependencies

Page 24: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Whenyourunthiscommand,anumberisoutputtedtothescreen.Thisnumberreferstoaprocessid(pid).Keepthisnumberhandyaswe'lluseitbelowto'kill'thebackgroundprocess.

Additionally,youshouldseeamessagestatingthatour'serverislisteningon8080'.

Testthatthewebserverisreturningoursitebytypingthefollowing:

curlhttp://localhost:8080/

Ifallissuccessful,youshouldreceivesomeHTMLsourcecodeback.

StoptheBackgroundProcessWedon'tneedthewebsiterunninganylongernowthatweknowitworks.Additionally,ifwekeptitrunning,it'suseoftheport8080couldcreatepotentialconflictsifanotherservice(e.g.container)isneedingthatport.

Referringtotheprocessid(pid)above,executethefollowingcommandwithyourid:

sudokill<pid>

Ifsuccessful,youshouldseethefollowingconfirmationmessage:

[1]+Donesudonodeindex.js

Buildingourwebserverhasbeensuccessful.Wearenowreadytomoveforwardandreplicateourworkinbuildingoutanimage.

Page 25: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewBasedonmostoftheprevioussteps,wearereadytobuildourDockerfile.Wewillmimicthosestepsforautomatingourimageconstruction.

ReviewInpreparationofwritingourDockerfile,let'sreviewallthestepswe'veperformeduptothispoint.

1. InstallthelatestversionofUbuntu2. Updatethepackagereferences3. Installthelatestpackages4. InstallandconfigureDocker5. InstallNode.js6. InstallNodePackageManager(NPM)7. Download(clone)thesamplewebsite8. Downloadwebsitedependencies9. Runthewebserver

Asareminder,sinceweareconstructinganimage,wecanignorestep4.Wewon'tneedDockerinstalledinsideoftheimage.

CreatetheDockerfileLet'sgoaheadandcreatetheDockerfilecontents.We'llthenexamineeachlinebelow.

1. Returntoyourhomefolderbytypingattheterminalprompt, cd~ .

2. CreateaDockerfileusingthe nano texteditorbytypingthefollowing: nanoDockerfile .NanoisreminiscentoftheoldDOSeditor.Ofcourse,youcanyou vim insteadifyouarecomfortableindoingso.NOTE'Dockerfile'iscase-sensitive.

3. Enterthefollowingwithoutthelinenumbers.Thelinenumbersareprovidedforreferencebelow.

ConstructDockerfile

Page 26: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

1FROMubuntu:latest2MAINTAINERYourName<[email protected]>34RUNapt-getupdate5RUNapt-getupgrade6RUNapt-getinstall-ynodejs7RUNapt-getinstall-ynpm8RUNln-s/usr/bin/nodejs/usr/bin/node9RUNapt-getinstall-ygit1011RUNgitclonehttps://github.com/AzureWorkshops/samples-simple-nodejs-website.git/var/www12WORKDIR/var/www13RUNnpmi1415EXPOSE80801617CMDnode/var/www/index.js

4. Tosave,Ctrl+O

5. Toexit,Ctrl+X

ExplanationFirst,ifyourememberfromtheprevioussteps,weprependedeachcommandwith sudo toallowthecommandtobeexecutedwithelevatedprivileges.Bydefault,allDockerimagesexecuteundertheidentityofthebuilt-insuperuseraccount root .Therefore,wecanomitthe sudo .

Line1:Specifiesthebaseimage,includingthetag,withwhichwe'restarting.Inourcase,weareusingtheminimalUbuntuOSasthebaseimage.

Line2:Specifiestheowneroftheimagewiththeiremailaddress.

Lines4-8:ThecommandsweexecutedearlierinthisworkshopthatupdatethesystemandinstallsNode.js.

Line9:Wewerenotrequiredtoinstall git inourvirtualmachine.However,becausethebaseimageofUbuntudoesn'tinclude git bydefault,weneedtoinstallitmanually.

Line11:Downloads(clones)thesamplewebsiteintothe /var/www localfolder.

Line12: WORKDIR ishowyouchangethecurrentdirectory(comparedto cd )inaDockerfile.Wearechangingtothewebsitehomedirectory.

Line13:Installthewebsite'sdependencies.

Line15:Ourwebsiteserverisprogrammedtouseport8080.Therefore,similartoafirewallintheimage,weopen,orexpose,theporttotheoutsidehost.Wewillbindtothisopenportlaterwhenwerunacontainerbasedonthisimage.

Line17:Thisstartsourwebserver.Wecouldhaveusedthe RUN directive,butthe CMD directiveis

Page 27: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Line17:Thisstartsourwebserver.Wecouldhaveusedthe RUN directive,butthe CMD directiveisdesignedtoexecuteourlong-runningprocess.While,technically,wecouldhavemultiple CMD linesintheDockerfile,theDockerbuildwillignoreall CMD linesexceptthelastone.

That'sit!That'sallthereistocreatingaDockerfile.

Page 28: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewNowthatwehaveourDockerfile,let'sbuildourimagefromit.

BuildtheDockerImageOncewehaveourDockerfile,buildingtheimageisprettysimple.

Fromthecommandprompt,type cd~ toensureyouareinyourhomefolder,thentypethefollowing:

dockerbuild-ttest/simpleweb.

Thiswillbuildanimageusing test/simpleweb astherepositoryname.TheperiodattheendspecifiesthepathwhereDockercanfindtheDockerfile.

WatchhowDockerwillstepthroughourDockerfiletobuildourimage.KeepinmindwhileyouwatchthisprocessthateachstepinourDockerfileconstitutesalayerinourimage.We'llseetheresultsofthisbelow.

CheckYourImagesFromthecommandprompt,typethefollowing:

dockerimages

Youshouldseesomethingsimilarto:

BuildImage

Page 29: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

REPOSITORYTAGIMAGEIDCREATEDSIZEtest/simpleweblatest0bfaff1a6a2a41secondsago486MBubuntulatest7b9b13f7b9c04daysago118MB

Ourimagehasbeenbuiltusingthespecifiedrepositoryname.You'llalsonoticethatthe ubuntuimagehasbeendownloaded.ThisisbecausethebuildprocessrequiredUbuntuinordertobuildourimage.Nowthatourimagehasbeenbuilt,youcoulddeletethe ubuntu imageifyouwantedto.Finally,whenlookingattheimagesizes,you'llseethatourimageis4timeslargerdueinstallationofNode.js,Git,andtheotherdependencies.Intheend,however,500MBisstillnotthatlarge.

ViewImageHistoryWhatifwewantedtoseehowourimageisconstructed?Or,whatifwewantedtoseeexactlyhowmuchdiskspaceeachlayerofourimagerequired?Wecouldfindthisoutbycheckingtheimage'shistory.

dockerimagehistorytest/simpleweb

Whenyouruntheabovecommand,youseeeachcommandalongfromourDockerfilealongwithit'slayeridandthespacerequirements,ifany.

We'venowbuiltacustomimagebasedonaDockerfile.Wecanuseourcustomimagetodeploycontainerslocally.Or,wecoulduploadourimagetoacentralrepositorysothatotherscouldleverageourimage'sfunctionality.

Page 30: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewOurcustomimagehasnowbeencreatedandiscurrentlysittinginourlocalrepository.Let'sinstantiateacontainerbasedonthatimage.

StartaContainerTostartacontainerfromourimageisverysimple.Theonlythingweneedtorememberisexposingtheinternalporttothehost.

dockerrun-d-p8080:8080--name'web_8080'test/simplewebdockerrun-d-p8081:8080--name'web_8081'test/simplewebdockerrun-d-p8082:8080--name'web_8082'test/simpleweb

We'vestarted3separatedinstancesofourwebserver.We'veboundthewebserver'sinternalport8080tothreehostports(e.g8080-8082).We'vealsosuppliedmeaningfulnamestoourcontainers.Wecanreferencethosecontainersbythenameswe'vespecifiedforeasiermanagement.Forexample,wecanrestartorstopacontainerusingit'snameinsteadofthecontainerid.

Checktherunningimages:

dockerps

Youshouldseesomethinglikethefollowing:

DeployContainer

Page 31: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES3d1929c8e1b5test/simpleweb"/bin/sh-c'node..."3secondsagoUp2seconds0.0.0.0:8082->8080/tcpweb_8082323a65fa5143test/simpleweb"/bin/sh-c'node..."11secondsagoUp10seconds0.0.0.0:8081->8080/tcpweb_80817d4fee5c8f89test/simpleweb"/bin/sh-c'node..."AboutaminuteagoUp59seconds0.0.0.0:8080->8080/tcpweb_8080

Noticethatallthreecontainersarerunning,but,aswe'vespecified,areboundtodifferentportsandhavecustomnames.

Forpractice,restart web_8081 :

dockerrestartweb_8081

Executingthecommand,maytakeasecond.Afteritcompletes,checktherunningimagesagain.Youshouldnowseethattheuptimefor web_8081 islessthantheothertwocontainers.

Weareleftwithsuccessfullycreatingthreecontainerinstancesrunningourcustomimage.

Page 32: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewThefinalpartofthisworkshopistopracticeexposingacontainerserviceoutsideofAzure.We'regoingtocreateasimplewebserverandaccessitfromourlocalmachine.

NetworkSecurityGroup(NSG)Nowthatourwebserverisrunning,let'smakeitavailableoutsideofAzure.

WhenwecreatedourUbuntuvirtualmachine,weacceptedthedefaults,includingthedefaultsettingsforourNSG.ThedefaultsettingsonlyallowedSSH(port22)access.WeneedtoaddaruletoourNSGtoallowHTTPtrafficoverourthreeports(8080-8082)sothatwecanaccessallthreecontainers.

1. Ifyouarenotstillthere,gobacktotheAzureportalandnavigatetothesettingsofyourUbuntuvirtualmachine.

2. Intheleftmenu,clickonNetworkinterfaces .

3. ThiswillopentheNetworkInterfacesbladeforyourUbuntuvirtualmachine.Clickonthesingular,listedinterface.

4. Intheleftmenu,clickonNetworksecuritygroup .

5. ThiswilllistthecurrentlyactiveNSG.Inourcase,itshouldbetheNSGthatwascreatedwithourvirtualmachine-dockerfile-ubuntu-nsg.ClickontheNSG(NOTE:ClickontheactualNSGlink,NOTonEdit).

6. Intheleftmenu,clickonInboundsecurityroles .

7. Atthetopoftheblade,clickAdd .

8. Enterthefollowingconfiguration:

Name:allow-httpPriority:1010Source:AnyService:CustomProtocol:Any

ExposeSiteinAzure

Page 33: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Portrange:8080-8082Action:Allow

9. ClickOK.

Thisshouldonlytakeacoupleofseconds.Onceyouseetheruleadded,openanewbrowserandnavigatetotheIPaddressofyourUbuntuvirtualmachine,includingtheportnumber.TheIPaddressusedinthisworkshop'sscreenshotsis52.170.85.112(yourIPaddresswillbedifferent).UsingtheaforementionedIPaddress,Iwoulddirectmybrowsertohttp://52.170.85.112:8080.Iwouldalsotesttheother2portnumbers(e.g.8081,8082).Youshouldseethe'HelloWorld'pageatallthreeURL/portcombinations.

Page 34: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

ObjectiveAllofourworkinthisworkshop,withtheexceptionofthesmallAzureconfigurationattheend,willbeperformedonasinglevirtualmachine.Let'sgetstartedcreatingthatVM.

CreateaResourceGroupInordertocreateresources,weneedaResourceGrouptoplacethemin.

1. Ifyouarenottherealready,goaheadandclickontheResourceGroups intheAzurePortaltoopentheResourceGroupsblade.

2. AtthetopoftheResourceGroupsblade,clickonAdd .Thiswillopenapanelthatasksforsomebasicconfigurationsettings.

3. Completetheconfigurationsettingswiththefollowing:

Resourcegroupname:azworkshops_dockerfile_centos_demoSubscription:<chooseyoursubscription>Resourcegrouplocation:<chooseyourlocation>

4. <Optional>CheckPintodashboardatthebottomofthepanel.

5. ClickCreate.

6. Itshouldonlytakeasecondfortheresourcegrouptobecreated.Onceyouclickcreate,theconfigurationpanelclosesandreturnsyoutothelistofavailableresourcegroups.Yourrecentlycreatedgroupmaynotbevisibleinthelist.ClickingonRefresh atthetopoftheResourceGroupsbladeshoulddisplayyournewresourcegroup.

NOTE:Whenyoucreatearesourcegroup,youarepromptedtochoosealocation.Additionally,asyoucreateindividualresources,youwillalsobepromptedtochooselocations.Thelocationofresourcegroupsandtheirresourcescanbedifferent.Thisisbecauseresourcegroupsstoremetadatadescribingtheircontainedresources;and,duetosometypesofcompliancethatyourcompanymayadhereto,youmayneedtostorethatmetadatainadifferentlocationthantheresourcesthemselves.Forexample,ifyouareaUS-basedcompany,youmaychoosetokeepthemetadatastate-sidewhilecreatingresourcesinforeignregionstoreducelatencyfortheend-user.

CreateVirtualMachine

Page 35: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

CreateaVirtualMachineNowthatwehaveanavailableresourcegroup,let'screatetheactualCentOSserver.

1. Ifyouarenottherealready,goaheadandnavigatetotheazworkshops_dockerfile_centos_demoresourcegroup.

2. Atthetopofthebladeforourgroup,clickonAdd .ThiswilldisplaythebladefortheAzureMarketplaceallowingyoutodeployanumberofdifferentsolutions.

3. WeareinterestedindeployingaCentOSserver.Therefore,intheSearchEverythingbox,typeinCentOS-based.Thiswilldisplayacoupleofdifferentversions.SincewewanttodeploythelateststableversionofCentOS,fromthedisplayedoptions,chooseCentOS-based7.3.

4. Choosetheimagepublishedby"RogueWaveSoftware".

Page 36: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

5. Thiswilldisplayabladeprovidingmoreinformationabouttheserverwehavechosen.Tocontinuecreatingtheserver,chooseCreate.

6. Wearenowpromptedwithsomeconfigurationoptions.Thereare3sectionsweneedtocompleteandthelastsectionisasummaryofourchosenoptions.

1. Basics

Name:dockerfile-centosVMdisktype:SSDUsername:localadminAuthenticationtype:Password(NOTE:YoucanchooseSSHifyouarefamiliarwithhowtosetthisup.Ifyouarenot,wewilldothisinalaterworkshop.However,forthisworkshop,Passwordauthenticationissufficient.)Password:Pass@word1234Confirmpassword:<sameasabove>Subscription:<chooseyoursubscription>Resourcegroup:Useexisting-azworkshops_dockerfile_centos_demoLocation:<choosealocation>

2. Size

DS1_V23. Settings

Page 37: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Usemanageddisks:No

Storageaccount:(clickonit&CreateNew)

Name:dfcentosdata<randomnumber>(ex.dfcentosdata123456)(NOTE:Thisnamemustbegloballyunique,soitcannotalreadybeused.)Performance:PremiumReplication:Locally-redundantstorage(LRS)

Virtualnetwork:<acceptdefault>(e.g.(new)azworkshops_dockerfile_centos_demo-vnet)

Subnet:<acceptdefault>(e.g.default(172.16.1.0/24))

PublicIPaddress:<acceptdefault>(e.g.(new)dockerfile-centos-ip)

Networksecuritygroup(firewall):<acceptdefault>(e.g.(new)dockerfile-centos-nsg)

Extensions:Noextensions

Availabilityset:None

Bootdiagnostics:Enabled

GuestOSdiagnostics:Disabled

Diagnosticsstorageaccount:(clickonit&CreateNew)

Name:dfcentosdiags<randomnumber>(ex.dfcentosdiags123456)Performance:StandardReplication:Locally-redundantstorage(LRS)

4. Summary(justclickOKtocontinue)

Thismachineisrelativelysmall,butwithcontainers,itcanstilldeliversomeprettyimpressiveperformance.Oncescheduled,itmaytakeaminuteortwoforthemachinetobecreatedbyAzure.Onceithasbeencreated,Azureshouldopenthemachine'sstatusbladeautomatically.

ConnecttotheVirtualMachineOnceyourmachinehasbeencreated,wecanremotelyconnecttoitusingsecureshell(SSH).TheseinstructionsassumethatyoudonothavestrongfamiliaritywithSSHand/orthatyouhavenobuilt-inSSHclientinyourlocalOS.Forthisreason,wewillbeusingthePuTTYclientwedownloadedearlierfortheworkshop.However,ifyouaremorecomfortableusinganotherTelnet/SSHclient(e.g.MacOS,Linux,WindowsSub-Layer(WSL)),pleasefeelfreetouseit.

GetPublicIP1. Ifitisnotalreadyopen,navigatetotheOverviewbladeofyournewlycreatedvirtual

machine.

Page 38: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

2. Inthetopsectionoftheblade,intherightcolumn,youshouldseeaPublicIPaddresslisted.

3. CopytheIPaddress.

ConnectwithSSH1. OpenPuTTY.

2. Intheconfigurationwindow:

Hostname:<IPaddressfrompreviousstep>Port:22Connectiontype:SSH

Page 39: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

3. ClickOpen

4. Inthesecurityprompt,clickYes.

Page 40: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

5. YouwillthenconnecttotheremoteCentOSserver.

6. Entertheusernameandpasswordfromabove(e.g.localadminandPass@word1234,respectively).

7. Youshouldthenseethe bash prompt:

[localadmin@dockerfile-centos~]$

Congratulations.YouhavesuccessfullycreatedandconnectedtoyourremoteCentOSserverinAzure.YouarenowreadytoinstalltheDockerruntime.

Page 41: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewWehavejustcreatedourCentOSserver.WenowneedtoapplyanyavailablesystemupdatesalongwithinstallingandconfiguringDockertobeginworkingwithcontainers.

InstallUpdatesJustlikeanyotheroperatingsystem,updatesareperiodicallyreleasedtosupportnewfeaturesandpatchanypotentialsecuritythreats.Wewillapplytheupdatesfirst.

1. Ifyouhavenotalready,connecttoyourremoteCentOSserverandlogin.

2. Fromthecommandprompt,typethefollowingtoautomaticallyinstallallavailableupdates:

sudoyumupdate-y

3. You'llberequiredtore-enteryourpassword.

4. Dependingonthenumberandsizeofavailableupdates,thisprocessmaytakeafewminutes.Nowwouldbeagoodtimetotakeabreak.

InstallUpdates

Page 42: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewInthisstep,wearegoingtoinstallDocker.Thisisoneofthestepsthatwillactuallynotbeperformedinsideofthecontainerimage.But,ofcourse,weneedDockeronthehostinordertoruncontainers.

InstallDockerWenowhaveanupdatedCentOSoperatingsystem.WearereadytoinstallDocker.

1. First,let'sremoveanyremnantsofolderversionsofDockertoensurethatwerunthelatestversion.Fromthecommandprompt,typethefollowing:

sudoyumremovedockerdocker-commoncontainer-selinuxdocker-selinuxdocker-engine

Copy&PasteYoucanpastethisintoPuTTYbyright-clickingtheterminalscreen.

2. WeneedtoinstalldependenciesforDocker:

sudoyuminstall-yyum-utilsdevice-mapper-persistent-datalvm2

3. Now,weneedtotellCentOSwheretheDockerrepositoryislocated.Fromthecommandprompt,type(orpaste)thefollowing:

sudoyum-config-manager--add-repohttps://download.docker.com/linux/centos/docker-ce.repo

InstallDocker

Page 43: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

4. Nowthatthenewrepositoryhasbeenadded,weneedtoupdatethe yum packageindex:

sudoyummakecachefast

5. WeneedtoqueryforthelatestversionofDockeravailableintherepository:

yumlistdocker-ce.x86_64--showduplicates|sort-r

6. Youshouldseeoutputedlistsimilartothefollowing:

docker-ce.x86_6417.03.1.ce-1.el7.centosdocker-ce-stabledocker-ce.x86_6417.03.0.ce-1.el7.centosdocker-ce-stable

7. ThelatestversionofDockerwillbethetopline.Theversionwewantislistedinthemiddlecolumn.Inthiscaseit's 17.03.1.ce-1.el7.centos .Toinstall,runthefollowingcommandreplacing <VERSION> withtheversionlistedinthecentercolumn.

sudoyuminstall-ydocker-ce-<VERSION>

8. InstallingtheDockerenginemaytakeanadditionalminuteortwo.

9. MapthestoragedeviceforDockertouse.We'llneedtotemporarilypromoteourselvestothehighestuserpermissionlevel.

sudobashmkdir/etc/dockerecho'{"storage-driver":"devicemapper"}'>/etc/docker/daemon.jsonexit

10. Finally,startDocker:

sudosystemctlstartdocker

Page 44: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

AdditionalConfigurationTosimplifyrunningandmanagingDocker,there'ssomeadditionalconfigurationthatweneedtoimplement.Whilethissectionisoptional,itisrecommendedtomakemanagingDockermucheasier.

EnsureDockerEngineisRunning1. Fromthecommandprompt,type:

sudosystemctlstatusdocker

2. Youshouldseesomethingsimilartothefollowing:

●docker.service-DockerApplicationContainerEngineLoaded:loaded(/lib/systemd/system/docker.service;enabled;vendorpreset:enabled)Active:active(running)sinceSun2017-06-0422:38:16UTC;4min10sagoDocs:https://docs.docker.comMainPID:32844(dockerd)

3. Becausetheserviceisrunning,wecannowusethe docker commandlaterinthisworkshop.

EnableDockerEngineatStartupLet'smakesuretheDockerengineisconfiguredtorunonsystemstartup(andreboot).

1. Fromthecommandprompt,type:

sudosystemctlenabledocker

2. Youshouldseesomethingsimilartothefollowing:

Createdsymlinkfrom/etc/systemd/system/multi-user.target.wants/docker.serviceto/usr/lib/systemd/system/docker.service.

ElevateYourPrivilegesBedefault,runningthe docker commandrequiresrootprivileges-thatis,youhavetoprefixthecommandwith sudo .Itcanalsoberunbyauserinthedockergroup,whichisautomaticallycreatedduringtheinstallofDocker.Ifyouattempttorunthe docker commandwithoutprefixingitwith sudo orwithoutbeinginthedockergroup,you'llgetanoutputlikethefollowing:

Page 45: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

docker:CannotconnecttotheDockerdaemon.Isthedockerdaemonrunningonthishost?.See'dockerrun--help'.

Toavoidtyping sudo wheneveryourunthe docker command,addyourusernametothedockergroup:

sudousermod-aGdocker$(whoami)

Youwillthenneedtologoutandbackinforthechangestotakeeffect.

Ifyouneedtoaddanotherusertothe docker group(oneinwhichyouhavenotloggedinascurrently),simplyprovidethatusernameexplicitlyinthecommand:

sudousermod-aGdocker<username>

You'vesuccessfullyinstalledtheDockerengine.YouhavealsoconfiguredittorunatstartupandhaveaddedyourselftotheDockergroupsothatyouhavesufficientprivilegesforrunningDocker.

Page 46: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewNowthatwehavethehostmachineconfiguredforDocker,we'regoingtobeginbuildingourwebserver.Keepinmindthatthisvirtualmachineisservingtwopurposes:1)ourDockerhost;and,2)ourtemporarywebserveruntilourimageisbuilt.

InstallNode.jsNode.jsisaJavaScriptexecutionenginethatallowsustowriteserver-sideJavaScriptandutilizeitlikeanyotherexecutablefile.WithNode.js,wewillhostaverysimplewebserver.

AddEPELRepositoryOneinstallationmethodforinstallingNode.jsusestheEPEL(ExtraPackagesforEnterpriseLinux)repositorythatisavailableforCentOSandrelateddistributions.

TogainaccesstotheEPELrepo,youmustmodifytherepo-listofyourinstallation.Fortunately,wecanreconfigureaccesstothisrepositorybyinstallingapackageavailableinourcurrentreposcalledepel-release .

sudoyuminstall-yepel-release

DownloadandInstallNode.jsRuntimeTheNode.jsruntimeiswhatisresponsibleforhostingandexecutingourJavaScript.

Fromtheterminalprompt,type:

sudoyuminstall-ynodejs

DownloadandInstallNPMNPMisanabbreviationforNodePackageManager.NPMallowsustoinstallNode.jsdependenciesforourapplications.

Attheprompt,type:

InstallNode.js

Page 47: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

sudoyuminstall-ynpm

VerifyInstallationLet'smakesureourinstallationwassuccessful.

Attheprompt,type:

node-vnpm-v

Youshouldreceiveversionnumbersforbothcommands.

We'venowsuccessfullycompletedtheinstallationofNode.jsandtheNodePackageManager.

Page 48: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewWe'vedownloadedmostofourdependencies.InthisstepwewilldownloadademowebsitefromGitHub,aremotesourcecoderepository.

ClonetheWebsite'Cloning'isthemethodinwhichyoudownloadaremoterepositorytoyourlocalmachine.Wearegoingtoclonethedemowebsitetothedefaultwebhostingfolderonoursystem.

InstallGitGitprovidesacommand-lineinterface(CLI)forinteractingwithGitrepositories.WeneedtoinstallGitonourCentOSmachine.

sudoyuminstall-ygit

DownloadtheWebsiteFromthecommandprompt,typethefollowing:

sudogitclonehttps://github.com/AzureWorkshops/samples-simple-nodejs-website.git/var/www

Youshouldseesomethingsimilartothefollowing:

DownloadSampleWebsite

Page 49: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Cloninginto'/var/www'...remote:Countingobjects:9,done.remote:Compressingobjects:100%(7/7),done.remote:Total9(delta0),reused6(delta0),pack-reused0Unpackingobjects:100%(9/9),done.Checkingconnectivity...done.

Thewebsitesourcecodehasnowbeendownloaded.

Page 50: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewEventhoughwe'veinstalledsystemdependencies,ourwebsitehasacoupleoflibrarydependenciesthatweneedtoinstall.We'llalsoensurethatthewebsiteisfunctioningcorrectly,beforeweproceedtobuildourDockerfile.

DownloadWebsiteDependenciesWe'llneedtoenterintothewebsite'smainfoldertoinstallthedependencies.

Typethefollowingintotheterminal:

cd/var/wwwsudonpmi

Youshouldseeanumberofprogressbarsdisplayedasdependenciesaredownloadedfollowedbywhatlookslikeafolderhierarchy.

TestOurWebsiteThefirstthingweneedtodoisrunourwebhostingserverwhichishandledbyNode.js.Ifweranthisnormallyfromthecommand-line,itwouldblockallotherinput.Wewouldthenhavetoopenasecondterminaltotestourwebsite.Instead,we'regoingtorunourwebserverinthebackgroundasadetachedprocess.

Attheterminalprompt,type:

sudonodeindex.js&

NOTE:Theampersandattheendofthelineinstructsthesystemtorunthepreceedingcommandinthebackground.WhenweconstructourDockerfile,wewillomittheampersandsothattheprocessrunsintheforegroundandcreatesalong-runningprocessthatkeepsourcontainer'alive'.

DownloadDependencies

Page 51: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Whenyourunthiscommand,anumberisoutputtedtothescreen.Thisnumberreferstoaprocessid(pid).Keepthisnumberhandyaswe'lluseitbelowto'kill'thebackgroundprocess.

Additionally,youshouldseeamessagestatingthatour'serverislisteningon8080'.

Testthatthewebserverisreturningoursitebytypingthefollowing:

curlhttp://localhost:8080/

Ifallissuccessful,youshouldreceivesomeHTMLsourcecodeback.

StoptheBackgroundProcessWedon'tneedthewebsiterunninganylongernowthatweknowitworks.Additionally,ifwekeptitrunning,it'suseoftheport8080couldcreatepotentialconflictsifanotherservice(e.g.container)isneedingthatport.

Referringtotheprocessid(pid)above,executethefollowingcommandwithyourid:

sudokill<pid>

Ifsuccessful,youshouldseethefollowingconfirmationmessage:

[1]+Exit143sudonodeindex.js

Buildingourwebserverhasbeensuccessful.Wearenowreadytomoveforwardandreplicateourworkinbuildingoutanimage.

Page 52: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewBasedonmostoftheprevioussteps,wearereadytobuildourDockerfile.Wewillmimicthosestepsforautomatingourimageconstruction.

ReviewInpreparationofwritingourDockerfile,let'sreviewallthestepswe'veperformeduptothispoint.

1. InstallthelatestversionofCentOS2. Installthelatestpackages3. InstallandconfigureDocker4. AddareferencetoEPEL5. InstallNode.js6. InstallNodePackageManager(NPM)7. InstallGit8. Download(clone)thesamplewebsite9. Downloadwebsitedependencies10. Runthewebserver

Asareminder,sinceweareconstructinganimage,wecanignorestep3.Wewon'tneedDockerinstalledinsideoftheimage.

CreatetheDockerfileLet'sgoaheadandcreatetheDockerfilecontents.We'llthenexamineeachlinebelow.

1. Returntoyourhomefolderbytypingattheterminalprompt, cd~ .

2. CreateaDockerfileusingthe nano texteditorbytypingthefollowing: nanoDockerfile .NanoisreminiscentoftheoldDOSeditor.Ofcourse,youcanyou vim insteadifyouarecomfortableindoingso.NOTE'Dockerfile'iscase-sensitive.

3. Enterthefollowingwithoutthelinenumbers.Thelinenumbersareprovidedforreferencebelow.

ConstructDockerfile

Page 53: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

1FROMcentos:latest2MAINTAINERYourName<[email protected]>34RUNyumupdate-y5RUNyuminstall-yepel-release6RUNyuminstall-ynodejs7RUNyuminstall-ynpm8RUNyuminstall-ygit910RUNgitclonehttps://github.com/AzureWorkshops/samples-simple-nodejs-website.git/var/www11WORKDIR/var/www12RUNnpmi1314EXPOSE80801516CMDnode/var/www/index.js

4. Tosave,Ctrl+O

5. Toexit,Ctrl+X

ExplanationFirst,ifyourememberfromtheprevioussteps,weprependedeachcommandwith sudo toallowthecommandtobeexecutedwithelevatedprivileges.Bydefault,allDockerimagesexecuteundertheidentityofthebuilt-insuperuseraccount root .Therefore,wecanomitthe sudo .

Line1:Specifiesthebaseimage,includingthetag,withwhichwe'restarting.Inourcase,weareusingtheminimalCentOSOSasthebaseimage.

Line2:Specifiestheowneroftheimagewiththeiremailaddress.

Lines4-8:ThecommandsweexecutedearlierinthisworkshopthatupdatethesystemandinstallsNode.jsandGit.

Line10:Downloads(clones)thesamplewebsiteintothe /var/www localfolder.

Line11: WORKDIR ishowyouchangethecurrentdirectory(comparedto cd )inaDockerfile.Wearechangingtothewebsitehomedirectory.

Line12:Installthewebsite'sdependencies.

Line14:Ourwebsiteserverisprogrammedtouseport8080.Therefore,similartoafirewallintheimage,weopen,orexpose,theporttotheoutsidehost.Wewillbindtothisopenportlaterwhenwerunacontainerbasedonthisimage.

Line16:Thisstartsourwebserver.Wecouldhaveusedthe RUN directive,butthe CMD directiveisdesignedtoexecuteourlong-runningprocess.While,technically,wecouldhavemultiple CMD linesintheDockerfile,theDockerbuildwillignoreall CMD linesexceptthelastone.

That'sit!That'sallthereistocreatingaDockerfile.

Page 54: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewNowthatwehaveourDockerfile,let'sbuildourimagefromit.

BuildtheDockerImageOncewehaveourDockerfile,buildingtheimageisprettysimple.

Fromthecommandprompt,type cd~ toensureyouareinyourhomefolder,thentypethefollowing:

dockerbuild-ttest/simpleweb.

Thiswillbuildanimageusing test/simpleweb astherepositoryname.TheperiodattheendspecifiesthepathwhereDockercanfindtheDockerfile.

WatchhowDockerwillstepthroughourDockerfiletobuildourimage.KeepinmindwhileyouwatchthisprocessthateachstepinourDockerfileconstitutesalayerinourimage.We'llseetheresultsofthisbelow.

CheckYourImagesFromthecommandprompt,typethefollowing:

dockerimages

Youshouldseesomethingsimilarto:

BuildImage

Page 55: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

REPOSITORYTAGIMAGEIDCREATEDSIZEtest/simpleweblatestd2c9a502fd303minutesago469MBcentoslatest3bee3060bfc837hoursago193MB

Ourimagehasbeenbuiltusingthespecifiedrepositoryname.You'llalsonoticethatthe centosimagehasbeendownloaded.ThisisbecausethebuildprocessrequiredCentOSinordertobuildourimage.Nowthatourimagehasbeenbuilt,youcoulddeletethe centos imageifyouwantedto.Finally,whenlookingattheimagesizes,you'llseethatourimageis4timeslargerdueinstallationofNode.js,Git,andtheotherdependencies.Intheend,however,500MBisstillnotthatlarge.

ViewImageHistoryWhatifwewantedtoseehowourimageisconstructed?Or,whatifwewantedtoseeexactlyhowmuchdiskspaceeachlayerofourimagerequired?Wecouldfindthisoutbycheckingtheimage'shistory.

dockerimagehistorytest/simpleweb

Whenyouruntheabovecommand,youseeeachcommandalongfromourDockerfilealongwithit'slayeridandthespacerequirements,ifany.

We'venowbuiltacustomimagebasedonaDockerfile.Wecanuseourcustomimagetodeploycontainerslocally.Or,wecoulduploadourimagetoacentralrepositorysothatotherscouldleverageourimage'sfunctionality.

Page 56: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewOurcustomimagehasnowbeencreatedandiscurrentlysittinginourlocalrepository.Let'sinstantiateacontainerbasedonthatimage.

StartaContainerTostartacontainerfromourimageisverysimple.Theonlythingweneedtorememberisexposingtheinternalporttothehost.

dockerrun-d-p8080:8080--name'web_8080'test/simplewebdockerrun-d-p8081:8080--name'web_8081'test/simplewebdockerrun-d-p8082:8080--name'web_8082'test/simpleweb

We'vestarted3separatedinstancesofourwebserver.We'veboundthewebserver'sinternalport8080tothreehostports(e.g8080-8082).We'vealsosuppliedmeaningfulnamestoourcontainers.Wecanreferencethosecontainersbythenameswe'vespecifiedforeasiermanagement.Forexample,wecanrestartorstopacontainerusingit'snameinsteadofthecontainerid.

Checktherunningimages:

dockerps

Youshouldseesomethinglikethefollowing:

DeployContainer

Page 57: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES3d1929c8e1b5test/simpleweb"/bin/sh-c'node..."3secondsagoUp2seconds0.0.0.0:8082->8080/tcpweb_8082323a65fa5143test/simpleweb"/bin/sh-c'node..."11secondsagoUp10seconds0.0.0.0:8081->8080/tcpweb_80817d4fee5c8f89test/simpleweb"/bin/sh-c'node..."AboutaminuteagoUp59seconds0.0.0.0:8080->8080/tcpweb_8080

Noticethatallthreecontainersarerunning,but,aswe'vespecified,areboundtodifferentportsandhavecustomnames.

Forpractice,restart web_8081 :

dockerrestartweb_8081

Executingthecommand,maytakeasecond.Afteritcompletes,checktherunningimagesagain.Youshouldnowseethattheuptimefor web_8081 islessthantheothertwocontainers.

Weareleftwithsuccessfullycreatingthreecontainerinstancesrunningourcustomimage.

Page 58: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

OverviewThefinalpartofthisworkshopistopracticeexposingacontainerserviceoutsideofAzure.We'regoingtocreateasimplewebserverandaccessitfromourlocalmachine.

NetworkSecurityGroup(NSG)Nowthatourwebserverisrunning,let'smakeitavailableoutsideofAzure.

WhenwecreatedourCentOSvirtualmachine,weacceptedthedefaults,includingthedefaultsettingsforourNSG.ThedefaultsettingsonlyallowedSSH(port22)access.WeneedtoaddaruletoourNSGtoallowHTTPtrafficoverourthreeports(8080-8082)sothatwecanaccessallthreecontainers.

1. Ifyouarenotstillthere,gobacktotheAzureportalandnavigatetothesettingsofyourCentOSvirtualmachine.

2. Intheleftmenu,clickonNetworkinterfaces .

3. ThiswillopentheNetworkInterfacesbladeforyourCentOSvirtualmachine.Clickonthesingular,listedinterface.

4. Intheleftmenu,clickonNetworksecuritygroup .

5. ThiswilllistthecurrentlyactiveNSG.Inourcase,itshouldbetheNSGthatwascreatedwithourvirtualmachine-dockerfile-centos-nsg.ClickontheNSG(NOTE:ClickontheactualNSGlink,NOTonEdit).

6. Intheleftmenu,clickonInboundsecurityroles .

7. Atthetopoftheblade,clickAdd .

8. Enterthefollowingconfiguration:

Name:allow-httpPriority:1010Source:AnyService:CustomProtocol:Any

ExposeSiteinAzure

Page 59: Docker Automation with Dockerfiles (Linux) - GitHub Pages · Docker Automation with Dockerfiles (Linux) Friday, August 4, 2017 4:52 PM Learn how to automate the build of a custom

Portrange:8080-8082Action:Allow

9. ClickOK.

Thisshouldonlytakeacoupleofseconds.Onceyouseetheruleadded,openanewbrowserandnavigatetotheIPaddressofyourCentOSvirtualmachine,includingtheportnumber.TheIPaddressusedinthisworkshop'sscreenshotsis52.170.85.112(yourIPaddresswillbedifferent).UsingtheaforementionedIPaddress,Iwoulddirectmybrowsertohttp://52.170.85.112:8080.Iwouldalsotesttheother2portnumbers(e.g.8081,8082).Youshouldseethe'HelloWorld'pageatallthreeURL/portcombinations.