Tải bản đầy đủ - 0 (trang)
C. Using Docker with Vagrant

C. Using Docker with Vagrant

Tải bản đầy đủ - 0trang

AppendixC.UsingDockerwithVagrant

Inthischapter,wewillcoverthefollowingtopics:

RunningDockercontainerswithVagrant

Mixedenvironments–theDockerprovisioner



Introduction

Therecipesinthisbookarefocusedmainlyonthemanagementandconfigurationof

virtualmachines(runtimeenvironmentsthatmimictheoperationofentireoperating

systems).Inactualuseandoperationofavirtualmachine,however,therearetypically

onlyafewprocessesrunninginthemachinethatareofimportancetodevelopmentand

deployment.Forexample,thedeploymentofwebapplicationsoftenrequiresthe

deploymentofawebserver(andperhapssomemiddlewareapplications),butavirtual

machinewithafulloperatingsystemwillalsorunseveralprocessesrequiredtomanage

theentireoperatingsystemofthevirtualmachineitself.Assuch,largedeploymentsof

virtualmachinestoservicesoftwareapplicationscanbecomemoreinefficientas

computationalresourcesareusedforvirtualenvironmentoperatingsystemsratherthanthe

computationalneedsofwebapplications.

Whiletheseproblemsareanissueforhypervisorapplications,therehavebeenother

attemptstovirtualizeenvironmentsthatdonotrequirehypervisors.Infact,theisolationof

processesintoseparateruntimeenvironmentsandoperatingsystemshavebeenhowmost

multiuserenvironmentshaveoperatedsincethebeginningofthesharedenvironment

(frommainframeprocessisolationtotechnologies,suchasSolarisZonesandBSD

chrootjails).TheLinuxproject(asofversion2.6.24oftheLinuxkernel)introduceda

similartechnologycalledLinuxContainers(LXC)torunseparateprocessesinisolation

fromotherswithoutrequiringhypervisorapplicationsandseparateoperatingsystems.

AnopensourceprojectwasstartedbydotCloud(acloudhostingcompany)tohelp

managethecomplexityofdealingwithcontainersintosimplebuildanddeployment

processes.ThisprojectwasnamedDockerandhasnowgrowntobecomethefocusand

thenameofthecompanyitself.DockerisfocusedontheuseofcontainersontheLinux

operatingsystem.Asinglehostoperatingsystemcanhostcontainersrunningsoftware

fromdatabasestowebservers,andevenentirelydifferentLinuxdistributions.

WhilethereareothermethodstomanageLinuxContainers,Dockerhasbeenintegrated

intoalargenumberofvendorofferingsthatallowsdevelopersmanychoicestodeploy

applicationspackagedasDockercontainers.Inthisappendix,we’lltakealookathow

VagrantcanintegratewithDockerdevelopmentworkflows.



RunningDockercontainerswithVagrant

Thefirstthingwe’llinvestigateishowtorunanddevelopsimpleDockercontainersusing

Vagrant.Inrecentversions,VagrantshipswithaDockerproviderthatallowsVagrant

usersasimpleenvironmenttostartandruncontainers.

Beforewecanstart,however,weneedtonotethatDockerbuildsontopofLinux

containers.Assuch,aDockercontaineronlyrunsonLinuxoperatingsystems.Thereare

twomainapproachestorunDockercontainersondevelopmentworkstations:

DevelopingDockercontainersnativelyonaLinuxplatform:Thisistheapproach

usedinanumberofdevelopmentbooksandguides,includingTheDockerBookby

JamesTurnbull.DevelopingwithLinuxrequireseitheranativeLinuxinstallationor

perhapsaLinuxdesktopvirtualmachine,suchasaLinuxdistributionrunningona

VMwarevirtualmachine.

DevelopingDockercontainersusingtheboot2dockerenvironment

