Upload
others
View
9
Download
0
Embed Size (px)
Citation preview
DockerAutomationwithDockerfiles(Windows)Tuesday,August29,201712:25AM
LearnhowtoautomatethebuildofacustomWindows-basedDockerimagefromaDockerfile.
ThisworkshopwillshowyouhowtoautomatethebuildingandconfiguringofaWindows-basedDockerimagebyutilizingDockerfiles.YouwillconstructaDockerfilebymimickingaproductionenvironmentconfiguration.You'llalsolearnsomeoftheoptionsforaDockerfileconfiguration.
WhatYouWillLearnConstructingaDockerfileforWindows-basedBuildsVariousDockerfileConfigurationOptionsBuildingaDockerImagefromaDockerfile
IdealAudienceITManagersDevelopersandSoftwareArchitectsConfigurationandChangeManagersDevOpsEngineers
ThisworkshopwillshowyouhowtoautomatethebuildingandconfiguringofaWindows-basedDockerimagebyutilizingDockerfiles.YouwillconstructaDockerfilebymimickingaproductionenvironmentconfiguration.You'llalsolearnsomeoftheoptionsforaDockerfileconfiguration.
TimeEstimate:2hours
Overview
SetupRequirementsThefollowingworkshopwillrequirethatyouuseaRemoteDesktopclientinordertoconnecttoaremotemachine.IfyouareusingaMac,thendownloadtheMicrosoftRemoteDesktopclient.
AdditionalRequirementsForthefollowingworkshop,youwillneedasubscription(trialorpaid)toMicrosoftAzure.Pleaseseethenextpageforhowtocreateatrialsubscription,ifnecessary.
Requirements
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
Congratulations!You'venowcreatedanOffice365tenant;anAzuretenantandsubscription;and,havelinkedthetwotogether.
ObjectiveInthisworkshop,youwillfirstbuilda'production'webserverenvironmentontheactualvirtualmachine.YouwillthentakethosesamestepsandreplicatetheminaDockerfileforbuildingacontainerizedversionofyourVM.
Thestepsinthisworkshoparenotextremelytedious.However,theyarebrokenoutintoindividualpagesforacoupleofreasons.First,itistosimplifytheprocessandaidyouinyourcomprehension.Second,itisforthepurposeofyouseeingtheactualstepsofbuildingtheproductionvirtualmachinesothatyoucomprehendwhatyouaredoingasyouaddeachsteptotheDockerfile.
Introduction
ObjectiveAllofourworkinthisworkshop,withtheexceptionofthesmallAzureconfigurationattheend,willbeperformedonasinglevirtualmachine.Let'sgetstartedcreatingthatVM.
CreateaResourceGroupInordertocreateresources,weneedaResourceGrouptoplacethemin.
1. Ifyouarenottherealready,goaheadandclickontheResourceGroups intheAzurePortaltoopentheResourceGroupsblade.
2. AtthetopoftheResourceGroupsblade,clickonAdd .Thiswillopenapanelthatasksforsomebasicconfigurationsettings.
3. Completetheconfigurationsettingswiththefollowing:
Resourcegroupname:azworkshops_dockerfile_win_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
CreateaVirtualMachineNowthatwehaveanavailableresourcegroup,let'screatetheactualWindowsserver.
1. Ifyouarenottherealready,goaheadandnavigatetotheazworkshops_dockerfile_win_demoresourcegroup.
2. Atthetopofthebladeforourgroup,clickonAdd .ThiswilldisplaythebladefortheAzureMarketplaceallowingyoutodeployanumberofdifferentsolutions.
3. WeareinterestedindeployingaWindowsServer2016Datacenterserver.Therefore,intheSearchEverythingbox,typeinWindowsServer2016.Thiswilldisplayacoupleofdifferentversions.ChooseWindowsServer2016Datacenter.
4. Therewillbeanumberofsolutionsavailable,includingonewithcontainersalreadyenabled.Forthepractice,we'llenablecontainersmanually.Therefore,choosetheimageashighlightedintheimagebelow.
5. Thiswilldisplayabladeprovidingmoreinformationabouttheserverwehavechosen.Tocontinuecreatingtheserver,chooseCreate.
6. Wearenowpromptedwithsomeconfigurationoptions.Thereare3sectionsweneedtocompleteandthelastsectionisasummaryofourchosenoptions.
1. Basics
Name:docker-winVMdisktype:SSDUsername:localadminPassword:Pass@word1234Confirmpassword:<sameasabove>Subscription:<chooseyoursubscription>Resourcegroup:Useexisting-azworkshops_dockerfile_win_demoLocation:<choosealocation>AlreadyhaveaWindowsServerlicense?No
2. Size
DS1_V23. Settings
Usemanageddisks:No
Storageaccount:(clickonit&CreateNew)
Name:dfwindata<randomnumber>(ex.dfwindata123456)(NOTE:Thisnamemustbegloballyunique,soitcannotalreadybeused.)Performance:PremiumReplication:Locally-redundantstorage(LRS)
Virtualnetwork:<acceptdefault>(e.g.(new)azworkshops_dockerfile_win_demo-vnet)
Subnet:<acceptdefault>(e.g.default(172.16.1.0/24))
PublicIPaddress:<acceptdefault>(e.g.(new)docker-win-ip)
Networksecuritygroup(firewall):<acceptdefault>(e.g.(new)docker-win-nsg)
Extensions:Noextensions
Availabilityset:None
Bootdiagnostics:Enabled
GuestOSdiagnostics:Disabled
Diagnosticsstorageaccount:(clickonit&CreateNew)
Name:dfwindiags<randomnumber>(ex.dfwindiags123456)Performance:StandardReplication:Locally-redundantstorage(LRS)
4. Summary(justclickOKtocontinue)
Oncescheduled,itmaytakeaminuteortwoforthemachinetobecreatedbyAzure.Onceithasbeencreated,Azureshouldopenthemachine'sstatusbladeautomatically.
ConnecttotheVirtualMachineOnceyourmachinehasbeencreated,wecanremotelyconnecttoitviaaremotedesktopprotocol(RDP)client.
GetPublicIP1. Ifitisnotalreadyopen,navigatetotheOverviewbladeofyournewlycreatedvirtual
machine.
2. Inthetopsectionoftheblade,intherightcolumn,youshouldseeaPublicIPaddresslisted.
3. CopytheIPaddress.
ConnecttotheMachineviaRemoteDesktopToconnecttothemachineremotely,weneedtodownloadtheRemoteDesktopProtocol(RDP)profile.
1. ClickontheOverview toreturntothegeneralinformationforthedocker-winvirtualmachine.
2. IntheActionssection,clickonConnect .ThiswilldownloadtheRDPprofiletoyourmachine.
3. Opentheprofileandacceptanywarnings.
4. Fortheusername,enter\localadmin(withthebackslash).And,forthepassword,[email protected].
5. Again,acceptanywarnings.
Congratulations.YouhavesuccessfullycreatedandconnectedtoyourremoteWindowsServer2016serverinAzure.YouarenowreadytoinstalltheDockerruntime.
OverviewWehavejustcreatedourWindowsServer2016server.WenowneedtoapplyanyavailablesystemupdatesalongwithinstallingandconfiguringDockertobeginworkingwithcontainers.
InstallUpdatesJustlikeanyotheroperatingsystem,updatesareperiodicallyreleasedtosupportnewfeaturesandpatchanypotentialsecuritythreats.Wewillapplytheupdatesfirst.
1. Ifyouhavenotalready,connecttoyourremoteWindowsServer2016serverandlogin.
2. OpenacommandpromptasanAdministrator,typethefollowingatthecommandprompt:
sconfig
3. Thiswillopenascreenlikethefollowing:
InstallDocker
4. Chooseoption 6 ,then A (twice)todownloadandinstallallupdates.
5. Dependingonthenumberandsizeofavailableupdates,thisprocessmaytakeafewminutesandcouldrequireareboot.Nowwouldbeagoodtimetotakeabreak.
InstallDockerWenowhaveanupdatedWindowsoperatingsystem.WearereadytoinstallDocker.
1. OpenaPowerShellpromptasanAdministrator:
2. Attheprompt,typethefollowing:
Install-PackageProvider-NameNuGet-MinimumVersion2.8.5.201-ForceInstall-Module-NameDockerMsftProvider-ForceInstall-Package-Namedocker-ProviderNameDockerMsftProvider-ForceRestart-Computer-Force
3. ThiswilldownloadtheDockerengineandinstallitasabackgroundservice.
4. Afteryouruntheabovecommands,yourvirtualmachinewillrebootforcingadisconnect.Goaheadandreconnect.
EnsureDockerEngineisRunning1. OpenaPowerShellpromptasanAdministratorandtypethefollowing:
dockerversion
2. Youshouldseesomethingsimilartothefollowing:
Client:Version:17.03.1-ee-3APIversion:1.27Goversion:go1.7.5Gitcommit:3fcee33Built:ThuMar3019:31:222017OS/Arch:windows/amd64
Server:Version:17.03.1-ee-3APIversion:1.27(minimumversion1.24)Goversion:go1.7.5Gitcommit:3fcee33Built:ThuMar3019:31:222017OS/Arch:windows/amd64Experimental:false
3. Becausetheserviceisrunning,wecannowusethe docker commandlaterinthisworkshop.
You'vesuccessfullyinstalledtheDockerengine.
OverviewThefinaltwoelementsofpreparingourWindowsServervirtualmachineistoinstallInternetInformationServer(IIS)andconfigurethenecessaryport(80)inthefirewalltoallowHTTPrequests.
InstallIISSince,forthisexample,wewillbedeployingandhostingabasic,staticwebsite,thestandardIIScomponentsaresufficient.WecouldinstallthemthroughtheServerManager,butwearegoingtousePowerShellsothatwebecomefamiliarwithexecutingtasksforlaterwhenweneedtoautomatethisprocessinDocker.
1. OpenPowerShellinelevatedmode(withAdministratorprivileges):
InstallIIS
2. Typeandexecutethecommand:
Install-WindowsFeature-NameWeb-Server,Web-Mgmt-Tools,NET-Framework-45-ASPNET,Web-App-Dev,Web-Net-Ext45,Web-AppInit,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter
3. Youshouldthenseethecomponentsdownloadandinstall.
4. Itshouldn'tbenecessary,butjusttobesafe,let'sresetIIStopickuptheinstallationofanyadditionalmodules.TypethefollowingandpressEnter: iisreset/restart
5. WeshouldthenseesomemessagestellingusthatIISrestartedsuccessfully.
ConfigureFirewallThelaststeptoconfiguringourserveristoallowIIStoservewebpagesthroughport80.Bydefault,theportisblockedandso,evenifIISwasrunning,wewouldnotbeabletoaccessthesiteoutsideoftheserver,itself.We,again,aregoingtousePowerShelltoconfigurethefirewall.
1. Ifit'snotalreadyopen,againopenPowerShellinelevatedmode.2. Typethefollowingcommand
New-NetFirewallRule-DisplayName'HTTP(S)Inbound'-Profile@('Domain','Private','Public')-DirectionInbound-ActionAllow-ProtocolTCP-LocalPort@('80','443')
We'venowcompletedtheserversetup.WecouldconfigureaseparateIISsiteandapppoolforoursite.But,tokeepthingssimple,we'regoingtousethedefault.
OverviewInthisshortstepwewilldownloadourwebsite-again,viaPowerShell-intoourdefaultIISdirectory.
DownloadandExpandSiteThedefaultfolderforIISis C:\inetpub\wwwroot .Thisisthefolderwewilluseforhostingoursite.Keepinmindthatwithinamicroservicearchitecture,acontainerhasasinglefunctionorpurpose.So,whilewetheoreticallycouldhostmultiplesitesinIIS,it'snotbestpractice.MovingawayfromVMswillrequireustorethinkhowwe'reaccustomedtodoingthings.
Wehaveasamplestaticsitethatwe'lldownloadfromGitHubasa.zipfileandexpanditintoourtargetfolder.
1. Ifit'snotstillopenfromthepreviousstep,openPowerShellwithelevatedprivileges.2. Typethefollowingcommands:
(new-objectNet.WebClient).DownloadFile('https://github.com/AzureWorkshops/samples-simple-iis-website/archive/master.zip','D:\master.zip');Expand-Archive-LiteralPathD:\master.zip-DestinationD:\(new-object-comshell.application).namespace('C:\inetpub\wwwroot\').CopyHere((new-object-comshell.application).namespace('D:\samples-simple-iis-website-master').Items(),16);delc:\inetpub\wwwroot\iisstart*.*
Afteracoupleofseconds,thefileshoulddownload.Theabovescriptdownloadsthe.zipfilefromGitHubtothe D:\ tempdrive(line1);extractsthe.zipfile'scontents(line2)which,in-turn,createsasubdirectoryoftheextractedfiles;copiesthefilesfromthesubdirectorytoourIISrootfolder(line3);and,deletestheIISplaceholderfiles.
Now,ifyouweretoopenInternetExplorerontheserver(e.g.http://localhost/),youshouldseeourwebsitethatsimplydisplaysa'HelloWorld'page.
DownloadSampleWebsite
OverviewBasedonmostoftheprevioussteps,wearereadytobuildourDockerfile.Wewillmimicthosestepsforautomatingourimageconstruction.
ReviewInpreparationofwritingourDockerfile,let'sreviewallthestepswe'veperformeduptothispoint.
1. InstallthelatestversionofWindowsServer.Typically,wewoulduseWindowsNanoServerwhichisdesignedforcontainerizeddeployments.However,preparingaNanoServercontainerrequiresHyper-Vandisalittlemorein-depththanwhatwewanttoaccomplishforthisworkshop,wowe'llstickwithWindowsServer2016.
2. Installthelatestupdates3. InstallandconfigureDocker4. InstallandconfigureIIS5. Configurethefirewall6. Downloadthesamplewebsite
Asareminder,sinceweareconstructinganimage,wecanignorestep3.Wewon'tneedDockerinstalledinsideoftheimage.Additionally,MicrosoftisniceenoughtoprovideusanimagewithIISinstalledandthefirewallconfigured.Thisallowsustoignoresteps4and5,aswell.Allwearerequiredtodoisinstallupdates,Microsoft.NETanddownloadourwebsite.
CreatetheDockerfileLet'sgoaheadandcreatetheDockerfilecontents.We'llthenexamineeachlinebelow.
ConstructDockerfile
1. WeneedtocreateaDockerfile.Somewhereonyourdesktop,right-click,thenclickNew,followedbyTextDocument.
2. NamethenewfileDockerfile.(Note:Thiswilladdthe".txt"extensiontothefileautomatically.Typically,ourDockerfilesshouldn'thaveanextension,butthat'sokay.We'llworkwithit.)
3. Enterthefollowingwithoutthelinenumbers.Thelinenumbersareprovidedforreferencebelow.
1FROMmicrosoft/iis:latest2SHELL["powershell"]3MAINTAINERYourName<[email protected]>45RUNInstall-WindowsFeatureNET-Framework-45-ASPNET;\6Install-WindowsFeatureWeb-Asp-Net45;\7Install-WindowsFeatureWeb-App-Dev;\8Install-WindowsFeatureWeb-Net-Ext45;\9Install-WindowsFeatureWeb-AppInit;\10Install-WindowsFeatureWeb-ISAPI-Ext;\11Install-WindowsFeatureWeb-ISAPI-Filter;1213RUNInvoke-Command-ScriptBlock{$ci=New-CimInstance-Namespaceroot/Microsoft/Windows/WindowsUpdate-ClassNameMSFT_WUOperationsSession;Invoke-CimMethod-InputObject$ci-MethodNameApplyApplicableUpdates;exit}1415RUNmkdirC:\temp16
17RUN(new-objectNet.WebClient).DownloadFile('https://github.com/AzureWorkshops/samples-simple-iis-website/archive/master.zip','C:\temp\master.zip');18RUNExpand-Archive-LiteralPathC:\temp\master.zip-DestinationC:\temp19RUN(new-object-comshell.application).namespace('C:\inetpub\wwwroot\').CopyHere((new-object-comshell.application).namespace('C:\temp\samples-simple-iis-website-master').Items(),16);20RUNdelc:\inetpub\wwwroot\iisstart*.*2122EXPOSE80
4. Tosave,Ctrl+S
ExplanationFirst,ifyourememberfromtheprevioussteps,wewererequiredtoopenaPowerShellpromptasanAdminstratortoallowthecommandtobeexecutedwithelevatedprivileges.Bydefault,allDockerimagesexecuteundertheidentityofthebuilt-inAdministratoraccount.
Line1:Specifiesthebaseimage,includingthetag,withwhichwe'restarting.Inourcase,weareusingtheMicrosoftWindowsServer2016withIISasthebaseimage.
Line2:DirectsDockertoruneverythingfromaPowerShellshell(notthedefaultDOS/CMDprompt).
Line3:Specifiestheowneroftheimagewiththeiremailaddress.
Lines5-11:InstallstheMicrosoft.NETFrameworkforASP.NETandtheASP.NETextensionsintoIIS.Mostoftheseshouldalreadybeinstalledbydefaultfortheimagewe'redownloading.However,thisensuresthatoursystemisup-to-date.
Line13:Installsanynecessarysystemupdates.NOTE:Onahostsystemorvirtualmachine,wewouldnormallyrequireareboot.However,becausewearesimplybuildinganimage,theimagewillstopnaturallyonceit'sbuilt.Wewillthenonlyboottheimageonceweloaditintoacontainer.
Therefore,wetheoreticallyhaveabuilt-inrebootinourprocessandareboothereisnotnecessary.
Line15:Createsa temp folderinwhichtostoreour.zipfile.Inourdemo,wedownloadedthe.zipfiletoourtemporary D:\ drive.Wedon'thavethatdriveinthecontainer,sowe'lluseatemporaryfolder.
Line17:Downloadsthe.zipfileforourwebsitetoour C:\temp folder.
Line18:Decompresses(expands)our.zipfileintothe C:\temp folder.
Line19:Whenwedecompressour.zipfile,wecreateasubdirectorycalled samples-simple-iis-website-master .Here,wearecopyingthecontentsofthatsubfoldertoourmainIISfolderC:\inetpub\wwwroot .
Line20:DeletesthetwoIISplaceholderfiles.
Line22:IIS,bydefault,usesport80.Therefore,similartoafirewallintheimage,weopen,orexpose,theporttotheoutsidehost.Wewillbindtothisopenportlaterwhenwerunacontainerbasedonthisimage.NOTE:Thisparticularimage,microsoft/iis,alreadyexposesport80forus,sowe'retechnicallynotrequiredtoaddthisline.However,it'sstillagoodpracticetoexplicitlyincludethislineincaseweneedtoreusethisDockerfileortheunderlyingbaseeverchanges.
That'sit!That'sallthereistocreatingaDockerfile.
OverviewNowthatwehaveourDockerfile,let'sbuildourimagefromit.
BuildtheDockerImageOncewehaveourDockerfile,buildingtheimageisprettysimple.
FromthePowerShellwindow,typethefollowing:
Get-Content"c:\users\localadmin\desktop\Dockerfile.txt"|dockerbuild-ttest/simpleweb-
Thiswillbuildanimageusing test/simpleweb astherepositoryname.WeareusingPowerShell'sGet-Content commandtoreadthecontentsofourpreviouslycreatedDockerfileandthenpipethemtoDocker'sbuildcommand.
DuetothesizeofWindowsServer,theinitialbuildwilltakesometimebecauseitmustdownloadthebaseimagefirst.WatchhowDockerwillstepthroughourDockerfiletobuildourimage.KeepinmindwhileyouwatchthisprocessthateachstepinourDockerfileconstitutesalayerinourimage.We'llseetheresultsofthisbelow.
CheckYourImagesFromthecommandprompt,typethefollowing:
dockerimages
Youshouldseesomethingsimilarto:
BuildImage
REPOSITORYTAGIMAGEIDCREATEDSIZEtest/simpleweblatest9f4ec58ca8303minutesago11.1GBmicrosoft/iislatest4f803ffceb5337hoursago10.6GB
Ourimagehasbeenbuiltusingthespecifiedrepositoryname.You'llalsonoticethatthemicrosoft/iis imagehasbeendownloaded.ThisisbecausethebuildprocessrequiredWindowsServerwithIISinordertobuildourimage.Nowthatourimagehasbeenbuilt,youcoulddeletethemicrosoft/iis imageifyouwantedto.Finally,whenlookingattheimagesizes,you'llseethatourimageis500MBlargerduetotheinstallationofMicrosoft.NET,ASP.NETandotherdependencies.
BeawarethattheNanoServerimageisonly1.07GBcomparedtothefullWindowsServerat10.6GBwhichmakesNanoServermoreidealforcontainers.ItsreallynotbestpracticetouseWindowsServerinproductionasdownloading10.6GBanddeployingthatacrossyourenterpisecouldconsumealotofbandwidth.Forproduction,it'sbesttooptforNanoServer.But,again,NanoServerrequiresalittlemorepreparationthatextendsatadfurtherbeyondthescopeofthisworkshop.
ViewImageHistoryWhatifwewantedtoseehowourimageisconstructed?Or,whatifwewantedtoseeexactlyhowmuchdiskspaceeachlayerofourimagerequired?Wecouldfindthisoutbycheckingtheimage'shistory.
dockerimagehistorytest/simpleweb
Whenyouruntheabovecommand,youseeeachcommandalongfromourDockerfilealongwithit'slayeridandthespacerequirements,ifany.
We'venowbuiltacustomimagebasedonaDockerfile.Wecanuseourcustomimagetodeploycontainerslocally.Or,wecoulduploadourimagetoacentralrepositorysothatotherscouldleverageourimage'sfunctionality.
OverviewOurcustomimagehasnowbeencreatedandiscurrentlysittinginourlocalrepository.Let'sinstantiateacontainerbasedonthatimage.
StartaContainerTostartacontainerfromourimageisverysimple.Theonlythingweneedtorememberisexposingtheinternalporttothehost.
dockerrun-d-p8080:80--name'web_8080'test/simplewebdockerrun-d-p8081:80--name'web_8081'test/simplewebdockerrun-d-p8082:80--name'web_8082'test/simpleweb
We'vestarted3separatedinstancesofourwebserver.We'veboundthewebserver'sinternalport80tothreehostports(e.g8080-8082).We'vealsosuppliedmeaningfulnamestoourcontainers.Wecanreferencethosecontainersbythenameswe'vespecifiedforeasiermanagement.Forexample,wecanrestartorstopacontainerusingit'snameinsteadofthecontainerid.
Checktherunningimages:
dockerps
Youshouldseesomethinglikethefollowing:
DeployContainer
CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES3d1929c8e1b5test/simpleweb"C:\\ServiceMonitor..."3secondsagoUp2seconds0.0.0.0:8082->80/tcpweb_8082323a65fa5143test/simpleweb"C:\\ServiceMonitor..."11secondsagoUp10seconds0.0.0.0:8081->80/tcpweb_80817d4fee5c8f89test/simpleweb"C:\\ServiceMonitor..."AboutaminuteagoUp59seconds0.0.0.0:8080->80/tcpweb_8080
Noticethatallthreecontainersarerunning,but,aswe'vespecified,areboundtodifferentportsandhavecustomnames.
Forpractice,restart web_8081 :
dockerrestartweb_8081
Executingthecommand,maytakeasecond.Afteritcompletes,checktherunningimagesagain.Youshouldnowseethattheuptimefor web_8081 islessthantheothertwocontainers.
Wehavenowsuccessfullycreatedthreecontainerinstancesrunningourcustomimage.
ViewtheContainerWebsitesBeforeweattempttoexposeoursitestotheoutsideworld,let'smakesurethatwecanaccessthemlocallyontheVM.
1. Openawebbrowseronthevirtualserverandtrytonavigateto http://localhost:8080 (ourweb_8080 container).Oops.Isseemswereceivedanerror.Whatdidwedowrong?Let'sinvestigate.
2. Lookagainattheoutputofthe dockerps command.
3. NoticethePortscolumn.Ourexternalportisnotmappedtotheloopbackaddress(e.g.127.0.0.1 or localhost ).Longstoryshort,thisisduetoawayWindowsmapsitsnetworkinterfaces.
4. Weneedtogettheactual,virtualIPaddressofthecontainer.Todothis,typethefollowingatthePowerShellpromptchangingthecontainernameforeachrunningcontainer:
dockerinspect--format'{{.NetworkSettings.Networks.nat.IPAddress}}'web_8080
5. Now,let'susethereturnedIPinsteadofthe localhost toloadourwebsite.InthebrowserchangetheURLto http://<web_8080'svirtualIPaddress:8080> (e.g.http://172.26.67.126:8080).ThisshoulddisplayourHelloWorldsamplewebsite.
OverviewThefinalpartofthisworkshopistopracticeexposingacontaineroutsideofAzure.We'regoingtocreateasimplewebserverandaccessitfromourlocalmachine.DuetothewayWindows(specifically,Hyper-V)currentlyhandlesnetworkingwithDocker(e.g.the 0.0.0.0 IPassignmenttoourcontainers),thisprocessismuchsimplerinLinux.Sowewillstepthroughthisslowlysothatyouunderstandthesteps.
NetworkSecurityGroup(NSG)WhenwecreatedourWindowsServervirtualmachine,weacceptedthedefaults,includingthedefaultsettingsforourNSG.ThedefaultsettingsonlyallowedRDP(port3389)access.WeneedtoaddaruletoourNSGtoallowHTTPtrafficoverit'sdefaultportforourrunningwebservers.
1. Ifyouarenotstillthere,gobacktotheAzureportalandnavigatetothesettingsofyourWindowsServervirtualmachine.
2. Intheleftmenu,clickonNetworkinterfaces .
3. ThiswillopentheNetworkInterfacesbladeforyourWindowsServervirtualmachine.Clickonthesingular,listedinterface.
4. Intheleftmenu,clickonNetworksecuritygroup .
5. ThiswilllistthecurrentlyactiveNSG.Inourcase,itshouldbetheNSGthatwascreatedwithourvirtualmachine-docker-win-nsg.ClickontheNSG(NOTE:ClickontheactualNSGlink,NOTonEdit).
6. Intheleftmenu,clickonInboundsecurityroles .
7. Atthetopoftheblade,clickAdd .
8. Enterthefollowingconfiguration:
Service:HTTPPortrange:80Priority:100Name:HTTP
ExposeSiteinAzure
9. ClickOK.
Thiswilltakeacoupleofsecondstocomplete.
DockerNetworkingFulldisclosure,theDockerNetworkingtopicisaverydeepandcomplicatedsubject.Therearemanywaystoaccomplishthis,especially,ifyouareusinganorchestratorsuchasDockerSwarmorKubernetes.Wetypicallywantanetworkingconfigurationthatallowsustodynamicallyaddcontainers(services)andhavethemauto-discovered.Thisisparticularlycriticalforservicesthatshouldautoscalebasedondemand.
Forourworkshop,wearegoingtosidestepthisconversationandleaveittoanotherworkshop.Instead,wearegoingtocreateanetworkschemathatwillallowustoexposeourindividualcontainersmanuallyviaanIPaddress.Inourcase,wewantaconfigurationthatissimilartowhat'sknownasaHostmapping.Bydefault,DockeronWindowsonlycreatesaNATnetwork.Therefore,weneedtocreateourHostnetworkmanually.InDocker,thistypeofnetworkconfigurationisknownasTransparent.
Forthenextsection,youwillbeswitchingbackandforthbetweentheAzureportalandyourVM.Keepbothopen.
SetServerStaticIPWhenwecreatedourVM,weopt'edthatthevirtualmachine'sinternalIPwassetdynamically.WenowwanttosetittoastaticinternalIP;and,wehavetodothisintwoplaces-AzureportalandtheVM,itself.
StaticIP-AzureLet'sbeginbysettingthestaticIPinAzure.
1. Ifyouarenotstillthere,gobacktotheAzureportalandnavigatetothesettingsofyourWindowsServervirtualmachine.
2. Intheleftmenu,clickonNetworkinterfaces .
3. ThiswillopentheNetworkInterfacesbladeforyourWindowsServervirtualmachine.Clickonthesingular,listedinterface.
4. Intheleftmenu,clickonIPconfigurations .
5. ThiswilllistalloftheVM'scurrentlyassignedIPs.Atthemoment,thereshouldonlybeoneIPconfigurationlistedipconfig1.UnderthetableheadingPRIVATEIPADDRESS,weshouldseethatitisassigneddynamically.Clickonipconfig1.
6. Approximately80%downontheresultingblade,youshouldseeatogglebetweenDynamicandStatic.ClickonStatic.
7. ThisshouldenabletheinputboxfortheIPaddress.Leaveitas-is.
8. Atthetopoftheblade,clickSave.
Thiswilltakeasecond,butafterthesavehasbeencompleted,theStaticbuttonshouldturnfrompurpletolightblueandtheSavebuttonshouldbedisabled.
StaticIP-VMNow,let'ssetthestaticIPonthevirtualmachine.
1. OntheVM,atthePowerShellprommpt(asAdministrator),type netshinterfaceshowinterface .Youwillseesomethinglikethefollowingtable:
ThevEthernetisavirtualadapteraddedbyDocker.It'stheinternal,NATadapter.WewanttheEthernetadapter.Inourcase,it'sEthernet2,butitcouldbe1,3orsomeothernumber.It'sourprimaryadapterprovidedtousbyHyper-V.
2. Again,atthePowerShellprompt,type netshinterfaceipshowconfigname="Ethernet2"(obviously,substitute"Ethernet2"forthenameofyourethernetadapterifitisdifferent).IMPORTANT:Keepthisinformationhandyasyouwillneeditforacoupleofstepsbelow.
Thiswillshowusthenecessaryconfiguration(outlinedwitharedborder)tomanuallyconfigureouradaptersettings.
AtthePowerShellprompt,type ncpa.cpl .Thiswillshowsomethinglikethefollowing.
3. AtthePowerShellprompt,type ncpa.cpl .Thiswillshowsomethinglikethefollowing.
4. Right-clickonyourprimaryethernetadapter(e.g."Ethernet2").SelectProperties.
5. Inthedialogwindow,selectInternetProtocolVersion4(TCP/IPv4)andclickonProperties.
6. Inthisdialog,selectUsethefollowingIPaddress:andUsethefollowingDNSserveraddresses:.Additionally,entertheinformationyouacquiredfromthepreviousPowerShellnetsh command.Yourinformationmaynotbeexactlylikebelow(again,comparethe
informationtothe netsh output),butitshouldlikesimilar.
7. ClickOK.
8. ClickClose.(NOTE:Youmaytemporarilyloseyourconnection,butyoushouldautomaticallybereconnectedwithinafewseconds.)
CreateaTransparentNetworkWearenowreadytocreateaTransparent,orHost,networkwithinDockerthatwillallowustocreatecontainersthathaveIPaddressesontheparentvirtualmachine'ssubnet.Thiswillprovideadirectroutefrominsideoroutsideofournetworktothecontainer.
Let'sstartbyexaminingthecurrentnetworksDockerhascreatedforus.
OntheVM,atthePowerShellprompt,type dockernetworkls .Thisshouldreturnsomethingsimilartothefollowing:
NETWORKIDNAMEDRIVERSCOPE7d22076d85e0natnatlocal3112bd939814nonenulllocal
Youwillseetwonetworkslisted- nat and none .Anythingattachedtothe none networkisnotaccessiblefromanetwork.The nat networkiswhatourcurrentthreecontainersareattachedto.Itiswhatallowsustoconnecttothemfromthevirtualmachine'swebbrowser.The nat networkisalsowhatallowsthecontainerstocommunicatewitheachother.It's,basically,anetworkthat'sinternaltothatvirtualmachine.
Toviewmoreinformationandseethecontainerscurrentlyconnectedtothenetwork,type dockernetworkinspectnat .
Amongotherthings,you'llseethesubnet,gatewayandthecontainersattachedtothenetwork.
Inthisprocess,wearegoingtoeventuallyreservesomeIPaddresseswithinoursubnettobeusedbyourcontainers.Again,keepinmind,thatourcontainersmustresideonthesamesubnetasourVM.
Multi-HomingIdeally,youwouldprobablyhavetwoNICsattachedtothisVMandsetitupasamulti-homedserver.Thiswouldallowyoutohaveaseparatesubnetthat'sdedicatedtoyourcontainers.However,thisisnottherecommendedsetupforproductionasyouwouldutilizesometypeoforchestratorwithservicediscoveryandameshnetwork.
Let'screateourtransparentnetworktositinsideoursubnet.
InPowerShell,typethefollowingandpressEnter.
dockernetworkcreate-dtransparent--subnet=10.0.0.0/24--gateway=10.0.0.1transparent
IMPORTANT:Refertotheinformationyoureceivedfromthelast netsh command.(NOTE:Youmaytemporarilyloseyourconnection,butyoushouldautomaticallybereconnectedwithinafewseconds.)
ThiscommandtellsDockertocreateanewnetworkusingthetransparentdriver( -d )witha10.0.0.0/24 subnetand 10.0.0.1 gateway,namingit"transparent".
Now,again,atthePowerShellprompt,type dockernetworkls .Youshouldnowseethenetworklisted.
Additionally,typein:
netshinterfaceshowinterface
Thiswillallowyoutoviewtheavailablenetworkinterfaces(NICs).
You'llnoticethat,whenwecreatedourtransparentnetwork,DockercreatedanewvirtualnetworkinterfacevEthernet(HNSTransparent).ThisistheNICwe'lladdourIPstointhestepsbelow.
We'venowcreatedourtransparentnetworkandwe'rereadytoaddourpubliclyaccessiblecontainers.
AddPublicContainersAfterallofthat,we'renowfinallyreadytoaddourpubliccontainersandaccessthemfromoutsideofAzure.
Fromthispointonward,eachstepbelowshouldberepeatedforeachcontainerwewishtoadd.SimplychangetheIPaddress.
Picka"Reserved"IPTheoretically,ourtransparentnetworkdoesn'texistoutsideofourVMsoAzureDHCP/DNSwillnotautomaticallyassignanIPaddresstoourcontainer.WemustassignanIPaddresstoitmanually.First,let'spickanIP.
I'mgoingtostartwith*.*.*.100asmyfirstcontainer'sIPaddress.Formynetwork(your'smaybedifferent),thefullIPaddresswillbe 10.0.0.100 withasubnetmaskof 255.255.255.0 (again,yougetthesubnetandmaskfromthe netsh command).
"Reserve"theIPinAzureSo,first,we'renotreallyreservingtheIPaddress.But,inaway,wekindofare.WearegoingtomanuallyassignourIPasasecondaryIPtoourvirtualmachine'sNIC.
1. Ifyouarenotstillthere,gobacktotheAzureportalandnavigatetothesettingsofyourWindowsServervirtualmachine.
2. Intheleftmenu,clickonNetworkinterfaces .
3. ThiswillopentheNetworkInterfacesbladeforyourWindowsServervirtualmachine.Clickonthesingular,listedinterface.
4. Intheleftmenu,clickonIPconfigurations .Thistimewe'llassignasecondaryIPaddress.
5. Inthetopmenu,clickonAdd .
6. Inthefieldsmakethefollowingselections:
Name:web_public100Allocation:StaticIPaddress:10.0.0.100(usetheIPaddressyouchoseabove)PublicIPaddress:EnabledIPaddress:(clickonit&CreateNew)
Name:web_public100Assignment:Dynamic
7. ClickOK.
Thiswilltakeasecond;bepatient.Onceithascompleted,you'llseethenewIPconfigurationlistedinthetable.MakenoteofthePUBLICIPADDRESSforthenewIPconfiguration.YouwillusethisIPaddresstoaccessyourcontainerfromawebbrowseroncewe'redone.
We'veaddedthenecessaryconfigurationinAzuretorouterequestsforthatIPtoourVM.Inthenextstep,we'lladdtheIPtothemachinesothatitwilllistenonthatIPaddress.
AssigntheIPtotheVirtualNICRememberthenewvirtualNICthatwascreatedabovewhenwecreatedourtransparentnetwork?WeneedtoaddanIPaddresstoit.MostofthetimeyouwouldaddtheIPaddressthroughtheGUI,butwecannotdothis.Weneedtouseafeaturecalled"SkipAsSource"(moreinfo).Therefore,wemustusethe netsh commandonceagainsothattheSkipAsSourcefeatureisnotenabled.
GobacktoyourVMandatthecommandprompt,type:
netshintipv4addaddress"vEthernet(HNSTransparent)"10.0.0.100255.255.255.0
(again,usethevirtualNICname,IPaddressandsubnetmaskacquiredfromthevariousstepsabove)
Now,typethecommand
netshinterfaceipshowconfigname="vEthernet(HNSTransparent)"
WeseethatbothIPs(ouroriginalstaticIPandournewIP)havebeenassignedtoourtransparentnetwork:
OurmachinewillnowlistenforrequestsonthatIPaddress.Ourroutingiscomplete.Now,wesimplyneedtoaddacontainerandassignitthatIPaddress.
IMPORTANT:Ourtransparentnetworkisavirtualnetworkonourmachine.IfwedeleteourtransparentnetworkinDocker,thenwealsoremovetheIPsassociatedwithourvirtualNIC.Justbeaware.
CreateaContaineronOurTransparentNetworkWealreadyhaveourfirstthreecontainersrunningonour nat network.Unfortunately,there'snoeasywaytoreconfigureacontainer'sportmapping;and,youcan'tchangeitwhilethecontainerisrunning.So,we'llcreateanewcontainerandattachittoourtransparentnetwork.
FromthePowerShellcommandline,type
dockerrun-d--net=transparent--ip=10.0.0.100--name"web_public100"test/simpleweb
Thiscommanddoesacoupleofthings.First,asyoumayrememberfromearlier,wearerunningthiscontainerinthebackground,oras"detached"( -d ).Second,weexplicitlyspecifythenetworkinwhichtoattachourcontainer.Inourcase transparent .Whenweuseatransparentnetwork(orafewothertypes),we'rerequiredtospecifytheIPaddressas,again,thehostnetwork'sDHCPcannotassignanIPaddress.Therestofthiscommandshouldbefamiliar.
Let'sviewourrunningcontainersbytyping dockerps .
CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES821e2dc235d4test/simpleweb"C:\\ServiceMonitor..."18minutesagoUp16minutes80/tcpweb_public1001c84a5399eaatest/simpleweb"C:\\ServiceMonitor..."3hoursagoUp3hours0.0.0.0:8082->80/tcpweb_80823b644253ff84test/simpleweb"C:\\ServiceMonitor..."3hoursagoUp3hours0.0.0.0:8081->80/tcpweb_808182dc9c21c5f2test/simpleweb"C:\\ServiceMonitor..."3hoursagoUp3hours0.0.0.0:8080->80/tcpweb_8080
Wenowseeour web_public100 running,butthereisnoNATtranslation-it'ssimplylisteningonport80.Ifweinspectthecontainer'sconfiguration(e.g. dockercontainerinspectweb_public100 ),weseeourassignedIPaddressclosertotheendoftheoutput.
Whew!That'sit!We'veaddedaWidowscontainerandmadeitaccessibleoutsideofAzure.Let'stestourwork.
TestontheVMLet'smakesurewecanaccessthecontainerfromourVM.
1. OntheVM,openupInternetExplorer.
2. IntheURL,typetheIPaddress,including'http://'(e.g. http://10.0.0.100 ).NOTE:Wedon'thavetouseaportthistimeasthecontainerismappeddirectlytoport80.
Ifsuccessful,youshouldseethe'HelloWorld'webpage.
TestOutsideofAzureNowthatweknowourcontainerisaccessiblefromaIPaddressfromwithinoursubnet,let'smakesureit'saccessiblefromoutsideofAzure.
1. Onyourlocalmachine,openawebbrowser.
2. UsethepublicIPaddressyouacquiredfromaddingthe"ReservedIP"toyourmachineandtypeit(includingthe'http://')intotheURL.
Success!Again,yourshouldseethe'HelloWorld'webpage.
ReviewGee,thatwasabitofwork!AsIstatedearlier,doingthisinLinuxismucheasier.Ifyouhaven'tdonesoalreadytryitout.Sincethiswasquiteabitofeffort,Iwantedtoquicklyreviewwhatwe'vedone.
1. Weopenedupport80inAzure'sfirewalltoallowHTTPtraffictoflowthrough.
2. WechangedourIPconfigurationfortheVMtoastaticIPfromadynamicIPsothatwecouldlateraddadditionalIPstotheVM'sNICandnotmessuproutingshouldtheVMreboot.
3. WecreatedatransparentnetworkinDockertoallowourcontainerstoconnectdirectlytoourHostsubnet.
4. Wepickeda"reservedIP"andthen:
1. AddedthatIPtoourVMinAzureasanew,staticIPconfiguration
2. AddedthatIPtoourvirtualNICcreatedbytheDockertransparentnetwork
3. CreatedanewcontainerandassignedittoourtransparentnetworkandassignedittheIP
Allofthestepsonthispage,simplycomesdowntotheprevious4-7steps.Also,remember,nowthatthenetworkingissetup(steps1-3),youonlyneedtofollowstep4forallfuturecontainersonthisVMthatshouldhaveexternalaccess.
NextStepsAsstatedmultipletimes,thisisnottheidealscenariowhenyouneedafully-scalableandredudantsolution.Forthosetypesofenvironments,itisrecommendedthatyouuseanorchestratorlikeDockerSwarmorKubernetes.
However,withthatsaid,youcouldrunstep4againandaddanotherwebservercontainertoyourVM'sDocker.Nowthatyouhavetwocontainersonthesubnet,youcouldaddaloadbalancerinAzureforabitofredudancy.Ofcourse,it'sonlyasredudantastheVM,itself.Forthis,youwouldprobablywanttoaddanAvailabilitySetwithmultipleVMshostingDocker.Then,loadbalanceacrossthemultipleDockercontainers.