CentOS7LinuxServerCookbookSecondEdition
TableofContents
CentOS7LinuxServerCookbookSecondEdition
Credits
AbouttheAuthors
AbouttheReviewer
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
WhySubscribe?
FreeAccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Sections
Gettingready
Howtodoit
Howitworks
Theresmore
Conventions
Readerfeedback
Customersupport
Errata
Piracy
Questions
1.InstallingCentOS
Introduction
DownloadingCentOSandconfirmingthechecksumonWindowsorOSX
Gettingready
Howtodoit
Howitworks
CreatingUSBinstallationmediaonWindowsorOSX
Gettingready
Howtodoit
Howitworks
PerforminganinstallationofCentOSusingthegraphicalinstaller
Gettingready
Howtodoit
Howitworks
RunninganetinstalloverHTTP
Gettingready
Howtodoit
Howitworks
InstallingCentOS7usingakickstartfile
Gettingready
Howtodoit
Howitworks
Gettingstartedandcustomisingthebootloader
Gettingready
Howtodoit
Howitworks
Troubleshootingthesysteminrescuemode
Gettingready
Howtodoit
Reachingrescuemode
Accessingthefilesystem
Accessingthefilesystem
Re-installtheCentOSbootloader
Howitworks
Updatingtheinstallationandenhancingtheminimalinstallwithadditionaladministrationanddevelopmenttools
Gettingready
Howtodoit
Howitworks
2.ConfiguringtheSystem
Introduction
Navigatingtextfileswithless
Gettingready
Howtodoit
Howitworks
IntroductiontoVim
Gettingready
Howtodoit
Howitworks
Speakingtherightlanguage
Gettingready
Howtodoit
Howitworks
Theresmore
SynchronizingthesystemclockwithNTPandthechronysuite
Gettingready
Howtodoit
Howitworks
Theresmore
Settingyourhostnameandresolvingthenetwork
Gettingready
Howtodoit
Howitworks
Theresmore
Buildingastaticnetworkconnection
Gettingready
Howtodoit
Howitworks
Becomingasuperuser
Gettingready
Howtodoit
Howitworks
Customizingyoursystembannersandmessages
Gettingready
Howtodoit
Howitworks
Theresmore
Primingthekernel
Gettingready
Howtodoit
Howitworks
Theresmore
3.ManagingtheSystem
Introduction
Knowingandmanagingyourbackgroundservices
Gettingready
Howtodoit
Howitworks
Theresmore
Troubleshootingbackgroundservices
Gettingready
Howtodoit
Howitworks
Trackingsystemresourceswithjournald
Gettingready
Howtodoit
Howitworks
Configuringjournaldtomakeitpersistent
Gettingready
Howtodoit
Howitworks
Managingusersandtheirgroups
Gettingready
Howtodoit
Howitworks
Schedulingtaskswithcron
Gettingready
Howtodoit
Howitworks
Theresmore
Synchronizingfilesanddoingmorewithrsync
Gettingready
Howtodoit
Howitworks
Maintainingbackupsandtakingsnapshots
Gettingready
Howtodoit
Howitworks
Monitoringimportantserverinfrastructure
Gettingready
Howtodoit
Howitworks
TakingcontrolwithGITandSubversion
Gettingready
Howtodoit
Howitworks
Theresmore
4.ManagingPackageswithYUM
Introduction
UsingYUMtoupdatethesystem
Gettingready
Howtodoit
Howitworks
Theresmore
UsingYUMtosearchforpackages
Gettingready
Howtodoit
Howitworks
Theresmore
UsingYUMtoinstallpackages
Gettingready
Howtodoit
Howitworks
Theresmore
UsingYUMtoremovepackages
Gettingready
Howtodoit
Howitworks
KeepingYUMcleanandtidy
Gettingready
Howtodoit
Howitworks
Theresmore
Knowingyourpriorities
Gettingready
Howtodoit
Howitworks
Usingathird-partyrepository
Gettingready
Howtodoit
Howitworks
Theresmore
CreatingaYUMrepository
Gettingready
Howtodoit
Howitworks
Theresmore
WorkingwiththeRPMpackagemanager
Gettingready
Howtodoit
Howitworks
Theresmore
5.AdministeringtheFilesystem
Introduction
Creatingavirtualblockdevice
Gettingready
Howtodoit
Howitworks
Theresmore
Formattingandmountingafilesystem
Gettingready
Howtodoit
Howitworks
Theresmore
Usingdiskquotas
Gettingready
Howtodoit
Enablinguserandgroupquotas
Enablingproject(directory)quotas
Howitworks
Theresmore
Maintainingafilesystem
Gettingready
Howtodoit
Howitworks
Theresmore
Extendingthecapacityofthefilesystem
Gettingready
Howtodoit
Howitworks
6.ProvidingSecurity
Introduction
LockingdownremoteaccessandhardeningSSH
Gettingready
Howtodoit
Howitworks
Theresmore
ChangingtheSSHportnumberofyourserver
LimitingSSHaccessbyuserorgroup
Installingandconfiguringfail2ban
Gettingready
Howtodoit
Howitworks
Workingwithafirewall
Gettingready
Howtodoit
Howitworks
Theresmore
Forgingthefirewallrulesbyexample
Gettingready
Howtodoit
Tochangeanexistingfirewalldservice(ssh)
Tocreateyourownnewservice
Howitworks
Theresmore
Generatingself-signedcertificates
Gettingready
Howtodoit
Howitworks
Theresmore
UsingsecurealternativestoFTP
Gettingready
Howtodoit
SecuringyourvsftpdserverwithSSLFTPS
SecuringyourvsftpdserverusingSSHSFTP
Howitworks
Theresmore
7.BuildingaNetwork
Introduction
PrintingwithCUPS
Gettingready
Howtodoit
Howitworks
Theresmore
HowtoaddanetworkprintertotheCUPSserver
HowtosharealocalprintertotheCUPSserver
RunningaDHCPserver
Gettingready
Howtodoit
Howitworks
Theresmore
UsingWebDAVforfilesharing
Gettingready
Howtodoit
Howitworks
InstallingandconfiguringNFS
Gettingready
Howtodoit
InstallingandconfiguringtheNFSserver
Creatinganexportshare
Howitworks
WorkingwithNFS
Gettingready
Howtodoit
Howitworks
SecurelysharingresourceswithSamba
Gettingready
Howtodoit
Howitworks
Theresmore
8.WorkingwithFTP
Introduction
InstallingandconfiguringtheFTPservice
Gettingready
Howtodoit
Howitworks
Theresmore
WorkingwithvirtualFTPusers
Gettingready
Howtodoit
Howitworks
CustomizingtheFTPservice
Gettingready
Howtodoit
Howitworks
Troubleshootingusersandfiletransfers
Gettingready
Howtodoit
Howitworks
9.WorkingwithDomains
Introduction
Installingandconfiguringacaching-onlynameserver
Gettingready
Howtodoit
Configuringacaching-onlyUnboundDNSserver
ConfiguringaforwardingonlyDNSserver
Howitworks
Theresmore
Settingupanauthoritative-onlyDNSserver
Gettingready
Howtodoit
Howitworks
Theresmore
Creatinganintegratednameserversolution
Gettingready
Howtodoit
Howitworks
Theresmore
Populatingthedomain
Gettingready
Howtodoit
Howitworks
Buildingasecondary(slave)DNSserver
Gettingready
Howtodoit
ChangestotheprimaryDNSserver
ChangestothesecondaryDNSserver(s)
Howitworks
10.WorkingwithDatabases
Introduction
InstallingaMariaDBdatabaseserver
Gettingready
Howtodoit
Howitworks
ManagingaMariaDBdatabase
Gettingready
Howtodoit
Howitworks
Theresmore
Reviewingandrevokingpermissionsordroppingauser
AllowingremoteaccesstoaMariaDBserver
Gettingready
Howtodoit
Howitworks
InstallingaPostgreSQLserverandmanagingadatabase
Gettingready
Howtodoit
Howitworks
Theresmore
ConfiguringremoteaccesstoPostgreSQL
Gettingready
Howtodoit
Howitworks
InstallingphpMyAdminandphpPgAdmin
Gettingready
Howtodoit
InstallingandconfiguringphpMyAdmin
InstallingandconfiguringphpPgAdmin
Howitworks
11.ProvidingMailServices
Introduction
Configuringadomain-widemailservicewithPostfix
Gettingready
Howtodoit
Howitworks
Theresmore
Changingane-mailsappearingdomainname
UsingTLS-(SSL)encryptionforSMTPcommunication
ConfigureBINDtouseyournewmailserver
WorkingwithPostfix
Howtodoit
ConnectingmailxtoaremoteMTA
Readingyourlocalmailsfromthemailbox
Howitworks
DeliveringthemailwithDovecot
Gettingready
Howtodoit
Howitworks
Theresmore
Settingupe-mailsoftware
UsingFetchmail
Gettingready
Howtodoit
Howitworks
Theresmore
ConfiguringFetchmailwithgmail.comandoutlook.come-mailaccounts
AutomatingFetchmail
12.ProvidingWebServices
Introduction
InstallingApacheandservingwebpages
Gettingready
Howtodoit
Howitworks
Enablingsystemusersandbuildingpublishingdirectories
Gettingready
Howtodoit
Howitworks
Implementingname-basedhosting
Gettingready
Howtodoit
Howitworks
ImplementingCGIwithPerlandRuby
Gettingready
Howtodoit
CreatingyourfirstPerlCGIscript
CreatingyourfirstRubyCGIscript
Howitworks
Theresmore
Installing,configuring,andtestingPHP
Gettingready
Howtodoit
Howtodoit
SecuringApache
Gettingready
Howtodoit
Configuringhttpd.conftoprovidebettersecurity
Removingunneededhttpdmodules
ProtectingyourApachefiles
Howitworks
SettingupHTTPSwithSecureSocketsLayer(SSL)
Gettingready
Howtodoit
Howitworks
Theresmore
13.OperatingSystem-LevelVirtualization
Introduction
InstallingandconfiguringDocker
Gettingready
Howtodoit
Howitworks
Downloadinganimageandrunningacontainer
Gettingready
Howtodoit
Howitworks
Theresmore
Stoppingandstartingacontainer
Attachingandinteractingwithyourcontainer
CreatingyourownimagesfromDockerfilesanduploadingtoDockerHub
Gettingready
Howtodoit
UploadingyourimagetotheDockerHub
Howitworks
SettingupandworkingwithaprivateDockerregistry
Gettingready
Howtodoit
StepstobedoneonourDockerregistryserver(192.168.1.100)
Stepstobedoneoneveryclientneedingaccesstoourregistry
Howitworks
14.WorkingwithSELinux
Introduction
InstallingandconfiguringimportantSELinuxtools
Gettingready
Howtodoit
Howitworks
Theresmore
WorkingwithSELinuxsecuritycontexts
Gettingready
Howtodoit
Howitworks
Workingwithpolicies
Gettingready
Howtodoit
Howitworks
Theresmore
TroubleshootingSELinux
Gettingready
Howtodoit
Howitworks
15.MonitoringITInfrastructure
Introduction
InstallingandconfiguringNagiosCore
Gettingready
Howtodoit
Howitworks
SettingupNRPEonremoteclienthosts
Gettingready
Howtodoit
Howitworks
Monitoringimportantremotesystemmetrics
Gettingready
Howtodoit
Howitworks
Index
CentOS7LinuxServerCookbookSecondEdition
CentOS7LinuxServerCookbookSecondEditionCopyright2016PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.NeithertheauthornorPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:April2013
Secondedition:January2016
Productionreference:1250116
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78588-728-4
www.packtpub.com
http://www.packtpub.com
CreditsAuthors
OliverPelz
JonathanHobson
Reviewer
MitjaResman
CommissioningEditor
PriyaSingh
AcquisitionEditor
KevinColaco
ContentDevelopmentEditor
PoojaMhapsekar
TechnicalEditor
DeeptiTuscano
CopyEditor
AngadSingh
ProjectCoordinator
FrancinaPinto
Proofreader
SafisEditing
Indexer
RekhaNair
ProductionCoordinator
ManuJoseph
CoverWork
ManuJoseph
AbouttheAuthorsOliverPelzhasmorethan10yearsofexperienceasasoftwaredeveloperandsystemadministrator.HegraduatedwithadiplomadegreeinbioinformaticsandiscurrentlyworkingattheGermanCancerResearchcenterinHeidelbergwherehehasauthoredandco-authoredseveralscientificpublicationsinthefieldofBioinformatics.Aswellasdevelopingwebapplicationsandbiologicaldatabasesforhisdepartmentandscientistsallovertheworld,headministersadivision-wideLinux-baseddatacenterandhassetuptwohigh-performanceCentOSclustersfortheanalysisofhigh-throughputmicroscopeandgenomesequencingdata.Heloveswritingcode,ridinghismountainbikeintheBlackForestofGermanyandhasbeenanabsoluteLinuxandopensourceenthusiastformanyyears.Hehascontributedtoseveralopen-sourceprojectsinthepastandalsoworkedasarevieweronthebookCentOSHighPerformance,PacktPublishing.HemaintainsanITtechblogatwww.oliverpelz.de.
IwouldliketothankmyfamilyandespeciallymywonderfulwifeBeatriceandlittlesonJonahfortheirpatienceandunderstandingduringallthelongworkinghourswhilewritingthisbook.AlsoIwouldliketothankthefolksatPacktPublishingforalltheirsupportandtheopportunitytotowritethisbook,itwasagreatpleasureforme.LastbutnotleastIwouldliketothankJonathanHobsonforwritingthefirsteditionofthisbook:withouthimnosecondeditionofthisbookwouldhavebeenpossible.
IwouldalsoliketothankallofthementorsthatIvehadovertheyears,especiallyProf.Dr.TobiasDykerhoff,whointroducedmetothewholeworldofLinuxalongtimeagoandinfectedmewithhisenthusiasmaboutopensourceandthefreesoftwaremovement.
JonathanHobsonisawebdeveloper,systemsengineer,andapplicationsprogrammer.Formorethan20years,hehasbeenworkingbehindthescenestosupportcompanies,organizations,andindividualsaroundtheworldtorealizetheirdigitalambitions.Withanhonorsdegreeinbothenglishandhistoryandasarespectedpractitionerofmanycomputerlanguages,Jonathanenjoyswritingcode,publishingarticles,buildingcomputers,playingthevideogames,andgettingoutandaboutinthebigoutdoors.HehasbeenusingCentOSsinceitsinception,andovertheyears,ithasnotonlyearnedhistrust,butithasalsobecomehisfirstchoiceforaserversolution.CentOSisafirstclasscommunity-basedenterpriseclassoperatingsystem.Itisapleasuretoworkwithandbecauseofthis,Jonathanhaswrittenthisbooksothathisknowledgeandexperiencecanbepassedontoothers.
http://www.oliverpelz.de
AbouttheReviewerMitjaResmancomesfromasmall,beautifulcountrycalledSlovenia,locatedinsouthernCentralEurope.MitjaisafanofLinuxandanopensourceenthusiast,andalsoaRedHatCertifiedEngineerandLinuxProfessionalInstituteprofessional.Workingasasystemadministrator,MitjagotyearsofprofessionalexperiencewithopensourcesoftwareandLinuxsystemadministrationonlocalandinternationalprojectsworldwide.SwissArmyknifesyndromemakesMitjaanexpertinthefieldsofVMwarevirtualization,Microsoftsystemadministration,andalsoAndroidsystemadministration.
Mitjahasastrongdesiretolearn,develop,andshareknowledgewithothers.ThisisthereasonhestartedablogcalledGeekPeek.Net.ThiswebsiteprovidesCentOSLinuxguidesandhowtoarticlescoveringallsortsoftopicsappropriateforbeginnersandadvancedusers.MitjawroteabookcalledCentOSHighAvailability,PacktPublishing,coveringhowtoinstall,configure,andmanageclusteronCentOSLinux.
Mitjaisalsoadevotedfatherandhusband.Histwodaughtersandwifetakehismindoffthegeekstuffandmakehimappreciatelife,lookingforwardtothingstocome.
http://GeekPeek.Net
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmoreForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusatformoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPacktsonlinedigitalbooklibrary.Here,youcansearch,access,andreadPacktsentirelibraryofbooks.
http://www.PacktPub.comhttp://www.PacktPub.commailto:[email protected]://www.PacktPub.comhttps://www2.packtpub.com/books/subscription/packtlib
WhySubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
FreeAccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
ThisworkisdedicatedtomysonMarlinPelzwhowastragicallystillbornon2.10.15,twoweeksbeforehisexpecteddateofdeliverywhileIwaswritingthelastfewchaptersofthisbook.Marlin,wordscannotexpresshowmuchImissyou!
http://www.PacktPub.com
PrefaceThisisthesecondeditionofthehighlyratedCentOSLinuxServerCookbook.WiththeadventofCentOS7inmid2014,therehasbeenalonglistofsignificantchangesandnewfeaturestothisfamousoperatingsystem.Tonameafew,thereisanewinstaller,suiteofsystemmanagementservices,firewalldaemon,enhancedLinuxcontainersupport,andanewstandardfilesystem.Withallthesenewadvancesintheoperatingsystem,amajorpartoftherecipesfromtheCentOS6LinuxServerCookbookbecameobsoleteorevennon-functional,makinganupdateofthebooksoriginalcontentessential.Butthisbookisnotjustarefresherofthetopicscoveredinthefirstedition:twobrandnewchaptershavebeenincludedaswelltokeepuptodatewiththelatestopensourcetechnologiesaswellasprovidingbettersecurity:operatingsystem-levelvirtualizationandSELinux.Finally,tomakethebookamorecomprehensiveserver-administrationbook,anotherchapteraboutservermonitoringhasbeenincludedaswell.
Buildingaservercanpresentachallenge.Itisoftendifficultatthebestoftimesandfrustratingattheworstoftimes.Theycanrepresentthebiggestofproblemsorgiveyouagreatsenseofprideandachievement.Wherethewordservercandescribemanythings,itistheintentionofthisbooktoliftthelidandexposetheinnerworkingsofthisenterprise-classcomputingsystemwiththeintentionofenablingyoutobuildyourprofessionalserversolutionofchoice.CentOSisacommunity-basedenterpriseclassoperatingsystem.Itisavailablefreeofcharge,andasafullycompatiblederivativeofRedHatEnterpriseLinux(RHEL),itrepresentsthefirstchoiceoperatingsystemfororganizations,companies,professionals,andhomeusersallovertheworldwhointendtorunaserver.ItswidelyrespectedasaverypowerfulandflexibleLinuxdistributionandregardlessofwhetheryouintendtorunawebserver,fileserver,FTPserver,domainserver,oramulti-rolesolution,itisthepurposeofthisbooktodeliveraseriesofturnkeysolutionsthatwillshowyouhowquicklyyoucanbuildafullycapableandcomprehensiveserversystemusingtheCentOSoperatingsystem.Sowiththisinmind,youcouldsaythatthisbookrepresentsmorethanjustanotherintroductiontoyetanotherserver-basedoperatingsystem.Thisisacookbookaboutanenterprise-classoperatingsystemthatprovidesastep-by-stepapproachtomakingitwork.So,regardlessofwhetheryouareaneworanexperienceduser,thereissomethinginsidethesepagesforeveryone,asthisbookwillbecomeyourpracticalguidetogettingthingsdoneandastartingpointtoallthingsCentOS.
WhatthisbookcoversChapter1,InstallingCentOS,isaseriesofrecipesthatintroducesyoutothetaskofinstallingyourserver,updating,andenhancingtheminimalinstallwithadditionaltools.Itisdesignedtogetyoustartedandtoprovideareferencethatshowsyouanumberofwaystoachievethedesiredinstallation.
Chapter2,ConfiguringtheSystem,isdesignedtofollowonfromasuccessfulinstallationtoofferahelpinghandandprovideyouwithanumberofrecipesthatwillenableyoutoachievethedesiredstartingserverconfiguration.Beginningwithshowingyouhowtoworkwithtextfiles,thenchanginglanguageandtimeanddatesettings,youwillnotonlylearnhowconfigureyournetworksettingsbutalsohowtoresolveafullyqualifieddomainnameandworkwithkernelmodules.
Chapter3,ManagingtheSystem,providesthebuildingblocksthatwillenableyoutochampionyourserverandtakecontrolofyourenvironment.Itisherewhereyouwillkickstartyourroleasaserveradministratorbydisseminatingawealthofinformationthatwillwalkyouthroughavarietyofstepsthatarerequiredtodevelopafullyconsideredandprofessionalserversolution.
Chapter4,ManagingPackageswithYUM,servestointroduceyoutoworkingwithsoftwarepackagesonCentOS7.Fromupgradingthesystemtofinding,installing,removing,andenhancingyoursystemwithadditionalrepositories,itisthepurposeofthischaptertoexplaintheopensourcecommand-linepackagemanagementutilityknownastheYellowdogUpdaterModified(YUM)aswellastheRPMpackagemanager.
Chapter5,AdministeringtheFilesystem,focusesonworkingwithyourserversfilesystem.Fromcreatingmockingdiskdevicestotest-driveconceptsexpertlevelformattingandpartitioningcommands,youwilllearnhowtoworkwiththeLogicalVolumeManager,maintainyourfilesystemandworkwithdiskquotas.
Chapter6,ProvidingSecurity,discussestheneedtoimplementaseriesofsolutionsthatwilldeliverthelevelofprotectionyouneedtorunasuccessfulserversolution.FromprotectingyoursshandFTPservices,tounderstandingthenewfirewalldmanagerandcreatingcertificates,youwillseehoweasyitistobuildaserverthatnotonlyconsiderstheneedtoreduceriskfromexternalattackbutonethatwillprovideadditionalprotectionforyourusers.
Chapter7,BuildingaNetwork,explainsthestepsrequiredtoimplementvariousformsofresourcesharingwithinyournetworkscomputers.FromIPaddressesandprintingdevicestovariousformsoffilesharingprotocols,thischapterplaysanessentialroleofanyserverwhetheryouareintendingtosupportahomenetworkorafullcorporateenvironment.
Chapter8,WorkingwithFTP,concentratesontheroleofVSFTPwithaseriesofrecipesthatwillprovidetheguidanceyouneedtoinstall,configureandmanagetheFileTransferProtocol(FTP)youwanttoprovideonaCentOS7server.
Chapter9,WorkingwithDomains,considersthestepsrequiredtoimplementdomain
names,domainresolution,andDNSqueriesonaCentOS7server.Thedomainnamesystemisanessentialroleofanyserverandwhetheryouareintendingtosupportahomenetworkorafullcorporateenvironment,itisthepurposeofthischaptertoprovideaseriesofsolutionsthatwilldeliverthebeginningofafuture-proofsolution.
Chapter10,WorkingwithDatabases,providesaseriesofrecipesthatdeliverinstantaccesstoMySQLandPostgreSQLwiththeintentionofexplainingthenecessarystepsrequiredtodeploythemonaCentOS7server.
Chapter11,ProvidingMailServices,introducesyoutotheprocessofenablingadomain-wideMailTransportAgenttoyourCentOS7server.FrombuildingalocalPOP3/SMTPservertoconfiguringFetchmail,thepurposeofthischapteristoprovidethegroundworkforallyourfuturee-mail-basedneeds.
Chapter12,ProvidingWebServices,investigatestheroleofthewell-knownApacheservertechnologytofulleffect,andwhetheryouareintendingtorunadevelopmentserveroraliveproductionserver,thischapterprovidesyouwiththenecessarystepstodeliverthefeaturesyouneedtobecomethemasterofyourwebbasedpublishingsolution.
Chapter13,OperatingSystem-LevelVirtualization,introducesyoutothewordofLinuxcontainersusingthestate-of-the-artopensourceplatformDocker,andguidesyouthroughbuilding,running,andsharingyourfirstDockerimage.
Chapter14,WorkingwithSELinux,helpstounderstandanddemystifySecurityEnhancedLinux,whichisoneofthemostlittle-knowntopicsofCentOS7.
Chapter15,MonitoringITInfrastructure,introducesandshowshowtosetupNagiosCore,thede-factoindustrystandardformonitoringyourcompleteITinfrastructure.
WhatyouneedforthisbookTherequirementsofthisbookarerelativelysimpleandbeginwiththeneedtodownloadtheCentOSoperatingsystem.Thesoftwareisfree,butyouwillneedacomputerthatiscapableoffulfillingtheroleofaserver,somefreeinstallationmedia(blankCD-R/DVD-RorUSBdevice),anInternetconnection,somesparetime,andadesiretohavefun.
Insayingthat,manyreaderswillbeawarethatyoudonotneedasparecomputertotakeadvantageofthisbookastheoptionofinstallingCentOSonvirtualizationsoftwareisalwaysavailable.Thisapproachisquitecommonandwheretherecipescontainedwithinthesepagesremainapplicable,youshouldbeawarethattheuseofvirtualizationsoftwareisnotconsideredbythisbook.Forthisreason,anyrequestsforsupportregardingtheuseofthissoftwareshouldbedirectedtowardstheappropriatesupplier.
WhothisbookisforThisisapracticalguideforbuildingaserversolution,andratherthanbeingaboutCentOSitself,thisisabookthatwillshowyouhowtogetCentOSupandrunning.Itisabookthathasbeenwrittenwiththenovice-to-intermediateLinuxuserinmindwhoisintendingtouseCentOSasthebasisoftheirnextserver.However,ifyouarenewtooperatingsystemsasawhole,thendontworry;thisbookwillalsoservetoprovideyouwiththestep-by-stepapproachyouneedtobuildacompleteserversolutionwithplentyoftricksofthetradethrowninforgoodmeasure.
SectionsInthisbook,youwillfindseveralheadingsthatappearfrequently(Gettingready,Howtodoit,HowitworksandTheresmore).
Togiveclearinstructionsonhowtocompletearecipe,weusethesesectionsasfollows:
GettingreadyThissectiontellsyouwhattoexpectintherecipe,anddescribeshowtosetupanysoftwareoranypreliminarysettingsrequiredfortherecipe.
HowtodoitThissectioncontainsthestepsrequiredtofollowtherecipe.
HowitworksThissectionusuallyconsistsofadetailedexplanationofwhathappenedintheprevioussection.
TheresmoreThissectionconsistsofadditionalinformationabouttherecipeinordertomakethereadermoreknowledgeableabouttherecipe.
ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:Forthepurposeofthisrecipe,itisassumedthatallthedownloadswillbestoredonWindowsinyourpersonalC:\Users\\Downloadsfolder,orifusinganOSXsystem,inthe/Users//Downloadsfolder.
Ablockofcodeissetasfollows:
enableFTPSports
Anycommand-lineinputoroutputiswrittenasfollows:
sudodiskutilunmountDisk/dev/disk3sudoddif=./CentOS-7-x86_64-Minimal-XXXX.isoof=/dev/disk3bs=1M
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:ClickingtheNextbuttonmovesyoutothenextscreen.
NoteWarningsorimportantnotesappearinaboxlikethis.
TipTipsandtricksappearlikethis.
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbookwhatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail,andmentionthebookstitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.
mailto:[email protected]://www.packtpub.com/authors
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooksmaybeamistakeinthetextorthecodewewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.
Toviewthepreviouslysubmittederrata,gotohttps://www.packtpub.com/books/content/supportandenterthenameofthebookinthesearchfield.TherequiredinformationwillappearundertheErratasection.
http://www.packtpub.com/submit-erratahttps://www.packtpub.com/books/content/support
PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusatwithalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.
mailto:[email protected]
QuestionsIfyouhaveaproblemwithanyaspectofthisbook,youcancontactusat,andwewilldoourbesttoaddresstheproblem.
mailto:[email protected]
Chapter1.InstallingCentOSInthischapter,wewillcover:
DownloadingCentOSandconfirmingthechecksumonWindowsorOSXCreatingUSBinstallationmediaonWindowsorOSXPerforminganinstallationofCentOSusingthegraphicalinstallerRunninganetinstalloverHTTPInstallingCentOSusingakickstartfileRe-installingthebootloaderTroubleshootingthesysteminrescuemodeGettingstartedandcustomizingthebootloaderUpdatingtheinstallationandenhancingtheminimalinstallwithadditionaladministrationanddevelopmenttools
IntroductionThischapterisacollectionofrecipesthatcoversthebasicpracticeofinstallingtheCentOS7operatingsystem.ThepurposeofthischapteristoshowyouhowquicklyyoucangetCentOSupandrunningwhilstenablingyoutocustomizeyourinstallationwithafewtricksofthetradethrowninforgoodmeasure.
DownloadingCentOSandconfirmingthechecksumonWindowsorOSXInthisrecipe,wewilllearnhowtodownloadandconfirmthechecksumofoneormoreCentOS7diskimagesusingatypicalWindowsorOSXdesktopcomputer.CentOSismadeavailableinvariousformatsbyHTTP,FTP,orthersyncprotocolfromaseriesofmirrorsiteslocatedacrosstheworldorviatheBitTorrentnetwork.FordownloadingveryimportantfilesfromtheInternet,suchasoperatingsystemimages,itisconsideredbestpracticestovalidatethosefileschecksum,inordertoensurethatanyresultingmediawouldfunctionandperformasexpectedwheninstalling.Thisalsomakescertainthatthefilesaregenuineandcomefromtheoriginalsource.
GettingreadyTocompletethisrecipe,itisassumedthatyouareusingatypicalWindows-based(Windows7,WindowsVista,orsimilar)orOSXcomputerwithfulladministrationrights.YouwillneedanInternetconnectiontodownloadtherequiredinstallationfilesandalsoneedaccesstoastandardDVD/CDdiskburnerwiththeappropriatesoftware,inordertocreatetherelevantinstallationdisksfromtheimagefiles.Forthepurposeofthisrecipe,itisassumedthatallthedownloadswillbestoredonWindowsinyourpersonalC:\Users\\Downloadsfolder,orifusinganOSXsystem,inthe/Users//Downloadsfolder.
HowtodoitRegardlessofthetypeofinstallationfilesyoudownload,thefollowingtechniquescanbeappliedtoalltheimagefilessuppliedbytheCentOSproject:
1. Letsbeginbyvisitinghttp://www.centos.orginawebbrowserandnavigatetothebuttonlinkGetCentOSNow.Thenclickthelinklistofthecurrentmirrorsinthetext.
2. Themirrorsitesarecategorized,sofromtheresultinglistoflinks,chooseamirrorthatisgeographicallynearyourcurrentlocation.Forexample,ifyouareinLondon(UK),youcanchooseamirrorfromEUandUnitedKingdom.NowchooseamirrorsitebyselectingeithertheHTTPortheFTPlink.
3. Havingmadeyourselection,youwillnowseealistofdirectoriesofalltheavailableCentOSversions.Toproceed,simplyclicktheappropriatefolderthatreads7.Next,youwillseeanadditionallistofdirectories,suchasatomic,centosplus,cloud,andsoon.Weproceedbychoosingtheisosdirectory.
4. CentOS7currentlyonlysupportsthe64-bitarchitecture,sobrowsetotheonlydirectoryavailablelabeledx86_64,whichisacontainerforthe64-bitversion.
5. Youwillnowbepresentedwithaseriesoffilesavailablefordownload.Beginbydownloadingacopyofthevalidchecksumresultidentifiedasmd5sum.txt.
6. IfyouarenewtoCentOSorareintendingtofollowtherecipesfoundthroughoutthisbook,thentheminimalinstallationisideal.Thiscontainstheleastamountofpackagestohaveafunctionalsystem,sochoosethefollowing(XXXXisthemonthstampofthisrelease):
CentOS-7-x86_64-Minimal-XXXX.iso
7. OnaWindows-basedsystemonly(onMac,thistoolisalreadyavailableinthesystem),visithttp://mirror.centos.org/centos/dostools/inyourbrowseranddownloadtheprogrammd5sum.exe.
8. NowonWindows,openthecommandprompt(typicallyfoundatStart|AllPrograms|Accessories|CommandPrompt)andtypethefollowingcommandsintothewindowthatwillopen(presstheEnterkeyattheendofallthelines):
cddownloadsdir
9. OnOSX,opentheprogramFinder|Applications|Utilities|Terminal,thentypethefollowingcommands(presstheEnterkeyattheendofallthelines):
cd~/Downloadsls
10. Youshouldnowseeallthefilesinyourdownloadfolder(includingallthedownloadedCentOSinstallationimagefiles,themd5sum.txtfileandonWindows,themd5sum.exeprogram).
11. Basedonthefilenamesshown,modifythefollowingcommandinordertocheckthechecksumofyourdownloadedISOimagefile.OnWindows,typethefollowing
http://www.centos.orghttp://mirror.centos.org/centos/dostools/
command(changetheXXXXmonthstampaccordingly):
md5sum.exeCentOS-7-x86_64-Minimal-XXXX.iso
12. OnOSX,useinstead:
md5CentOS-7-x86_64-Minimal-XXXX.iso
13. PresstheReturnkeytoproceedandthenwaitforthecommandprompttorespond.TheresponseisknownastheMD5sumandtheresultcouldlooklikethefollowing:
d07ab3e615c66a8b2e9a50f4852e6a77CentOS-7-x86_64-Minimal-1503-01.iso
14. Nowlookatthethesumandcompareagainsttherelevantlistingforyourparticularimagefileinmd5sum.txt(openinatexteditor).Ifboththenumbersmatch,thenyoucanbeconfidentthatyouhaveindeeddownloadedavalidCentOSimagefile.Ifnot,yourdownloadedfileisprobablycorrupted,sopleaserestartthisprocedurebydownloadingtheimagefileagain.
15. Whenyouhavefinished,simplyburnyourimagefile(s)toablankCD-ROMorDVD-ROMusingyourpreferreddesktopsoftware,orcreateaUSBinstallationmediafromit,aswewillshowyouinthenextrecipeinthischapter.
HowitworksSowhathavewelearnedfromthisexperience?
TheactofdownloadingaCentOSinstallationimageisjustthefirststeptowardsbuildingtheperfectserver.Althoughthisprocessisverysimple,manydoforgettheneedtoconfirmthechecksum.Inthisbook,wewillworkwiththeminimalinstallationimage,butyoushouldbeawarethatthereareotherinstallationoptionsavailabletoyou,suchasNetInstall,DVD,Everything,andvariousLiveCDs.
CreatingUSBinstallationmediaonWindowsorOSXInthisrecipe,wewilllearnhowtocreateaUSBinstallationmediaonWindowsorOSX.Nowadays,moreandmoreserversystems,desktopPCs,andlaptopsgetshippedwithoutanyopticaldrive.Installinganewoperatingsystem,suchasCentOSLinuxusingUSBdevicesgetsessentialforthemasnootherinstallationoptionisavailable,asthereisnootherwaytoboottheinstallationmedia.Also,installingCentOSusingUSBmediacanbeconsiderablyfasterthanusingtheCD/DVDapproach.
GettingreadyBeforewebegin,itisassumedthatyouhavefollowedthepreviousrecipeinwhichyouwereshownhowtodownloadaminimalCentOSimageandconfirmthechecksumoftherelevantimagefiles.Itisalsoassumedthatallthedownloads(includingthedownloadedISOfile)arestoredonWindowsinyourC:\Users\\DownloadsfolderorifusingaOSXsystem,inthe/Users//Downloadsfolder.Next,youwillneedafreeUSBdevicewhichcanbediscoveredbyyouroperatingsystem,withenoughtotalspace,andwhichisemptyorwithdataonitthatcanbediscarded.ThetotalspaceoftheUSBdeviceneededforpreparingasaninstallationmediaforCentOS7fortheminimalversionmustberoughly700megabyte.IfyouareworkingonaWindowscomputer,youwillneedaworkingInternetconnectiontodownloadadditionalsoftware.OnOSX,youneedanadministratoruseraccount.
HowtodoitTobeginthisrecipe,startupyourWindowsorOSXoperatingsystem,thenconnectafreeUSBdevicewithenoughcapacity,andwaituntilitgetsdiscoveredbyFileManagerunderWindowsorFinderunderOSX.
1. OnaWindowsbasedsystem,weneedtodownloadanadditionalsoftwarecalleddd.Visithttp://www.chrysocome.net/ddinyourfavoritebrowser.Nowdownloadthelatestdd-XX.zipfileyoucanfindthere,withXXbeingthelateststableversionnumber.Forexample,dd-0.5.zip.
2. OnWindows,navigatetoyourDownloadsfolderusingFileManager.Hereyouwillfindthedd-05.zipfile.Right-clickonitandclickonExtractAll,andextractthedd.exefilewithoutcreatinganysubdirectory.
3. OnWindows,openthecommandprompt(typicallyfoundatStart|AllPrograms|Accessories|CommandPrompt)andtypethefollowingcommands:
cddownloadsdd.exe--list
4. OnOSX,opentheprogramFinder|Applications|Utilities|Terminal,andthentypethefollowingcommands:
cd~/Downloadsdiskutillist
5. OnWindows,tospotthenameoftherightUSBdeviceyouwanttouseasinstallationmedia,lookintotheoutputofthecommandundertheremovablemediasection.Belowthat,youshouldfindalinestartingwithMountingonandthenadriveletter,forexample,\.\e:.Thiscrypticwrittendriveletteristhemostimportantpartweneedinthenextstep,sopleasewriteitdown.
6. OnOSX,thedevicepathcanbefoundintheoutputoftheformercommandandhastheformatof/dev/disk,wherenumberisauniqueidentifierofthedisk.Thedisksarenumbered,startingwithzero(0).Disk0islikelytobetheOSXrecoverydisk,anddisk1islikelytobeyourmainOSXinstallation.ToidentifyyourUSBdevice,trytocomparetheNAME,TYPE,andSIZEcolumnstothespecificationsofyourUSBstick.Ifyouhaveidentifiedthedevicename,writeitdown,forexample,/dev/disk3.
7. OnWindows,typethefollowingcommand,assumingyourUSBdeviceselectedasainstallationmediahastheWindowsdevicename\\.\e:(changethisasrequiredandbecarefulwhatyoutypethiscancreatetremendousdataloss).Also,substituteXXXXwiththecorrectisofileversionnumberinthenextcommand:
dd.exeif=CentOS-7-x86_64-Minimal-XXXX.isoof=\\.\e:bs=1M
8. OnOSX,youneedtwocommandswhichwillaskfortheadministratorpassword(replaceXXXXanddisk3withthecorrectversionnumberandthecorrectUSBdevicepath):
sudodiskutilunmountDisk/dev/disk3
http://www.chrysocome.net/dd
sudoddif=./CentOS-7-x86_64-Minimal-XXXX.isoof=/dev/disk3bs=1m
9. Aftertheddprogramfinishes,therewillbesomeoutputstatisticsonhowlongittookandhowmuchdatahasbeentransferredduringthecopyprocess.OnOSX,ignoreanywarningmessagesaboutthedisknotbeingreadable.
10. Congratulations!YounowhavecreatedyourfirstCentOS7USBinstallationmedia.YounowcansafelyremovetheUSBdriveinWindowsorOSX,andphysicallyunplugthedeviceanduseitasabootdeviceforinstallingCentOS7onyourtargetmachine.
HowitworksSowhathavewelearnedfromthisexperience?
ThepurposeofthisrecipewastointroduceyoutotheconceptofcreatinganexactcopyofaCentOSinstallationISOfileonaUSBdevice,usingtheddcommand-lineprogram.TheddprogramisaUnixbasedtoolwhichcanbeusedtocopybitsfromasourcetoadestinationfile.Thismeansthatthesourcegetsreadbitbybitandwrittentoadestinationwithoutconsideringthecontentorfileallocation;itjustinvolvesreadingandwritingpurerawdata.Itexpectstwofilenamebasedarguments:inputfile(if)andoutputfile(of).WewillusetheCentOSimagefileasourinputfilenametocloneitexactly1:1totheUSBdevice,whichisaccessiblethroughitsdevicefileasouroutputfileparameter.Thebsparameterdefinestheblocksize,whichistheamountofdatatobecopiedatonce.Becareful,itisanabsoluteexperttoolandoverwritesanyexistingdataonyourtargetwhilecopyingdataonitwithoutfurtherconfirmationoranysafetychecks.Soatleastdouble-checkthedevicedrivelettersofyourtargetUSBdeviceandneverconfusethem!Forexample,ifyouhaveasecondharddiskinstalledatD:andyourUSBdeviceatE:(onOSX,at/dev/disk2and/dev/disk3respectively)andyouconfusethedriveletterE:withD:(or/dev/disk3with/dev/disk2),yoursecondharddiskwouldbeerasedwithlittletonochancesofrecoveringanylostdata.Sohandlewithcare!Ifyoureindoubtofthecorrectoutputfiledevice,neverstarttheddprogram!
Inconclusion,itisfairtosaythatthereareotherfarmoreconvenientsolutionsavailableforcreatingaUSBinstallationmediaforCentOS7thantheddcommand,suchastheFedoraLiveUSBCreator.Butthepurposeofthisrecipewasnotonlytocreateaready-to-useCentOSUSBinstallerbutalsotogetyouusedtotheddcommand.ItsacommonLinuxcommandthateveryCentOSsystemadministratorshouldknowhowtouse.Itcanbeusedforabroadvarietyofdailytasks.Forexample,forsecurelyerasingharddisks,benchmarkingnetworkspeed,orcreatingrandombinaryfiles.
PerforminganinstallationofCentOSusingthegraphicalinstallerInthisrecipe,wewilllearnhowtoperformatypicalinstallationofCentOSusinganewgraphicalinstallerinterfaceintroducedinCentOS7.Inmanyrespects,thisisconsideredtobetherecommendedapproachtoinstallingyoursystem,asitnotonlyprovidesyouwiththeabilitytocreatethedesiredharddiskpartitionsbutalsotocustomizeyourinstallationinlotsofways(forexample,keyboardlayout,packageselection,installationtype,andsoon).Yourinstallationwillthenformthebasisofaserveronwhichyoucanbuild,develop,andrunanytypeofserviceyoumaywanttoprovideinthefuture.
GettingreadyBeforewebegin,itisassumedthatyouhavefollowedthepreviousrecipeinwhichyouwereshownhowtodownloadaCentOSimage,confirmthechecksumoftherelevantimagefiles,andcreatetherelevantinstallationopticaldisksorUSBmedia.Yoursystemmustbea64bit(x64_86)architecture,musthaveatleast406MBRAMtoloadthegraphicalinstaller1GBormoreisrecommendedifinstallingagraphicalwindowmanagersuchasGnome),andhaveatleast10GBfreeharddiskspace.
HowtodoitTobeginthisrecipe,insertyourinstallationmedia(CD/DVDorUSBdevice),restartthecomputer,andpressthecorrectkeyforselectingthebootdeviceduringstartup.Thenchoosetheinserteddevicefromthelist(formanycomputers,thiscanbereachedusingF11orF12butcanbedifferentonyoursystem.Pleaserefertoyourmotherboardsmanual).
1. Onthewelcomesplashscreen,theoptionTestthismedia&installCentOS7ispreselectedandwewillusethisoption.Whenyouareready,presstheReturnkeytoproceed.
2. Afterloadingsomeinitialfiles,theinstallerthenstartstotesttheinstallationmedia.Asingletestshouldtakebetween30secondstofiveminutesandwillreportifthereareanyerrorsonyourinstallationmedia.Whenthisprocessiscomplete,thesystemwillfinallyloadthegraphicalinstaller.
3. TheCentOSinstallerwillnowpresentthegraphicalinstallationwelcomescreen.Fromthispointonwards,youcanuseyourkeyboardandmouse(thelatterishighlyrecommended),butremembertoenablethenumberlockonyourkeyboardifyouintendtousethekeypad.
4. Ontheleftsideyouseethemainlanguagecategoryandontherightside,thesub-languagesfortheinstaller.Youcanalsosearchforalanguageusingthetextboxontheleftbottom.Allchangestoyourlanguagesettingswilltakeeffectimmediately,sowhenyouareready,choosetheContinuebuttontoproceed.
5. Nowwereachthemaininstallationmenu,whichiscalledInstallationsummary.6. Mostoptionsshownherealreadyhavesomepredefinedvaluesandcanbeused
withoutchanging,otherswhichdonothaveanydefaultvalueandwhichneedyourattentionarelabeledwitharedexclamationmarkliketheInstallationDestinationunderSystemcategory.Soletsclickonitusingthemouse.
7. AfterclickingtheInstallationDestinationbutton,youwillseeagraphicallistofalltheharddiskdevicescurrentlyconnectedtoyourcomputer,whichyoucanuseforinstallingtheoperatingsystemon.Youcanselectyourtargetharddiskbyclickingonthecorrectharddisksymbol.Itwillthenputacheckmarkonit.Ifyouareunsureabouttherightharddisk,trytoidentifyitbycomparingitsbrandandtotalsizeshowninthemenu.Beforetheinstallationcanproceed,youmustselectaharddisk.Becarefulandchooseyourtargetharddiskwiselyasitwilleraseanyexistingdataonitduringtheinstallation.Whenyouareready,clicktheDonebutton.
8. Ifyourselectedharddiskalreadycontaineddata,thenwhenclickingonDone,youmayseewhatcouldbedescribedasawarning/errormessage.Themessagemayread:YoudonthaveenoughspaceavailabletoinstallCentOS.Dontworry!Thisistobeexpectedandthemessageissimplyaskingyoutore-initializeyourharddiskbecauseCentOScanonlybeinstalledonanemptydisk.Inmostcases,especiallyifyouhavemorethanonepartitionontheharddisk,simplyclickonReclaimspacewhichwillshowanewwindowwithadetailedlistofallthepartitionsonthisdrive.HerejustclickonDeleteAllandthenagainonReclaimspacetodiscardanydataonthisdisk,whichwillcompletethetaskofdiskinitializationandenableyouto
proceedtothenextstep.Whenfinished,clicktheDonebutton.9. BackattheInstallationSummaryscreen,theexclamationmarkontheInstallation
Destinationitemshouldbegonenow.10. Optionally,wecanclickonNetwork&HostnameunderSystemcategory.Onthe
followingpage,ontheleftside,youcanchoosetheprimarynetworkadapteryouwouldliketoconnecttotheInternetandselectitbyclickingonit.Fortheselecteddevice,clickontheswitchontherightsidetoenableandconnectitautomaticallyusingtheOnpositionoftheswitch.Finally,beforeclosingthissubmenu,changethehostnameinitstextfieldtosomethingappropriate.ClickDone.
11. NowbackattheInstallationSummaryscreen,alltheimportantsettingshavebeenmadeorhavegotpredefinedvalues,andalltheexclamationmarksaregone.Ifyouarehappywiththesesettings,clickontheStartinstallationbuttonorchangethesettingsappropriately.
12. Onthenextscreen,youwillberequiredtocreateandconfirmarootpasswordfortherootuserwhilethenewsystemgetsinstalledinthebackground.Chooseasecurepasswordwithnotlessthansixcharacters.
13. Hereonthisscreenyoucanalsocreateastandarduseraccountwhichishighlyrecommended.IfyoucreateanewuserdonotcheckMakethisuseradministrator.Whenyouareready,clickDone(ifyouenteredaweakpassword,youhavetoconfirmthisbyclickingtwice)
14. CentOSwillnowpartitionateandformatyourharddiskinthebackgroundandresolveanydependencies,andtheinstallerwillbeginwritingtotheharddisk.Thismaytakesometime,butaprogressbarwillindicatethestatusofyourinstallation.Whenfinished,theinstallerwillinformyouthattheentireprocessiscompleteandthattheinstallationwassuccessful.Sowhenyouareready,clickontheRebootbutton.Nowreleaseyourinstallationmediafromthedrive.
15. Congratulations!YouhavenowinstalledCentOS7onyourcomputer.
HowitworksInthisrecipe,youhavediscoveredhowtoinstalltheCentOS7operatingsystem.Havingcoveredthetypicalapproachtothegraphicalinstallationprocess,youarenowinapositiontodeveloptheserverwithadditionalconfigurationchangesandpackagesthatwillsuittheroleyouintendtheservertofulfill.Thisgraphicalinstallerhasbeenbuiltwiththeaimtobeveryintuitiveandflexible,andmakesinstallationveryeasyasitwillguidetheuserthroughsomemandatorytasksthathehastofulfillbeforetheinstallationofthemainsystemcanbestarted.
RunninganetinstalloverHTTPInthisrecipe,wewilllearnhowtoinitiatetheprocessofrunninganetinstalloverHTTP(usingtheURLmethod)inordertoinstallCentOS7.Itisaprocessinwhichasmallimagefileisusedtobootthecomputerandlettheuserselectandinstallonlythesoftwarepackagesandserviceshewantsandnothingmoreoveranetworkconnectionthusprovidinggreatflexibility.
GettingreadyBeforewebegin,itisassumedthatyoualreadyknowhowtodownloadandchecksumaCentOS7installationimageandhowtocreatetherelevantinstallationmediafromit.Forthisrecipehere,wewillneedtodownloadandcreateinstallationmediaforthenetinstallimage(downloadthelatestCentOS-7-x86_64-NetInstall-XXXX.isofile)insteadoftheminimalISOshowninanotherrecipeinthischapter.Also,itisassumedthatyouhaveatleastgonethroughthegraphicalinstallationprocedureoncetoexactlyknowhowtobootfromyourinstallationmediaandworkwiththeinstallerprogram.
HowtodoitTobeginthisrecipe,insertyourpreparednetinstallmedia,bootyourcomputerfromit,andwaitforthewelcomescreentoappear:
1. Onthewelcomesplashscreen,theoptionTestthismedia&installCentOS7ispreselectedandwewillusethisoption.Whenyouareready,presstheReturnkeytoproceed.
2. Afterthetestsfinish,thegraphicalinstallerwillloadandpresentthetypicalgraphicalinstallationsummaryscreen.
NoteHeretheinstallershouldbeconfiguredexactlyasinthenormalgraphicalinstallationrecipe,besidesthefollowingmandatorychangestotheNetwork&HostnameandInstallationsourcemenuitems(whichisshownbytheredexclamationmarks).
3. BeforewecaninstallCentOSoverthenetwork,wehavetomakesurethatwehaveaworkingnetworkconnection.Therefore,youshouldfirstclickontheNetwork&Hostnamemenuentryandactivateoneofyournetworkadapterstotheconnectedstate.Refertothenormalinstallationrecipeformoredetails.
4. Next,clickonInstallationsourcetoenterthesettings.AswewillbeinstallingoverHTTP(alsoreferredtoastheURLmethod),youshouldleavethedefaultOnthenetworkselectedintheWhichinstallationsourcewouldyouliketouse?section.
5. NowtypeinthefollowingURLinthestandardhttp://textfield,whichwewillusetodownloadalltherequiredinstallationpackagesathttp://mirror.centos.org/centos/7/os/x86_64/.
6. Alternatively,youcanalsouseapersonalrepositorywhichyouwouldhavetocreateinadvance(seeChapter4,ManagingPackageswithYUM)
7. Whenyouareready,clickonDonetostarttheinitializationprocess.8. Onsuccess,theinstallerwillbegintoretrievetheappropriateinstall.imgfile.This
maytakeseveralminutestocomplete,butonceresolved,aprogressbarwillindicateallthedownloadactivity.Whenthisprocessfinishessuccessfully,theexclamationmarkattheinstallationsourcewillgoawaybutanotheronewillpopupwhichwilltelltheuserthatitismissingthesoftwareselection.Clickonitandchoosewhateverfitsyourneed.Asforthepurposeofthisrecipe,justselectMinimalinstallunderBaseenvironmentandthenclickonDone.
9. IftheWhichinstallationsourcewouldyouliketousestaysgreyedoutandcannotbechanged,thenthereareconnectionproblemswithyournetworkadapter.Ifthisisthecase,gobacktoconfigureNetwork&Hostnameandchangethenetworksettingsuntiltheconnectedstatecanbereached.
10. CentOS7willnowinstalltheoperatingsystemtheusualwayandwillcongratulateyouwhenthisprocessfinishes.ItmaybeslowerthaninstallingfromaphysicalinstallationmediasinceallthepackageshavetoberetrievedfromtheInternet.
http://%20http://mirror.centos.org/centos/7/os/x86_64/
HowitworksThepurposeofthisrecipewastointroduceyoutotheconceptoftheCentOSnetworkinstallationprocess,inordertoshowyoujusthowsimplethisapproachcanbe.Bycompletingthisrecipeyouhavenotonlysavedtimebylimitingyourinitialdownloadtothosefilesthatarerequiredbytheinstallationprocess,butyouhavealsobeenabletotakeadvantageofthefullgraphicalinstallationmethodwithouttheneedforacompleteDVDsuite.
InstallingCentOS7usingakickstartfileWhileinstallingCentOS7manuallyusingthegraphicalinstallerutilityisfineonasingleserver,doingsoonamultiplenumberofsystemscanbetedious.Kickstartfilescanautomatetheinstallationprocessofaserversystemandherewewillshowhowthiscanbedone.Theyaresimpletextbasedconfigurationfileswhichprovidedetailedandexactinstructionsonhowthetargetsystemshouldbesetupandinstalled(forexample,whichkeyboardlayoutoradditionalsoftwarepackagestoinstall).
GettingreadyTosuccessfullycompletethisrecipe,youwillneedaccesstoanalreadyinstalledCentOS7systemtoretrievethekickstartconfigurationfilewewanttoworkwithanduseforautomatedinstallation.Onthispre-installedCentOSserver,youalsoneedaworkingInternetconnectiontodownloadadditionalsoftware.
Next,wewillneedtodownloadandcreateinstallationmediafortheDVDortheEverythingimage(downloadthelatestCentOS-7-x86_64-DVD-XXXX.isoorCentOS-7-x86_64-Everything-XXXX.isofile),insteadoftheminimalisofileshowninanotherrecipeinthischapter.ThenyouneedanotherUSBdevicewhichmustbereadandwritableonLinuxsystems(formattedasFAT16,FAT32,EXT2,EXT3,EXT4,orXFSfilesystem).
HowtodoitForthisrecipetowork,wefirstneedphysicalaccesstoanexistingkickstartfilefromanotherfinishedCentOS7installation,whichwewilluseasatemplateforanewCentOS7installation.
1. LoginasrootontheexistingCentOS7systemandmakesurethekickstartconfigurationfileexistsbytypingthefollowingcommandandpressingtheReturnkeytoexecute(thiswillshowyouthedetailsofthefile):
ls-l/root/anaconda-ks.cfg
2. Next,physicallypluginaUSBdeviceandthentypethefollowingcommand,whichwillgiveyoualistofalltheharddiskdevicescurrentlyconnectedtothecomputer:
fdisk-l
3. Trytoidentifythedevicenamebycomparingitssize,partitions,andidentifiedfilesystemswiththespecificationsofyourUSBdevice.Thedevicenamewillbeofkind/dev/sdX,whereXisanalphabeticalcharacter,suchasb,c,d,e,andsoon.IfyoucannotfindtherightdevicenameforyourUSBmediausingthefdiskcommand,trythefollowingtrick:runfdisk-ltwice-firstwithplugged-outandthenwithplugged-inUSBdeviceandcomparehowthesecondoutputchanged-ithasonedevicenamemorethanthefirstoutput:yourdevicenameofinterest!
4. Ifyouhavefoundtherightdevicenameinthelist,createadirectorytomountittothecurrentfilesystem:
mkdir/mnt/kickstart-usb
5. Next,actuallymountthesticktothisfolder,assumingthatyourUSBpartitionofchoiceisat/dev/sdc1(changethisasrequired):
mount/dev/sdc1/mnt/kickstart-usb
6. NowwewillcreateourworkingcopyofthekickstartfileontheUSBdeviceforcustomizing:
cp/root/anaconda-ks.cfg/mnt/kickstart-usb
7. Next,openthecopiedkickstartfileontheUSBdevicewithyourfavoritetexteditor(herewewillusetheeditornano,ifyouhavenotinstalledityettypeyuminstallnano):
nano/mnt/kickstart-usb/anaconda-ks.cfg
8. WewillnowmodifythefileforinstallingCentOSonanewtargetsystem.Innano,usetheupanddownarrowkeystogotothelinewhichstartswith(willbethenameofthehostnameyougaveduringinstallatione.g.minimal.home):
network--hostname=
9. Noweditthestringtogiveitanewuniquehostname.Forexample,adda-2totheendofanyexistingname,asshownnext:
network--hostname=minimal-2.home
10. Next,movethecursordownusingtheupanddownarrowkeysuntilitstopsatthelinewhichsays%packages.Appendthefollowinglinesrightbelowit(youcanfurthercustomizethisandprovideadditionalpackagesthatyouwanttoinstallautomatically):
mariadb-serverhttpdrsyncnet-tools
11. Nowsaveandclosethefile,todothisinthenanoeditorusethekeycombinationCtrl+o(whichmeans,holddowntheCtrlkeyonthekeyboardandthentheokeywithoutreleasingtheCtrlkey)towritethechanges.ThenpressReturntoconfirmthefilenameandCtrl+xtoexittheeditor.
12. Next,installthefollowingCentOSpackage:
yuminstallsystem-config-kickstart
13. Nowwevalidatethesyntaxofourkickstartfileusingtheksvalidatorprogram,whichisincludedinthepackagewejustinstalled:
ksvalidator/mnt/kickstart-usb/anaconda-ks.cfg
14. Iftheconfigfileiserror-free,unmounttheUSBsticknowbyusingthefollowingcommands:
cdumount/mnt/kickstart-usb
15. Whenyougetanewcommandpromptagain,unplugtheUSBdevicewiththekickstartfileforusingonthetargetmachinephysicallyfromthesystem.
16. NowyouneedphysicalaccesstothetargetmachineyouwanttoinstallCentOSon,usingthekickstartfilejustcreated.Disconnectanyotherexternalfilestorage(s)thatyoudonotneedduringtheinstallation.
17. PoweronthecomputerandputinyourpreparedCentOSinstallationmedia(mustbeaCentOSDVDorEverythinginstallationdiskimagepreparedonaCD/DVDdiscoraUSBdeviceinstaller).AlsoconnecttothecomputertheUSBstickcontainingthekickstartfileyoujustcreatedintheearliersteps(ifyouusingaUSBdriveforinstallingCentOSthenyouwillneedtwofreeUSBportsintotaltocompletethisrecipe).
18. Next,starttheserverandpressthecorrectkeyduringtheinitialbootupscreen,associatedwithbootingtheCentOSinstallationmediayoujustconnected.
19. AftertheCentOSinstallerstartsloading,thecommonstandardCentOS7installationwelcomescreenwillshowupandtheoptionTestthismedia&installCentOS7willbepre-selectedbythecursor.
20. Next,presstheEsckeyonyourkeyboardoncetoswitchtotheboot:prompt.21. Nowwearereadytostartthekickstartinstallation.Todothis,youneedtoknowthe
exactpartitionnameontheUSBdevicewherethekickstartfileislocated.Typethe
followingcommand,assumingthatyourpartitionisat/dev/sdc1(changethisasrequired),andpresstheReturnkeytostartthekickstartinstallationprocess:
linuxks=hd:sdc1:/anaconda-ks.cfg
NoteIfyoucannotfindouttherightdeviceandpartitionnameoftheUSBstick,youhavetostartthetargetsysteminrescuemode(refertotheTroubleshootingthesysteminrescuemoderecipe)toidentifytherightdevicenameandpartitionnumberbycomparingitssize,partitions,andidentifiedfilesystemswiththespecificationsofyourstick.
22. Thenewsystemnowgetsinstalledautomaticallyusingtheinstructionsfromtheprovidedkickstartfile.Youcanwatchtheinstallationoutputmessagesasitisshowingtheuserdetailedinstallationprogress.
23. Ifthesystemhasfinishedinstalling,rebootthesystemandlogintoyournewmachinetoverifythatthenewsystemhasbeensetupthewaywedescribedusingthekickstartfile.
HowitworksInthisrecipe,youhaveseenthateveryserverrunningaCentOS7installationkeepsthekickstartfileinitsrootdirectory,whichcontainsdetailedinformationonhowthesystemhadbeensetupduringtheinstallation.Thekickstartfilescanbeusedtoautomatetheinstallationsofmultiplesystemswiththesameconfiguration.Thiscansavealotoftimedoingrepetitiveworkasnouserinteractionduringinstallationisneeded.Also,wecanusethismethodifthetargetmachinesdontmeettheminimumrequirementinRAMforgraphicalbasedinstallationsbutwhenneededotherfeaturesthetextmodeinstallerdoesnotprovidesuchascustompartitioningofthesystem.Kickstartconfigurationfilesaresimpleplaintextfileswhichcanbecreatedmanuallyfromscratch.Becausetherearequiteanumberofdifferentcommandsavailabletoconstructyoursystemusingthekickstartsyntax,weusedanexistingfileasatemplateandcustomizedittofitourneeds,insteadofstartingoutcompletelynew.WedidnotusetheminimalinstallationimagetodriveourkickstartinstallationbecauseweinstalledsomeextrapackagesnotincludedontheminimalISOfile,suchastheApachewebserver.
GettingstartedandcustomisingthebootloaderWhenyouturnonyourcomputer,thebootloaderisthefirstprogramthatstartsupandisresponsibleforloadingandtransferringcontroltoanunderlyingoperatingsystem.Nowadays,almostanymodernLinuxdistributionusestheGRandUnifiedBootloaderversion2(GRUB2)forstartingthesystem.Ithasalotofflexibilityinconfigurationandsupportsalotofdifferentoperatingsystems.Inthisrecipe,wewillshowhowtocustomizetheGRUB2bootloaderbydisablingthewaitingtimeofthemenudisplayandthereforeimprovingthetimeittakesforbootingthesystem.
GettingreadyTocompletethisrecipe,youwillrequireaccesstoanalreadyinstalledCentOS7operatingsystem(minimaloranyotherCentOS7installationtypewillwork)withrootprivileges.Also,youneedtohavesomebasicexperienceswithatextbasededitor,suchasnano,forchangingtheconfigurationfiles.
HowtodoitWebeginthisrecipebyopeningthemainGRUB2configurationfilewithourtexteditorofchoiceandmodifyingit.
1. FirstloginasrootintoyoursystemandcreateacopyoftheGRUB2configurationfileforbackupandrollback,ifneeded.PresstheReturnkeytofinish:
cp/etc/default/grub/etc/default/grub.BAK
2. OpenthemainGRUB2configurationfilethatwewanttoeditwiththefollowingcommandandpresstheReturnkey(herewewillusetheeditornano,ifyouhavenotinstalledityettypeyuminstallnano):
nano/etc/default/grub
3. PresstheReturnkeyinthefirstlinewherethecursorisattoinsertanewlineatthetop,andtheninsertthefollowingline:
GRUB_HIDDEN_TIMEOUT=0
4. Adda#signtothebeginningofthefollowingline,asshown:
GRUB_TIMEOUT=0
5. NowsavethefileinthenanousingCtrl+o(andReturntoconfirmthefilenametosave).UseCtrl+xtoexittheeditorandthenrunthefollowingcommand:
dmesg|grep-Fq"EFIv"
6. Iftheprecedingcommanddoesnotproduceanyoutput,runthefollowingcommand:
grub2-mkconfig-o/boot/grub2/grub.cfg
7. Otherwise,ifthereisanoutput,run:
grub2-mkconfig-o/boot/efi/EFI/centos/grub.cfg
8. Ifgrub2-mkconfigissuccessful,itwillprintDone.Nowrebootyoursystemusingthefollowingcommand:
reboot
9. Duringtherebootingprocess,youwillnoticethattheGRUB2bootmenuwillnotappearanymoreandthesystemwillbootupfaster.
HowitworksHavingcompletedthisrecipe,wenowknowhowtocustomizetheGRUB2bootloader.Inthisveryeasyrecipe,weonlyshowedyouverybasicmodificationstothebootloaderbutitcandomuchmore!Itsupportsabroadvarietyoffilesystemsandcanbootalmostanycompatibleoperatingsystem.Thisisalsoparticularlyusefulifyouplantorunmultipleoperatingsystemsonthesamemachine.TolearnmoreaboutGRUB2sconfigurationfilesyntaxtypetheinfogrub2|lesscommandandgotothesection6.1Simpleconfigurationhandling(readtherecipeNavigatingtextfileswithlessinChapter2,ConfiguringtheSystemtolearnhowtobrowsethisdocument).
TroubleshootingthesysteminrescuemodeWeallmakemistakesandthisisespeciallytruefornoviceLinuxsystemadministrators.LinuxcanhaveasteeplearningcurveandsoonerorlatertherewillbeapointinyourcareerwhereyourCentOSinstallationdoesnotstartupduetobroadnumberofreasons,includinghardwareproblemsorhumanmistakessuchasconfigurationerrors.IfthishashappenedtoyouthenyoucanusetheCentOSrescuemodeinordertobootanotherwiseunbootablesystemandtrytoundoyourmistakesorfindouttherootoftheproblems.Inthisrecipe,wewillshowyouthreecommonusecaseswhentousethisoption:
AccessingthefilesystemforrecoveringimportantdataorundoingchangestoconfigurationfilesifCentOSisnotbootingupChangingtherootpasswordifyouforgotitRe-installingthebootloaderwhichcanbedamagedwheninstallinganotheroperatingsystemonthesameharddiskwhereCentOSisinstalled
GettingreadyTocompletethisrecipe,youwillrequireastandardinstallationmedia(CD/DVDorUSBdevice)oftheCentOS7operatingsystem.Forrecoveringthedatafromthesystem,youwillneedtoconnectsomesortofexternalstoragedevicetothesystem,suchasanexternalharddiskoraworkingnetworkconnectiontoanothercomputertocopyallyourpreciousdatatoadifferentlocation.
HowtodoitTobeginthisrecipe,youshouldbootyourserverfromtheCentOSinstallationCD/DVDortheUSBdeviceandwaituntilthefirstwelcomesplashscreenappearswiththecursorwaitingattheTestthismedia&installCentOS7menuoption.
Reachingrescuemode1. Fromthemainmenu,usethedownarrowkeytoselectTroubleshootingandthen
presstheReturnkeytoproceed.2. OntheTroubleshootingscreen,usethedownarrowkeytohighlightRescuea
CentOSsystem.Whenyouareready,presstheReturnkeytoproceed.3. Aftersomeloadingtime,weentertherescuescreen,whichincludesvarious
confirmationsub-screens.Tobeginthissection,usetheleftandrightarrowkeystochooseContinueandpresstheReturnkeytoproceed.
4. Onthefirstsub-screen,chooseOKandpresstheReturnkeytoproceed.5. Again,inthefollowingsub-screen,chooseOKandpresstheReturnkeytoproceed.6. Onthenextscreen,choosetheStartshellandbyusingtheTabkey,highlightOK
andpresstheReturnkeytoproceed.7. Bycompletingtheprecedingsteps,youwilllaunchashellsession.Youwillnotice
thisatthebottomofyourdisplay.Thecurrentstatusoftheshellsessionwillreadasfollows:
bash-4.2#_
8. Attheprompt,typethefollowinginstructiontochangetherootfilesystem,beforepressingtheReturnkeytocompleteyourrequest:
chroot/mnt/sysimage
9. Congratulations!Youjustreachedtherescuemode.Toexititatanytime,simplytypethefollowingcommandandthenpresstheReturnkeytocompleteyourrequest(dontdothisrightnowasthiswillrestartthesystem):
reboot
10. Afterthebasicrescuemodeisreached,wehavethefollowingoptions,dependingonthetypeofproblem.
AccessingthefilesystemIfyouarenowintherescuemodeandneedtobackupimportantfilesfromthefilesystem,youneedadestinationlocationforthedatatransfer.FortransferringthedatawewanttorecoverfromtheservertoanothercomputerpleasephysicallyconnectanexternalUSBdevicetoit.Youcanalsousenetworkstoragesfortherecovery.Forexample,youcouldimportanNFSservershareandcopydatatoit.RefertotheWorkingwithNFSrecipeinChapter7,BuildingaNetwork.
1. Ontherescuemodecommandline,typeinthefollowingcommand,whichwillshow
youallthecurrentpartitionsconnectedtothesystem,andthenpresstheReturnkeytocompleteyourrequest:
fdisk-l
2. Younowneedtofindouttherightdevicenamewiththepartitionnumberofyourconnecteddevice;comparingthetotalsizeorthefilesystemoutputofthevariousdeviceswiththespecificationsfromyourstickcanhelpyouinthisprocess.Youcanalsotrythefollowingtrick:runthefdisk-lcommandtwice,firstwiththeplugged-inUSBdeviceandthenagainwiththeUSBdeviceunplugged,andcomparetheoutputofboththecommands.Itshouldbedifferentbyonedevicenamewhichyouaresearchingfor!
3. Ifyouhavefoundtherightdevicenameinthelist,createadirectorytomountthesticktothefilesystem:
mkdir/mnt/hdd-recovery
4. Next,mountthediskpartitiontothisfolder.HereweassumethattheUSBdeviceofinteresthasthedevicenamesdd1(pleasechangeifdifferentonyoursystem):
mount/dev/sdd1/mnt/hdd-recovery
5. Theoriginalsystemsharddisksrootpartitionhasbeenmountedunderaspecificfolderbytherescuesystemautomatically(under/mnt/sysimage),ifyouneedtoaccessitforexampletochangeconfigurationfileswhichcausedstartupproblemsormakeafullorpartialbackup.Forexample,ifyouneedtobackupyourApachewebserverconfigurationfiles,use:
cp-r/mnt/sysimage/etc/http/mnt/hdd-recovery
6. Ifyouneedtoaccessthedatathatlivesonpartitionsotherthanthecurrentlymountedrootpartition,usefdisk-ltoidentifythepartitionofinterest.ThencreateadirectoryandmountthepartitiontoitandchangetothatdirectorytoaccessyourdatasimilaryoudidwhenmountingtheUSBdevice.
7. Tofinishbackingupthefiles,type:
reboot
Accessingthefilesystem1. Ifyouareintherescuemodeforchangingtherootpassword,justusethefollowing
commandandprovideanewpassword:
passwd
2. Tocompletechangingthepassword,type:
reboot
Re-installtheCentOSbootloader
1. Wewillnowusethefdiskcommandtofindthenameofallthecurrentpartitions.Todothis,typethefollowinginstructionandthenpresstheReturnkeytocompleteyourrequest:
fdiskl
2. Nowrunthefollowingcommand:
dmesg|grep-Fq"EFIv"
3. Iftheprecedingcommanddoesnotproduceanyoutputlookforthe*symbolinthefdisklistinginthebootcolumntofindthecorrectstartpartition,andassumingthatyourbootdiskison/dev/sda1(changethisasrequired),typethefollowing:
grub2-install/dev/sda
4. Otherwise,ifthereisanoutput,runinstead:
yumreinstallgrub2-efishim
5. Ifnoerrorisreported,theconsoleshouldrespondasfollows:
#thisdevicemapwasgeneratedbyanaconda(hd0)/dev/sda
6. TheconsoleoutputfromthelaststephasconfirmedthatGRUBhasnowbeensuccessfullyrestored.
7. Torebootthecomputer,type:
reboot
HowitworksThereareabroadvarietyofproblemswhichcanberesolvedbythetoolsprovidedthroughtherescuemodeenvironment.Oftentheseproblemsrefertobootingproblemsbutcanalsobefromdifferenttypes,suchasforgettingtherootpassword.Rescuemodecanbealife-saverandanunderstandingofitisaveryimportantskilltolearn.Itwasfeltthatsucharecipeshouldthusremaincloseathand.
TipRemembertoalwaysbecarefulwhenworkingwithbootloadercommandsasimproperusecanmakeyouroperatingsystemunbootable.
UpdatingtheinstallationandenhancingtheminimalinstallwithadditionaladministrationanddevelopmenttoolsInthisrecipe,wewilllearnhowtoenhancetheminimalinstallwithadditionaltoolsthatwillgiveyouavarietyofadministrativeanddevelopmentoptions,whichinturnwillprovevitalduringthelifetimeofyourserverandwhichareessentialforsomerecipesinthisbook.Theminimalinstallisprobablythemostefficientwayyoucaninstallaserver,buthavingsaidthat,aminimalinstalldoesrequiresomeadditionalfeaturesinordertomakeitamorecompellingmodel.
GettingreadyTocompletethisrecipe,youwillrequireaminimalinstallationoftheCentOS7operatingsystemwithrootprivilegesandaconnectiontotheInternetinordertofacilitatethedownloadofadditionalpackages.
HowtodoitWewillbeginthisrecipebyupdatingthesystem.
1. Toupdatethesystem,loginasrootandtype:
yum-yupdate
2. CentOSwillnowsearchfortherelevantupdatesand,ifavailable,theywillbeinstalled.Oncompletionanddependingonwhatwasupdated(thatis,kernelandnewsecurityfeaturestonamebutafew),youcandecidetorebootyourcomputer.Todothis,type:
reboot
3. Yourserverwillnowrebootandreturntotheloginscreen.Wewillnowcompletethisrecipeandenhanceourcurrentinstallationwithaseriesofpackagegroupsthatwillprovetobeveryusefulinthefuture.Todothis,loginasrootandtype:
yum-ygroupinstall"Base""DevelopmentLibraries""DevelopmentTools"yum-yinstallpolicycoreutils-python
HowitworksThepurposeofthisrecipeistoenhancetheminimalinstallationoftheCentOS7operatingsystemandbydoingthisyouhavenotonlyintroducedyourselftotheYellowdogUpdaterModified(YUM)packagemanager(somethingtowhichwewillreturntolateroninthisbook),butyounowhaveasystemthatiscapableofrunningavastamountofapplicationsrightout-of-the-box.
Sowhathavewelearnedfromthisexperience?
Westartedtherecipebyupdatingthesysteminordertoensurethatitisuptodate.Atthisstage,itisoftenagoodideatorebootthesystem.Itisnotexpectedthatwewilldothisveryoftenbutitisexpectedwhenupdatingforthefirsttimeaftertheinstallationoftheoperatingsystem,asitismostlikelythattherearemajorchangesavailable.Thereasonbehindthisistypicallybasedonthedesiretotakeadvantageofanewkernelorrevisedsecurityupdates.Inthenextphase,therecipeshowedyouhowtoaddaseriesofpackagegroupsthatmayprovetobemorethanusefulinthefuture.Tosavetime,wewrappedtheinstructiontoinstallthethreemainpackagegroups:Base,DevelopmentLibraries,andDevelopmentTools.Theprecedingactionaloneinstallsover200individualpackages,therebygivingyourservertheabilitytocompilethecodeandrunavastarrayofapplicationsout-of-the-box,thatyoumayneedoverthelifetimeofyourserver.Toseealistofallthepackageswithinagroup,forexample,fromBase,runtheyumgroupinfoBasecommand.Anotherpackageweinstalledwaspolicycoreutils-pythonwhichprovidestoolsandprogramstomanagethesecurityenhancedaccesscontroltoLinux,whichwewillusequiteoftenthroughoutthechaptersofthisbook.
Chapter2.ConfiguringtheSystemInthischapter,wewillcoverthefollowingtopics:
NavigatingtextfileswithlessIntroductiontoVimSpeakingtherightlanguageSynchronizingthesystemclockwithNTPandthechronysuiteSettingyourhostnameandresolvingthenetworkBecomingasuperuserBuildingastaticnetworkconnectionCustomizingyoursystembannersandmessagesPrimingthekernel
IntroductionThischapterisacollectionofrecipesthatcoversthebasicpracticeofestablishingthebasicneedsofaserver.Formany,buildingaservercanoftenseemtobeadauntingtask,andsothepurposeofthischapteristoprovideyouwithaninstantmethodtoachievethedesiredgoals.
NavigatingtextfileswithlessThroughoutthisbook,youwilloftenuseprogramsandtoolsthatusetheprogramlessoraless-likenavigationtoviewandreadfilecontentordisplayoutput.Atfirst,thecontrolcanseemabitunintuitive.Here,inthisrecipe,wewillshowyouthebasicsofhowtonavigatethroughafileusinglesscontrols.
GettingreadyTocompletethisrecipe,youwillrequireaworkinginstallationoftheCentOS7operatingsystemwithrootprivileges.
Howtodoit1. Tobegin,loginasrootandtypethefollowingcommandtoopenaprogramthatuses
lessfornavigation:
manman
2. Tonavigate,presstheupanddownkeytoscrollupanddownonelineatatime,thespacebartoscrolldownapage,andthebkeytoscrollupapage.Youcansearchwithinthetextusingtheforwardslashkey,/,followedbythesearchterm,thenpressReturntosearch.Pressntojumptothenextsearchresult.Presstheqkeytoexit.
HowitworksHere,inthisshortrecipe,wehaveshownyoutheverybasicsoflessnavigation,whichisessentialforreadingmanpagesandisusedbyalotofotherprogramsthroughoutthisbooktodisplaytext.Weonlyshowedyouthebasiccommandsandthereismuchmoretolearn.Pleasereadthelessmanualtofindoutmoreonmanlesscommand.
IntroductiontoVimInthisrecipe,wewillgiveyouaverybriefintroductiontothetexteditor,Vim,whichisusedasthestandardtexteditorthroughoutthisbook.Youcanalsouseanyothertexteditoryouprefer,suchasnanooremacs,instead.
GettingreadyTocompletethisrecipe,youwillrequireaworkinginstallationoftheCentOS7operatingsystemwithrootprivileges.
HowtodoitWewillstartthisrecipebyinstallingthevim-enhancedpackage,asitcontainsatutorialyoucanusetolearnworkingwithVim:
1. Tobegin,loginasrootandinstallthefollowingpackage:
yuminstallvim-enhanced
2. Afterwards,typethefollowingcommandtostarttheVimtutorial:
vimtutor
3. ThiswillopentheVimtutorialintheVimeditor.Tonavigate,presstheupanddownkeytoscrollupanddownsingle-linewise.Toexitthetutorial,presstheEsckey,thentype:q!,followedbytheReturnkeytoexit.
4. YoushouldnowreadthroughthefileandgothroughthelessonstogetabasicunderstandingofVim,tolearnhowtoedityourtextdocuments.
HowitworksThetutorialshowninthisrecipeshouldbeseenasastartingpointfromwhichtolearnthebasicsforworkingwithoneofthemostpowerfulandeffectivetexteditorsavailableforLinux.Vimhasaverysteeplearningcurve,butafterdedicatingabouthalfanhourtothevimtutorguideyoushouldbeabletodoallthecommontexteditingtaskswithoutanyproblem,suchasopening,editing,andsavingtextfiles.
SpeakingtherightlanguageInthisrecipe,wewillshowyouhowtochangethelanguagesettingsofyourCentOS7installationforthewholesystemandforsingleusers.Theneedtochangethisisrarebutcanbeimportant,forexampleifweaccidentallychosethewronglanguageduringinstallation.
GettingreadyTocompletethisrecipe,youwillrequireaworkinginstallationoftheCentOS7operatingsystemwithrootprivileges,andaconsole-basedtexteditorofyourchoice.YoushouldhavereadtheNavigatingtextfileswithlessrecipe,becausesomecommandsinthisrecipewilluselessforprintingoutput.
HowtodoitTherearetwocategoriesofsettingsthatyouhavetoadjustifyouwanttochangethesystem-widelanguagesettingsofyourCentOS7system.Webeginbychangingthesystemlocaleinformationandthenthekeyboardsettings:
1. Tobegin,loginasrootandtypethefollowingcommandtoshowthecurrentlocalesettingsfortheconsole,graphicalwindowmanagers(X11layout),andalsothecurrentkeyboardlayout:
localectlstatus
2. Next,tochangethesesettings,wefirstneedtoknowalltheavailablelocaleandkeyboardsettingsonthissystem(bothcommandsuselessnavigation):
localectllist-localeslocalectllist-keymaps
3. Ifyouhavepickedtherightlocalefromtheoutputaboveinourexample,de_DE.utf8andkeymapde-mac(changetoyourownappropriateneeds),youcanchangeyourlocaleandkeyboardsettingsusing:
localectlset-localeLANG=de_DE.utf8localectlset-keymapde-mac
4. Now,verifythepersistenceofyourchangesusingthesamecommandagain:
localectlstatus
HowitworksAswehaveseen,thelocalectlcommandisaveryconvenienttoolthatcantakecareofmanagingallimportantlanguagesettingsinaCentOS7system.
Sowhathavewelearnedfromthisexperience?
Westartedbyloggingintoourcommandlinewiththerootuser.Then,weranthelocalectlcommandwiththeparameterstatus,whichgaveusanoverviewofthecurrentlanguagesettingsinthesystem.TheoutputofthiscommandshowedusthatlanguagepropertiesinaCentOS7systemcanbeseparatedintolocale(systemlocale)andkeymap(VCkeymapandallX11layoutproperties)settings.
LocalesonLinuxareusedtosetthesystemslanguageaswellasotherlanguage-specificproperties.Thiscanincludetextsfromerrormessages,logoutput,userinterfaces,and,ifyouareusingawindowmanagersuchasGnome,evenGraphicalUserInterfaces(GUI).Localesettingscanalsodefineregion-specificformattingsuchaspapersizes,numbersandtheirnaturalsorting,currencyinformation,andsoon.Theyalsodefinecharacterencoding,whichcanbeimportantifyouchosealanguagethathascharactersthatcannotbefoundinthestandardASCIIencoding.
Keymapsettingsontheotherhanddefinetheexactlayoutofeachkeyonyourkeyboard.
Next,tochangethesesettings,wefirstissuedthelocalectlcommandwiththelist-localesparametertoretrieveafulllistofalllocalesonthesystem,andlist-keymapstoshowalistofallkeyboardsettingsavailableinthesystem.Localesasoutputtedfromthelist-localesparameteruseaverycompactannotationfordefiningalanguage:
Language[_Region][.Encoding][@Modificator]
OnlytheLanguagepartismandatory,alltherestisoptional.Examplesforlanguageandregionare:en_USforEnglishandregionUnitedStatesorAmericanEnglish,es_CUwouldbelanguageSpanishandRegionCubaorCubanSpanish.
EncodingsareimportantforspecialcharacterssuchasGermanumlautoraccentsintheFrenchlanguage.Thememoryrepresentationofthesespecialcharacterscanbeinterpreteddifferentlydependingontheusedencodingtype.IngeneralUTF-8shouldbeusedasitiscapableofencodingalmostanycharacterineverylanguage.
Modificatorsareusedtochangesettingsdefinedbythelocale.Forexample,sr_RS.utf8@latinisusedifyouwanttohaveLatinsettingsforserbianSerbia,whichnormallyusesCyrillicdefinitions.Thiswillchangetowesternsettingssuchassorting,currencyinformation,andsoon.
Tochangetheactuallocale,weusedtheset-localeLANG=de_DE.utf8parameter.Here,theencodingwasselectedtodisplayproperGermanumlauts.PleasenotethatweusedtheLANGoptiontosetthesamelocalevalue(forexample,de_DE.utf8)forallavailablelocaleoptions.Ifyoudontwanttohavethesamelocalevalueforallavailableoptions,youcanuseamorefine-grainedcontroloversinglelocaleoptions.Pleaserefertothelocaledescriptionusingthemanpage,man7locale(onminimalinstallation;youneedto
installallLinuxdocumentationmanpagesbeforeusingtheyuminstallman-pagescommand).Youcansettheseadditionaloptionsusingasimilarsyntax,forexample,tosetthetimelocaleuse:
localectlset-localeLC_TIME="de_DE.utf8"
Next,weshowedallavailablekeymapcodesusingthelist-keymapsparameter.Aswehaveseenfromrunninglocalectlstatus,thekeymapscanbeseparatedinnon-graphical(VCkeymap)andgraphical(X11layout)settings,whichallowstheflexibleconfigurationofdifferentkeyboardlayoutswhenusingawindowmanagersuchasGnomeandfortheconsole.Runninglocalectlwiththeparameter,set-keymapde-mac,setsthecurrentkeymaptoaGermanAppleMacintoshkeyboardmodel.ThiscommandappliesthegivenkeyboardtypetoboththenormalVCandtheX11keyboardmappings.IfyouwantdifferentmappingsforX11thanfortheconsole,uselocalectl--no-convertset-x11-keymapcz-querty,whereweusecz-quertyforthekeymapcodetoaCzechquertykeyboardmodel(changethisaccordingly).
TheresmoreSometimes,singlesystemusersneeddifferentlanguagesettingsthanthesystemslocale(whichcanonlybesetbytherootuser),accordingtotheirregionalkeyboarddifferencesandforinteractingwiththesystemintheirpreferredhumanlanguage.System-widelocalesgetinheritedbyeveryuseraslongastheyarenotoverwrittenbylocalenvironmentvariables.
NoteChangingsystem-widelocalesdoesnotnecessarilyhaveaneffectonyouruserslocalesiftheyhavealreadydefinedsomethingelseforthemselves.
Toprintallthecurrentlocaleenvironmentvariablesforanysystemuser,wecanusethecommand,locale.Tosetsingleenvironmentvariableswiththeappropriatevariablename;forexample,tosetthetimelocaletoUStimewewouldusethefollowingline:
exportLC_TIME="en_US.UTF-8"
But,mostlikelywewouldwanttochangeallthelocalestothesamevalue;thiscanbedonebysettingLANG.Forexample,tosetallthelocalestoAmericanEnglish,usethefollowingline:
exportLANG="en_US.UTF-8"
Totesttheeffectoflocalechanges,wecannowproduceanerrormessagethatwillbeshowninthelanguagesetbythelocalecommand.HereisthedifferentlanguageoutputforchanginglocalefromEnglishtoGerman:
exportLANG="en_US.UTF-8"ls!
Thefollowingoutputwillbeprinted:
ls:cannotaccess!:Nosuchfileordirectory
Now,changetoGermanlocalesettings:
exportLANG="de_DE.UTF-8"ls!
Thefollowingoutputwillbeprinted:
ls:Zugriffauf!nichtmglich:DateioderVerzeichnisnichtgefunden
Settingalocaleinanactiveconsoleusingtheexportcommandwillnotsurviveclosingthewindoworopeninganewterminalsession.Ifyouwanttomakethosechangespermanent,youcansetanylocaleenvironmentvariables,suchastheLANGvariable,inafilecalled.bashrcinyourhomedirectory,whichwillbereadeverytimeashellisopened.Tochangethelocalesettingspermanentlytode_DE.UTF-8inourexample(changethistoyourownneeds)usethefollowingline:
echo"exportLANG='de_DE.UTF-8'">>~/.bashrc
SynchronizingthesystemclockwithNTPandthechronysuiteInthisrecipe,wewilllearnhowtosynchronizethesystemclockwithanexternaltimeserverusingtheNetworkTimeProtocol(NTP)andthechronysuite.Fromtheneedtotime-stampdocuments,e-mails,andlogfiles,tosecuring,running,anddebugginganetwork,ortosimplyinteractwithshareddevicesandservices,everythingonyourserverisdependentonmaintaininganaccuratesystemclock,anditisthepurposeofthisrecipetoshowyouhowthiscanbeachieved.
GettingreadyTocompletethisrecipe,youwillrequireaworkinginstallationoftheCentOS7operatingsystemwithrootprivileges,aconsole-basedtexteditorofyourchoice,andaconnectiontotheInternettofacilitatedownloadingadditionalpackages.
HowtodoitInthisrecipe,wewillusethechronyservicetomanageourtimesynchronization.AschronyisnotinstalledbydefaultonCentOSminimal,wewillstartthisrecipebyinstallingit:
1. Tobegin,loginasrootandinstallthechronyservice,thenstartitandverifythatitisrunning:
yuminstall-ychronysystemctlstartchronydsystemctlstatuschronyd
2. Also,ifwewanttousechronypermanently,wewillhavetoenableitonserverstartup:
systemctlenablechronyd
3. Next,weneedtocheckwhetherthesystemalreadyusesNTPtosynchronizeoursystemclockoverthenetwork:
timedatectl|grep"NTPsynchronized"
4. IftheoutputfromthelaststepshowedNoforNTPsynchronized,weneedtoenableitusing:
timedatectlset-ntpyes
5. Ifyourunthecommand(fromstep3)again,youshouldseethatitisnowsynchronizingNTP.
6. Thedefaultinstallationofchronywilluseapublicserverthathasaccesstotheatomicclock,butinordertooptimizetheservicewewillneedtomakeafewsimplechangestostreamlineandoptimizeatwhattimeserversareused.Todothis,openthemainchronyconfigurationfilewithyourfavoritetexteditor,asshownhere:
vi/etc/chrony.conf
7. Inthefile,scrolldownandlookforthelinescontainingthefollowing:
server0.centos.pool.ntp.orgiburstserver1.centos.pool.ntp.orgiburstserver2.centos.pool.ntp.orgiburstserver3.centos.pool.ntp.orgiburst
8. Replacethevaluesshownwithalistofpreferredlocaltimeservers:
server0.uk.pool.ntp.orgiburstserver1.uk.pool.ntp.orgiburstserver2.uk.pool.ntp.orgiburstserver3.uk.pool.ntp.orgiburst
NoteVisithttp://www.pool.ntp.org/toobtainalistoflocalserversgeographicallynearyourcurrentlocation.Remember,theuseofthreeormoreserverswillhavea
http://www.pool.ntp.org/
tendencytoincreasetheaccuracyoftheNTPservice.
9. Whencomplete,saveandclosethefilebeforesynchronizingyourserverusingthesytstemctlcommand:
systemctlrestartchronyd
10. Tocheckwhetherthemodificationsintheconfigfileweresuccessful,youcanusethefollowingcommand:
systemctlstatuschronyd
11. Tocheckwhetherchronyistakingcareofyoursystemtimesynchronization,usethefollowing:
chronyctracking
12. Tocheckthenetworksourceschronyusesforsynchronization,usethefollowing:
chronycsources
HowitworksOurCentOS7operatingsystemstimeissetoneverybootbasedonthehardwareclock,whichisasmall-batterydrivenclocklocatedonthemotherboardofyourcomputer.Often,thisclockistooinaccurateorhasnotbeensetright,thereforeitsbettertogetyoursystemtimefromareliablesourceovertheInternet(thatusesrealatomictime).Thechronydaemon,chronyd,setsandmaintainssystemtimethroughaprocessofsynchronizationwitharemoteserverusingtheNTPprotocolforcommunication.
So,whathavewelearnedfromthisexperience?
Asafirststep,weinstalledthechronyservice,sinceitisnotavailablebydefaultonaCentOS7minimalinstallation.Afterwards,weenabledthesynchronizationofoursystemtimewithNTPusingthetimedatectlset-ntpyescommand.
Afterthat,weopenedthemainchronyconfigurationfile,/etc/chrony.conf,andshowedhowtochangetheexternaltimeserversused.ThisisparticularlyusefulifyourserverisbehindacorporatefirewallandhaveyourownNTPserverinfrastructure.
Havingrestartedtheservice,wethenlearnedhowtocheckandmonitorournewconfigurationusingthechronyccommand.Thisisausefulcommandlinetool(cstandsforclient)forinteractingandcontrollingachronydaemon(locallyorremotely).Weusedthetrackingparameterwithchronyc,whichshowedusdetailedinformationofthecurrentNTPsynchronizationprocesswithaspecificserver.Pleaserefertothemanpagesofthechronyccommandifyouneedfurtherhelpaboutthepropertiesshownintheoutput(manchronyc).
Wealsousedthesourcesparameterwiththechronycprogram,whichshowedusanoverviewoftheusedNTPtimeservers.
Youcanalsousetheolderdatecommandtovalidatecorrecttimesynchronization.Itisimportanttorealizethattheprocessofsynchronizingyourservermaynotbeinstantaneous,anditcantakeawhilefortheprocesstocomplete.However,youcannowrelaxinthefullknowledgethatyounowknowhowtoinstall,manageandsynchronizeyourtimeusingtheNTPprotocol.
TheresmoreInthisrecipe,wesetoursystemstimeusingthechronyserviceandtheNTPprotocol.Usually,systemtimeissetasCoordinatedUniversalTime(UTC)orworldtime,whichmeansitisonestandardtimeusedacrossthewholeworld.Fromit,weneedtocalculateourlocaltimeusingtimezones.Tofindtherighttimezone,usethefollowingcommand(readtheNavigatingtextfileswithlessrecipetoworkwiththeoutput):
timedatectllist-timezones
Ifyouhavefoundtherighttimezone,writeitdownanduseitinthenextcommand;forexample,ifyouarelocatedinGermanyandarenearthecityofBerlin,usethefollowingcommand:
timedatectlset-timezoneEurope/Berlin
Usetimedatectlagaintocheckifyourlocaltimeiscorrectnow:
timedatectl|grep"Localtime"
Finally,ifitiscorrect,youcansynchronizeyourhardwareclockwithyoursystemtimetomakeitmoreprecise:
hwclock--systohc
SettingyourhostnameandresolvingthenetworkTheprocessofsettingthehostnameistypicallyassociatedwiththeinstallationprocess.IfyoueverneedtochangeitoryourserversDomainNameSystem(DNS)resolver,thisrecipewillshowyouhow.
GettingreadyTocompletethisrecipe,youwillrequireaworkinginstallationoftheCentOS7operatingsystemwithrootprivileges,andaconsole-basedtexteditorofyourchoice.
HowtodoitTobeginthisrecipe,weshallstartbyaccessingthesystemasrootandopeningthefollowingfileinordertonameorrenameyourcurrentservershostname:
1. Loginasrootandtypeinthefollowingcommandtoseethecurrenthostname:
hostnamectlstatus
2. Now,changethehostnamevaluetoyourpreferredname.Forexample,ifyouwanttocallyourserverjimi,youwouldtype(changeappropriately):
hostnamectlset-hostnamejimi
NoteStatichostnamesarecase-sensitiveandrestrictedtousinganInternet-friendlyalphanumericstringoftext.Theoveralllengthshouldbenolongerthan63characters,buttrytokeepitmuchshorter.
3. Next,weneedtheIPaddressoftheserver.Typeinthefollowingcommandtofindit(youneedtoidentifythecorrectnetworkinterfaceintheoutput):
ipaddrlist
4. Afterwards,wewillsettheFullyQualifiedDomainName(FQDN),inordertodothis,wewillneedtoopenandeditthehostsfile:
vi/etc/hosts
5. Here,youshouldaddanewlineappropriatetoyourneeds.Forexample,ifyourservershostnamewascalledjimi,(withanIPaddressof192.168.1.100,andadomainnameofhenry.com)yourfinallinetoappendwilllooklikethis:
192.168.1.100jimi.henry.comjimi
NoteForaserverfoundonalocalnetworkonly,itisadvisabletouseanon-Internetbasedtop-leveladdress.Forexample,youcoulduse.localor.lan,oreven.home,andbyusingthesereferencesyouwillavoidanyconfusionwiththetypical.com,.co.uk,or.netdomainnames.
6. Next,wewillopentheresolv.conffile,whichisresponsibleforconfiguringstaticDNSserveraddressesthatthesystemwilluse:
vi/etc/resolv.conf
7. Replacethecontentofthefilewiththefollowing:
#usegooglefordnsnameserver8.8.8.8nameserver8.8.4.4
8. Whencomplete,saveandcloseyourfilebeforerebootingyourservertoallowthe
changestotakeimmediateeffect.Todothis,returntoyourconsoleandtype:
reboot
9. Onasuccessfulreboot,youcannowcheckyournewhostnameandFQDNbytypingthefollowingcommandsandwaitingfortheresponse:
hostname--fqdn
10. TotestifwecanresolvedomainnamestoIPaddressesusingourstaticDNSserveraddresses,usethefollowingcommand:
ping-c10google.com
HowitworksAhostnameisauniquelabelcreatedtoidentifyamachineonanetwork.Itisrestrictedtoalphanumeric-basedcharacters,andmakingachangetoyourservershostnamecanbeachievedbyusingthehostnamectlcommand.ADNSserverisusedtotranslatedomainnamestoIPaddresses.ThereareseveralpublicDNSserversavailable;inalaterrecipe,wewillbuildourownDNSservice.
So,whathavewelearnedfromthisexperience?
Inthefirststageoftherecipe,wechangedthecurrenthostnameusedbyourserverwiththehostnamectlcommand.Thiscommandcansetthreedifferenttypesofhostnames.Usingthecommandwiththeset-hostnameparameterwillsetthesamenameforallthreehostnames:thehigh-levelprettyhostname,whichmightincludeallkindsofspecialcharacters(forexample,Lennart'sLaptop),thestatichostnamewhichisusedtoinitializethekernelhostnameatboot(forexamplelennarts-laptop),andthetransienthostname,whichisadefaultreceivedfromnetworkconfigurations.
Followingthis,wesettheFQDNofourserver.AFQDNisthehostnamealongwithadomainnameafterit.AdomainnamegetsimportantwhenyouarerunningaprivateDNS,orallowingexternalaccesstoyourserver.BesidesusingaDNSserversettingtheFQDNcanbeachievedbyupdatingthehostsfilefoundat/etc/hosts.
ThisfileisusedbyCentOStomaphostnamestoanIPaddress,anditisoftenfoundtobeincorrectonanew,un-configured,orrecentlyinstalledserver.Forthisreason,wefirsthadtofindouttheIPaddressoftheserverusingipaddrlist.
AnFQDNshouldconsistofashorthostnameandthedomainname.Basedontheexampleshowninthisrecipe,wesettheFQDNforaservernamedhenry,whoseIPaddressis192.168.1.100anddomainnameishenry.com.
Savingthisfilewouldarguablycompletethisprocess.However,becausethekernelmakesarecordofthehostnameduringthebootprocess,thereisnochoicebuttorebootyourserverbeforeyoucanusethechangedsettings.
Next,weopenedthe