(http://boot2docker.io).boot2dockerisaLinuxVMdesignedtohostDocker

containersonOSXorWindowsoperatingsystems.boot2dockerhasapackage

installerthatwillguideusersintheuseoftheenvironment.



Note

We’lltakesomecaretonotethattherearetwoprojectsthatwerefertointhis

appendix.Oneistheofficialboot2dockerproject(http://boot2docker.io),andthe

otherisMitchellHashimoto’sboot2docker-vagrant-box

(https://github.com/mitchellh/boot2docker-vagrant-box).Theseenvironmentsare

onlynecessarytouseDockeronaWindowsorOSXmachine.AsDockerisbuilton

topofLinuxContainers,DockerwillrunnativelyonLinuxdesktoporserver

machines.

TheVagrantDockerprovidercansupporteitheroneoftheseapproaches:managing

containersnativelyonLinuxormanagingcontainersthroughtheboot2docker

environment.Vagrantcanevenmanagetheinstallationandoperationoftheboot2docker

environmentonWindowsandOSX,whichcanmakeitsimplerforuserstogetstarted.

ThisappendixwillfocusonusingVagrantonOSX(withtheaidoftheDockerprovider)

tocreateasimpleDockerdevelopmentenvironment.Inparticular,we’lllaunchaMySQL

databasethatusesacontainerprovidedbytheMySQLproject,anduseasimple

Dockerfiletopackageasimplewebapplication.



Howtodoit…

Inthissection,we’lllearnhowtoinstallaDockerimagefromarepositoryandbuilda

DockerimagewithVagrant.



InstallingaDockerimagefromarepository

We’llstartwithasimplecase:installingaDockercontainerfromarepository(aMySQL

container)andconnectingittoanexternaltoolfordevelopment(theMySQLWorkbench

oraclienttoolofyourchoice).We’llneedtoinitializetheboot2dockerenvironmentand

usesomeVagranttoolstointeractwiththeenvironmentandthedeployedcontainers.

Beforewecanstart,we’llneedtofindasuitableDockerimagetolaunch.Oneofthe

uniqueadvantagestouseDockerasadevelopmentenvironmentisitsabilitytoselecta

baseDockerimage,thenaddsuccessivebuildstepsontopofthebaseimage.Inthis

simpleexample,wecanfindabaseMySQLimageontheDockerHubregistry

(https://registry.hub.docker.com).TheMySQLprojectprovidesanofficialDockerimage

thatwecanbuildfrom.



We’llnotefromtherepositorythecommandtousetheimage:dockerpullmysqlmysql

andnotethattheimagenameismysql.

1. StartwithaVagrantfilethatdefinestheDocker:

#-*-mode:ruby-*#vi:setft=ruby:

VAGRANTFILE_API_VERSION="2"



ENV['VAGRANT_DEFAULT_PROVIDER']='vmware_fusion'

Vagrant.configure(VAGRANTFILE_API_VERSION)do|config|

config.vm.define"database"do|db|

db.vm.provider"docker"do|d|

d.image="mysql"

end

end

end



Animportantthingtonoteimmediatelyisthatwhenwedefinethedatabasemachine

andtheproviderwiththeDockerprovider,wedonotspecifyaboxfile.TheDocker

providerwillstartandlaunchcontainersintoaboot2dockerenvironment,negating

theneedforaVagrantboxorvirtualmachinedefinition.Thiswillintroduceabitofa

complicationininteractingwiththeVagrantenvironmentinlatersteps.

AlsonotethemysqlimagenametakenfromtheDockerHubregistry.

2. We’llneedtolaunchtheimagewithafewbasicparameters.Addthefollowingcode

totheDockerproviderblock:

db.vm.provider"docker"do|d|

d.image="mysql"

d.env={

:MYSQL_ROOT_PASSWORD=>""root",

:MYSQL_DATABASE=>""dockertest",

:MYSQL_USER=>""dockertest",

:MYSQL_PASSWORD=>""d0cker"

}

d.ports=["3306:3306"]

d.remains_running="true"

end



Theenvironmentvariables(d.env)aretakenfromthedocumentationontheMySQL

Dockerimagepage(https://registry.hub.docker.com/_/mysql/).Thisishowtheimage

expectstosetcertainparameters.Inthiscase,ourparameterswillsetthedatabase

rootpassword(fortherootuser)andcreateadatabasewithanewuserthathasfull

permissionstothisdatabase.

Thed.portsparameterisanarrayofportlistingsthatwillbeforwardedfromthe

container(thedefaultMySQLportof3306)tothehostoperatingsystem,inthiscase

also3306.Thecontainedapplicationwill,thus,behavelikeanativelyinstalled

MySQLinstallation.



Note

Theportforwardinghereisfromthecontainertotheoperatingsystemthathoststhe

container(inthiscase,thecontainerhostisourboot2dockerimage).Ifweare

developingandhostingcontainersnativelywithVagrantonaLinuxdistribution,the

portforwardingwillbetolocalhost,butboot2dockerintroducessomethingofa

wrinkleindoingDockerdevelopmentonWindowsorOSX.We’lleitherneedto

refertooursoftwareinstallationbytheIPoftheboot2dockercontainerorconfigurea

secondportforwardingconfigurationthatallowsaDockercontainedapplicationto



beavailabletothehostoperatingsystemaslocalhost.

Thefinalparameter(d.remains_running=true)isaflagforVagranttonotethat

theVagrantrunshouldmarkasfailediftheDockercontainerexitsonstart.Inthe

caseofsoftwarethatrunsasadaemonprocess(suchastheMySQLdatabase),a

Dockercontainerthatexitsimmediatelyisanerrorcondition.

3. Startthecontainerusingthevagrantup–provider=dockercommand.Afewthings

willhappenhere:

Ifthisisthefirsttimeyouhavestartedtheproject,you’llseesomemessages

aboutbootingaboxnamedmitchellh/boot2docker.ThisisaVagrantpackagedversionoftheboot2dockerproject.Oncethemachineboots,it

becomesahostforallDockercontainersmanagedwithVagrant.



Note

Keepinmindthatboot2doockerisnecessaryonlyfornonLinuxoperating

systemsthatarerunningDockerthroughavirtualmachine.OnaLinuxsystem

runningDockernatively,youwillnotseeinformationaboutboot2docker.

Afterthecontainerisbooted(orifitisalreadyrunning),Vagrantwilldisplay

notificationsaboutrsyncingafolder(ifweareusingboot2docker)and

launchingtheimage:



Dockergeneratesuniqueidentifiersforcontainersandnotesanyportmapping



information.

4. Let’stakealookatsomedetailsonthecontainersthatarerunningintheDockerhost.

We’llneedtofindawaytogainaccesstotheVagrantboot2dockerimage(andonlyif

weareusingboot2dockerandnotanativeLinuxenvironment),whichisnotquiteas

straightforwardasavagrantssh;we’llneedtoidentifytheVagrantcontainerto

access.

First,identifytheDockerVagrantmachinefromtheglobalVagrantstatus.Vagrant

keepstrackofrunninginstancesthatcanbeaccessedfromVagrantitself.Inthiscase,

weareonlyinterestedintheVagrantinstancenameddocker-host.Theinstance

we’reinterestedincanbefoundwiththevagrantglobal-statuscommand:



Inthiscase,Vagrantidentifiestheinstanceasd381331(auniquevalueforevery

Vagrantmachinelaunched).Wecanaccessthisinstancewithavagrantssh

command:

vagrantsshd381331



ThiswilldisplayanASCII-artboot2dockerlogoandacommandpromptforthe

boot2dockerinstance.Let’stakealookattheDockercontainersrunningonthe

systemwiththedockerpspscommand:



ThedockerpspscommandwillprovideinformationabouttherunningDocker

containersonthesystem;inthiscase,theuniqueIDofthecontainer(outputduring

theVagrantstartup)andotherinformationaboutthecontainer.

5. FindtheIPaddressofboot2docker(onlyifwe’reusingboot2docker)toconnectto

theMySQLinstance.Inthiscase,executetheifconfigcommand:



docker@boot2docker:~$ifconfig



Thiswilloutputinformationaboutthenetworkinterfacesonthemachine;weare

interestedintheeth0entry.Inparticular,wecannotetheIPaddressofthemachine

ontheeth0interface:



MakeanoteoftheIPaddressnotedastheinetaddraddr;inthiscase,

192.168.30.129.

6. ConnectaMySQLclienttotherunningDockercontainer.Inthiscase,we’llneedto

notesomeinformationtotheconnection:

TheIPaddressoftheboot2dockervirtualmachine(ifusingboot2docker).In

thiscase,we’llnote192.168.30.129.

TheportthattheMySQLinstancewillrespondtoontheDockerhost.Inthis

case,theDockercontainerisforwardingport3306inthecontainertoport3306

onthehost.

InformationnotedintheVagrantfilefortheusernameorpasswordonthe

MySQLinstance.

Withthisinformationinhand,wecanconfigureaMySQLclient.TheMySQL

projectprovidesasupportedGUIclientnamedMySQLWorkbench

(http://www.mysql.com/products/workbench/).Withtheclientinstalledonour

hostoperatingsystem,wecancreateanewconnectionintheWorkbenchclient

(consultthedocumentationforyourversionofWorkbench,oruseaMySQL

clientofyourchoice).



Inthiscase,we’reconnectingtotheboot2dockerinstance.Ifyouarerunning

DockernativelyonaLinuxinstance,theconnectionshouldsimplyforwardto

localhost.Iftheconnectionissuccessful,theWorkbenchclientonceconnected

willdisplayanemptydatabase:



Oncewe’veconnected,wecanusetheMySQLdatabaseaswewouldforanyother

MySQLinstancethatishostedthistimeinaDockercontainerwithouthavingtoinstall

andconfiguretheMySQLpackageitself.



BuildingaDockerimagewithVagrant

WhilelaunchingpackagedDocker,applicationscanbeuseful(particularlyinthecase

wherelaunchingaDockercontainerissimplerthannativeinstallationsteps),Vagrant



becomesevenmoreusefulwhenusedtolaunchcontainersthatarebeingdeveloped.On

OSXandWindowsmachines,theuseofVagrantcanmakemanagingthecontainer

deploymentsomewhatsimplerthroughtheboot2dockercontainers,whileonLinux,using

thenativeDockertoolscouldbesomewhatsimpler.Inthisexample,we’lluseasimple

Dockerfiletomodifyabaseimage.

1. First,startwithasimpleVagrantfile.Inthiscase,we’llspecifyabuilddirectory

ratherthanaimagefile:

#-*-mode:ruby-*#vi:setft=ruby:

#VagrantfileAPI/syntaxversion.Don'ttouchunlessyouknowwhat

you'redoing!

VAGRANTFILE_API_VERSION="2"

ENV['VAGRANT_DEFAULT_PROVIDER']='vmware_fusion'

Vagrant.configure(VAGRANTFILE_API_VERSION)do|config|

config.vm.define"nginx"do|nginx|

nginx.vm.provider"docker"do|d|

d.build_dir="build"

d.ports=["49153:80"]

end

end

end



ThisVagrantfilespecifiesabuilddirectoryaswellastheportsforwardedtothehost

fromthecontainer.Inthiscase,thestandardHTTPport(80)forwardstoport49153

onthehostmachine,whichinthiscaseistheboot2dockerinstance.

2. CreateourbuilddirectoryinthesamedirectoryastheVagrantfile.

3. Inthebuilddirectory,createaDockerfile.ADockerfileisasetofinstructionson

howtobuildaDockercontainer.Seehttps://docs.docker.com/reference/builder/or

JamesTurnbull’sTheDockerBookformoreinformationonhowtoconstructa

Dockerfile.Inthisexample,we’lluseasimpleDockerfiletocopyaworkingHTML

directorytoabaseNGINXimage:

FROMnginx

COPYcontent/usr/share/nginx/html



4. Createadirectoryinourbuilddirectorynamedcontent.Inthedirectory,placea

simpleindex.htmlfilethatwillbeservedfromthenewcontainer:







ThisisanNGINXbuild.









Onceallthepiecesareinplace,ourworkingdirectorywillhavethefollowing

structure:



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

C. Using Docker with Vagrant

Tải bản đầy đủ ngay(0 tr)

×