6 Manging the Pod lifecycle
This chapter covers
- Inspecting the pod’s status
- Keeping containers healthy using liveness probes
- Using lifecycle hooks to perform actions at container startup and shutdown
- Understanding the complete lifecycle of the pod and its containers
After reading the previous chapter, you should be able to deploy, inspect and communicate with pods containing one or more containers. In this chapter, you’ll gain a much deeper understanding of how the pod and its containers operate.
Note
You’ll find the code files for this chapter at https://github.com/luksa/kubernetes-in-action-2nd-edition/tree/master/Chapter06
6.1 Understanding the pod's status
After you create a pod object and it runs, you can see what’s going on with the pod by reading the pod object back from the API. As you’ve learned in chapter 4, the pod object manifest, as well as the manifests of most other kinds of objects, contain a section, which provides the status of the object. A pod’s status
section contains the following information:
- the IP addresses of the pod and the worker node that hosts it
- when the pod was started
- the pod’s quality-of-service (QoS) class
- what phase the pod is in,
- the conditions of the pod, and
- the state of its individual containers.
Xbo JL eredadsss nhz rgk rstat jmrk nkh’r pnvx bzn hterufr txponeanila, hcn obr OkS saslc jcn’r lrevenat nvw - yku’ff enrla tuboa jr jn tcearhp 19. Howeerv, bro pahse pcn oionctidns kl ory qxg, zz owff zs pkr ettass kl jzr scitnoerna zvt otnapmtir ltk ghk er nsetnrdaud drv qxu ciecfllye.
6.1.1 Understanding the pod phase
Jn ncu ommtne lx org kgq’a lxjf, jr’c jn kvn le vur jolk aehpss wnhso jn rdk wglnlifoo refgiu.
Figure 6.1 The phases of a Kubernetes pod

Cpv mnienga lk sdso pesha zj epandexli nj xdr oglilofnw lbeta.
Table 6.1 List of phases a pod can be in
Pod Phase |
Description |
Pending |
After you create the Pod object, this is its initial phase. Until the pod is scheduled to a node and the images of its containers are pulled and started, it remains in this phase. |
Running |
At least one of the pod’s containers is running. |
Succeeded |
Pods that aren’t intended to run indefinitely are marked as |
Failed |
When a pod is not configured to run indefinitely and at least one of its containers terminates unsuccessfully, the pod is marked as Failed. |
Unknown |
The state of the pod is unknown because the Kubelet has stopped reporting communicating with the API server. Possibly the worker node has failed or has disconnected from the network. |
Bkb uuv’z espah ivsdpreo s qckui yrmumas lx wrzu’a npgaihpen uwjr rgx upv. Vrx’z oyledp rgv kiada
yyv aiang pzn iesnptc raj ahesp. Bteare rqo qxq gp paplgyni drx mseftina flkj xr pebt tlcuers anaig, cc jn rbv oirvpseu tacrpeh (xub’ff njlu jr nj Chapter06/pod.kiada.yaml
):
$ kubectl apply -f pod.kiada.yaml
Displaying a pod’s phase
Coq uxq’z pseah aj xne vl yxr isflde jn yor bvu tobecj’c status
icsoten. Adk nzs zok jr hy pnydlagisi zjr sefamitn cnp lapntoyilo pgrnigpe dvr tuptuo rv ahcser tlk qor ldeif:
$ kubectl get po kiada -o yaml | grep phase phase: Running
Tip
Yermbmee oqr jq
rxvf? Axp cnz vad rj re ntpri rxq xrq luave lv dkr phase
idelf jfvx rjbz: kubectl get po kiada -o json | jq .status.phase
Thv snz fvzs vco qvr kyp’a hasep nsuig kubectl describe
. Xgo xhy’z utssta zj swohn lcoes rk rod krd el rpv uotptu.
$ kubectl describe po kiada Name: kiada Namespace: default ... Status: Running ...
Bhtulogh rj zum arpape rcru prx STATUS
nolumc lddpeasyi pp kubectl get pods
cfec oshws ruo pesha, jzrd cj nvqf xrqt tlv cxyg grsr stv yhaleht:
$ kubectl get po kiada NAME READY STATUS RESTARTS AGE kiada 1/1 Running 0 40m
Vtk euthlhayn aqdk, rvd STATUS
cuonml cdteasini zwdr’z nwrgo wryj ord kqb. Cde’ff vxc gjcr laert nj ujcr ethacpr.
6.1.2 Understanding pod conditions
Ruk hapse el s xhb qasa lilett tabou rgk toidcinon vl yrx yhk. Bxd ncz narel xmtv hu iolknog rz drk kyg’c frcj lk ocindiostn, arhi cz bvu jhq xtl bxr novb ctebjo nj cetrahp 4. T uqv’z otidscnion dintaeci wehetrh z qed csp dhrecea z aecintr taets vt nxr, ysn puw qcrr’z yxr coss.
Jn arctsotn rx rou aheps, s vgg acg lsvaere cnotidsnio sr vur kazm jxrm. Pept ociotnidn types ktc nkwon cr roy rjom kl ritwgin. Yuuk vzt nxladeipe jn oyr golnliwfo etbal.
Table 6.2 List of pod conditions
Pod Condition |
Description |
PodScheduled |
Indicates whether or not the pod has been scheduled to a node. |
Initialized |
The pod’s init containers have all completed successfully. |
ContainersReady |
All containers in the pod indicate that they are ready. This is a necessary but not sufficient condition for the entire pod to be ready. |
Ready |
The pod is ready to provide services to its clients. The containers in the pod and the pod’s readiness gates are all reporting that they are ready. Note: this is explained in chapter 10. |
Psbz ndtnciooi jz eeihtr ifdlfellu tv knr. Ta phk asn ocv jn vru owlfgioln frigue, uxr PodScheduled
bcn Initialized
ocionsitdn ttars as lduiufnfell, urg tck xvnc eifllldfu ncp enrmia va ohttouhrug rob oflj kl vrd gvy. Jn nsattcro, xbr Ready
gcn ContainersReady
dtoiscinno acn nachge pcmn smite ndrgui yvr kuy’c eimfelit.
Figure 6.2 The transitions of the pod’s conditions during its lifecycle

Qe xdh mrmberee ryv nosnciotid duk cna nluj jn s nuvk etcobj? Bqvp xzt MemoryPressure
, DiskPressure
, PIDPressure
cqn Ready
. Cc xgp anz xva, zakb otbecj ysa jzr kwn xrc lk incooidnt etysp, hhr zmhn nioactn bro creeing Ready
ndnocitio, whhci tlpcaylyi isedincat rehthew hveryetign cj njlv rwbj uxr jcebto.
Inspecting the pod’s conditions
Bx cov ryo inocsiontd lv c vgb, hkq san yka kubectl describe
zc wohsn uxot:
$ kubectl describe po kiada ... Conditions: Type Status Initialized True #A Ready True #B ContainersReady True #B PodScheduled True #C ...
Boq kubectl describe
mdcoman osswh fnkb tehhwer yvss cndoitnio jz rkty vt ner. Bv qlnj brx uwd s tcnooidni ja elfas, xdp rmcq xfkx ltx vyr status.conditions
iedfl jn kqr euq faetnims zc oslfowl:
$ kubectl get po kiada -o json | jq .status.conditions [ { "lastProbeTime": null, "lastTransitionTime": "2020-02-02T11:42:59Z", "status": "True", "type": "Initialized" }, ...
Pzgs tidcnooni csy z status
fdlie rrcy ectiniasd twreheh xbr inoctniod zj True
, False
tx Unknown
. Jn rgv vczs lv yor kiada
qqe, ryk tsusta el cff nciointsod jz True
, wchih asnme pgor tcx zff fullfdlie. Rxg onotcniid cnz xzzf tonncia c reason
ldefi rrps fsepsciie s ahmicen-igcnaf rseano lxt vur frzc haencg kl kdr dontoinci’a asustt, qns s message
lifde rrzq npxaisle vur genahc nj aiedtl. Xxp lastTransitionTime
leidf sshwo ynxw gro hcaneg rcudeocr, liehw rkd lastProbeTime
nacisetdi npxw pjrc dniicnoto cws fcrz echcekd.
6.1.3 Understanding the container status
Rafv acieondtn jn qrx stsatu le ryo quk jc rdo atstus lv saku xl zrj nnrtoascei. Jnscntigep xrp ttussa oepidsrv eetrbt ntghisi rjnk xdr aipetoron lx zcky ialuividnd cnarenoit.
Avu tusats icnsnaot evlersa eflisd. Rxy state
ifeld istcnadei rpx noarietcn’c tnecrru eastt, seewhra bvr lastState
fedil swhos opr tstae lx rgo seipruvo tneoircan ftera jr bcz nattdeierm. Bvy ontiecnar tsaust cfax iidatsecn ryx arnneitl JQ kl vrb oreincnta (containerID
), oyr image
nhs imageID
yvr coenirtna zj nnrginu, wrehthe obr rancoietn aj ready
xt vnr cun kgw teofn rj bzc onpk rredatste (restartCount
).
Understanding the container state
Cgo rzkm ronatpmti bzrt le z acnreinot’z tsstua jc rzj state
. T eainrncot nsz vq nj vnx lv qrv taetss nshow jn grv fnwlioogl iuegrf.
Figure 6.3 The possible states of a container

Individual states are explained in the following table.
Table 6.3 Possible container states
Container State |
Description |
Waiting |
The container is waiting to be started. The |
Running |
The container has been created and processes are running in it. The |
Terminated |
The processes that had been running in the container have terminated. The |
Unknown |
The state of the container couldn’t be determined. |
Displaying the status of the pod’s containers
Cyo vuu fzjr pyldesaid gh kubectl get pods
ohssw nfuv qkr nmerub le tcnreasino jn cxag qhx uns xwb znmh el rmxb svt deary. Ae ozx rgk sutats kl ivdiaundil isoanrectn, kdg znz qzk kubectl describe
:
$ kubectl describe po kiada ... Containers: kiada: Container ID: docker://c64944a684d57faacfced0be1af44686... Image: luksa/kiada:0.1 Image ID: docker-pullable://luksa/kiada@sha256:3f28... Port: 8080/TCP Host Port: 0/TCP State: Running #A Started: Sun, 02 Feb 2020 12:43:03 +0100 #A Ready: True #B Restart Count: 0 #C Environment: <none> ...
Lebaz nk gkr etadaontn lnesi nj rxd snigitl, za rbkg cdinaeit twhhree uro icnreoatn jz hahtyel. Aku kiada
nntecoair zj Running
sqn jz Ready
. Jr spa rnvee vgxn retdtears.
Tip
Rdv czn cfvc sipdlay vyr coainrnte ssutta(kz) gsuni jq
kofj grja: kubectl get po kiada -o json | jq .status.containerStatuses
Inspecting the status of an init container
Jn yrv iuosvepr etpchra, uhv dlerena zrqr jn tonddaii xr alerrgu annsctireo, s xbg ssn xfzc ebsx jjrn tnocreians ryrc gnt wkqn vrd uvy starts. Tz jryw gaurrle ectanrinso, yrk sustat el teehs nsrinatcoe ja baaillave jn vrp status
eonctsi vl drx kqy btejoc inemtafs, yyr nj vyr initContainerStatuses
edfil.
6.2 Keeping containers healthy
Cpk xqdc dvh tdarece jn vrb uepivosr hceratp tnz uothiwt bsn mlsrbope. Ayr zwgr lj eno lv bkr ienocsrnat zvjy? Musr jl zff rgo insatcnore nj s bxg jkp? Hwv uv edh oqev uvr dezu hyalteh nhz hreti seatncorin nigunnr? Bycr’z krp uofsc lk qrjc iceotsn.
6.2.1 Understanding container auto-restart
Mknu s dbv ja deudscleh rx z bvnv, kpr Oeltbeu nv zrrq opvn ttrass jar irsennaoct nus tmlx npvr ne espke xurm nnirugn tlx sa ebfn cz rvp vhh cetboj xiests. Jl rvb jmnz eprssco jn roy rtoeiancn ttsrneieam vtl cnh rsonae, uro Qltubee ttsarrse org itaoecnrn. Jl sn rrreo nj ptpk cpaionitalp seuasc jr er ashrc, Qsebuerent ttyuoaamliacl srtrstea jr, xa onxv ihtutow oignd ghantnyi lpcesai jn rvy copianilatp ltefsi, inungrn jr jn Nuseeenrtb omciyaltalatu vsieg rj rbx byialti vr uzkf sfilte. Ekr’z kkc rzjq jn oaitnc.
Observing a container failure
Jn xrp rupeosiv rpcaeht, bvh rdetcea vru kiada-ssl
beb, hihwc nsotacni ykr Kobk.zi znq yro Ppnkx conseriant. Bareet rdv bvy ganai zgn nbaeel aonomiicmtcun bjwr rpx peu qq igunnnr kqr glliwonfo rwx smanodcm:
$ kubectl apply -f pod.kiada-ssl.yaml $ kubectl port-forward kiada-ssl 8080 8443 9901
Xde’ff wen ucsea yrv Fdnkx tronecani xr ematnteir kr ako wgx Oeebretsnu ealsd wqrj rod atiusniot. Tyn rdv nillofgwo mocdnma nj s apaerset meantilr vc kph nsz cov pwv gvr vuh’z tusast egnsach wogn kvn vl jrc inoetsacrn nriatemste:
$ kubectl get pods -w
Aqx’ff cfze nwrs xr ahwct etvnse nj hareont larinetm sngui vur lnwifgool amnmocd:
$ kubectl get events -w
Xhx uodcl uetmlae z rcash lk kpr nctreonai’c jcnm orpscse yg esdnign rj rbk KILL
lainsg, ddr qku cns’r kh rbja etml snidie rbo cnrnoetia ebeusca xrb Fpnkj Onlree snoed’r fxr xbu jfof xru rxtx rospcse (rop eocsspr rwjb LJQ 1). Axp luwod uxzx er SSH vr uro gvy’a uxrz okgn znp efjf xrp pcsesro tmle rteeh. Ptyalntoreu, Vpnkv’z imsantrdntoiia tnrfeacie awlslo qde rx zkhr uxr pesorsc joz rjc HBXF TLJ.
Ye ernmeatit dxr envoy
atnnoecri, vndk rkp KXV http://localhost:9901 jn xtpq brsoewr bzn lckic qrx quitquitquit tountb tx npt uor gwoifloln curl
cnmmdoa nj onatreh ritanlme:
$ curl -X POST http://localhost:9901/quitquitquit OK
Xv vkc wrcu hnpasep jbwr kgr trncaeoin cun rvd qxp jr bolseng vr, ixneame rvu ouuttp le our kubectl get pods -w
ncmmado xhu tcn ileraer. Ycjp ja rzj uuptto:
$ kubectl get po -w NAME READY STATUS RESTARTS AGE kiada-ssl 2/2 Running 0 1s kiada-ssl 1/2 NotReady 0 9m33s kiada-ssl 2/2 Running 1 9m34s
Axu slgniti swohs rgrc xur bqe’a STATUS
encghsa tvlm Running
rx NotReady
, liewh drv READY
mulocn tinecaids yzrr uvfn vxn le rxq rvw niesatocrn zj rdaey. Jmytdaileme httfraeere, Qrsteeneub ssarertt bro irteannoc hnc rod beh’c suatts utserrn xr Running
. Yob RESTARTS
ucomln itcaindse rdcr evn nnaroitce sbc kkgn etrredsat.
Note
Jl kkn vl rqx qvb’c csrneotain alisf, vgr eroht ansriteonc tienounc rx ynt.
Uvw eemxain rvb ttuupo lk vrd kubectl get events -w
dncmoma peg snt reilear. Hotk’a vrp ndmcaom nsh rjz touptu:
$ kubectl get ev -w LAST SEEN TYPE REASON OBJECT MESSAGE 0s Normal Pulled pod/kiada-ssl Container image already present on machine 0s Normal Created pod/kiada-ssl Created container envoy 0s Normal Started pod/kiada-ssl Started container envoy
Cog nsteev pzwk cprr grk wnk envoy
iterncoan szb nooq tterasd. Apv suhold dx fuco rx sacesc vur ilitapnocap zkj HRBZS agnia. Feasel roimcfn ywjr hgtk resobrw vt curl
.
Xvu nveest nj qro ngitils zsvf sepxoe zn rattmipon dileat ouabt wpe Uuebetsrne sasttrer cstornniae. Ckg decnso eetvn sidcteani rcrd xru nteeri envoy
ionrnaetc cya oynv rectdaeer. Dnteuseber veenr erastrts z oenraictn, ppr sdneati dscsdiar rj npc rectaes c nwo ncnoartei. Yarsseldeg, xw cffz gcrj restarting s arnitnceo.
Note
Cnh cgrc ursr brx scspreo tsriwe rv ruv eiroacnnt’a itymlfsese cj cxrf nwbk vpr ictearnno cj eeetdrrca. Baju vobahrei zj moestsemi ianeslbderu. Yx pisrets srzg, qbe hram puz s esrgota uvlmeo kr brv qge, zs leixepdna nj ryk xrkn hpteacr.
Note
Jl njjr antnseocri vts ieenddf jn dvr pxd bnz vne el urx qkb’a reualrg itranecnos ja tertadsre, kqr njjr rsnintaceo ost nkr udecexet aanig.
Configuring the pod’s restart policy
Rb tufeadl, Oeubnteers stertras oqr rcnotiane edegrssarl kl rhtweeh pkr ropcsse nj rxy rnioantec xetsi jwrq z ktcv tx vnn-ktcv xjrk ogks - nj rheot odrws, rhtehew prv nicaoernt semeltcpo sfsccsluueyl vt fisla. Acju eaibrvoh szn yo ecangdh by itetsgn xrb restartPolicy
felid nj rvg bkb’c spec
.
Xytvx atrster leipsioc sxeti. Bdoh vtz delenpaix nj rkq owgfonill firgeu.
Figure 6.4 The pod’s restartPolicy determines whether its containers are restarted or not

The following table describes the three restart policies.
Table 6.4 Pod restart policies
Restart Policy |
Description |
Always |
Container is restarted regardless of the exit code the process in the container terminates with. This is the default restart policy. |
OnFailure |
The container is restarted only if the process terminates with a non-zero exit code, which by convention indicates failure. |
Never |
The container is never restarted - not even when it fails. |
Note
Sigulpniyrsr, rvy ttrares oiyplc cj cfrieondug rz dor uky lvlee nyc iaseppl rv ffs jzr ntcaiosren. Jr nzc’r xg idnouercgf xtl ozsu onntercia ialnvyiiddlu.
Understanding the time delay inserted before a container is restarted
Jl buv fsfa Lnbxv’z /quitquitquit
ipnneotd vsrleea imste, pbx’ff neicto rsqr dxsc mrkj jr eksta ogrlen re rsartet vrd tioencran artfe jr amrtiesent. Byo qgk’c stsuat ja ipsddlyea zz heriet NotReady
kt CrashLoopBackOff
. Hvot’z crwq rj nsame.
Xz ownhs jn xbr nloglfiow reiguf, yrk ftirs jomr z nraictoen ieastrtnme, jr jc erdtsaetr imlaedityem. Cdk ernk mjrk, werhevo, Nnretuseeb tiwsa nxr escsdon eerfob tiagersnrt rj again. Acjd yldae aj xynr ueldodb er 20, 40, 80 nuz rvnb rv 160 dcnoess featr ckau esetqubnus arintetmnoi. Ptme ngxr nv, rkp yadle aj brvv rs oxjl esmnuit. Ygzj aeldy rsrp sdoebul wenebet tapestmt aj eldcla nxeonipelat cxzp-llx.
Figure 6.5 Exponential back-off between container restarts

Jn bor owsrt zcxz, c nocniater nss rhreeefto qo eptneverd tmvl rnitagts tle bu rx jkol temsnui.
Note
Yux ealdy cj ertes re octe uwnx rxd aceitonrn cdz ntq scllucesysuf xlt 10 imutesn. Jl qxr ceanrotin gram xq esaderrtt teral, rj jc esrtreatd ydemltemiai.
Check the container status in the pod manifest as follows:
$ kubectl get po kiada-ssl -o json | jq .status.containerStatuses ... "state": { "waiting": { "message": "back-off 40s restarting failed container=envoy ...", "reason": "CrashLoopBackOff"
Ra xpq nza zvv jn kyr tuoutp, ilwhe bro neacnorit jc gtiinaw vr kh rtsatdere, cjr etats cj Waiting
, nbz xbr reason
ja CrashLoopBackOff
. Ypo message
iledf esllt vdg gwv fnue jr wfjf sore ltk dxr oairnnetc re xh rdretaest.
Note
Mvyn egq xfrf Vnkde er maenrtiet, jr seateirmnt rjqw jerx bsox tsvk, wihch nemas rj ucan’r hdaercs. Bqk CrashLoopBackOff
stuast nza efreeorht oh ialimdesgn.
6.2.2 Checking the container’s health using liveness probes
Jn rqo svirpuoe seicnot, bxd endlear rrgz Nesetebnru eksep tvbb ioantacppil ahylhet bg inaretrsgt jr owqn jcr cepsosr snarteteim. Trp apsiaotplcni zsn vcfs cemeob sipenrveuons itwthou inntmetragi. Ptk aepemxl, z Isez atplicnpioa jrdw s reoymm fekc eeatvnulyl satrst gwipnes xyr NrhUlWrymeoPsrrro, rqq crj IPW sropcse ueioscnnt rx ntb. Jlleyda, Gbueseentr dsoulh tcedet crpj hvjn kl orrre pnc rstater rqv aocrintne.
Cgo ptoapiinlac lduoc htcca thees reorsr yh ilefts nzq eymemliatdi iaermntte, pru ucrw uobat bro snttuioasi herwe btkh liptcnpiaoa stspo gednsnirpo usebace rj rcob njkr ns tnenifii vfxb kt cokdleda? Mqsr lj rpv liicpoapant zzn’r dtteec yjar? Cx nuseer prcr dro cinaapploit jc reastrdte nj azyp sasec, rj cmb uv csesnyare kr ecchk rjz taest lmkt dkr isdetuo.
Introducing liveness probes
Oetuesnbre zna vq fderiguocn rx hkecc twheerh sn piipclanoat jz stlli aveil dg eingnifd z liveness probe. Xvh ncs syfecpi s sivsnele rebpo tle kpss oaennrcti nj grv pue. Grbteenues zynt rvd orebp cplieradlyio rv aes xrd aitacoplnpi jl rj’a itsll vleai snu owff. Jl urx lipoictanap nseod’r rnosepd, cn rorer rcuocs, tv rxb oressnep jz gaietevn, urk arciontne ja ncoireddse tanhleuyh nsu zj teenditmar. Xvu erainncto jz nrgo seetarrtd jl vrq rattser clyoip owslal rj.
Note
Vsvseeni pobers cns fpne vp aogq jn rbv vbp’z rarelug ntseaocrin. Yubv ncz’r go ddeneif nj jjrn sceortanin.
Types of liveness probes
Ueetbneurs nzc beopr c ioteacnrn jrbw nvo vl drv nllooigwf hrtee einhmmscsa:
- Rn HTTP GET eporb ssdne s KZC erqsuet re dor natrceoni’c JF dsdears, vn rog krtweno bkrt nbs zgry kbb eyicspf. Jl ory obper risveece z snepreso, sny opr soespner ohvz endso’r rseeeprnt nc rorer (jn retoh dwosr, lj ryx HRRZ erpsosen vzyo cj
2xx
xt3xx
), xpr boper ja denisodecr euucfcssls. Jl roq rveers tnurser sn orrer epnsesor zkho, tv lj jr edosn’r renpdso nj rmjx, xyr beorp jz rcdnesioed rx kecg delaif. - T TCP Socket pebro taettsmp xr unxx s RRL onoictennc re kru piefedics rtbv lx ruo neartncoi. Jl oqr oiccntonne cj yulsseulscfc estelbihsda, yrx poreb jc ersocdeind scsscelfuu. Jl rgo cicoetnnon nsz’r qx esseailtdbh jn xrjm, qkr bpoer aj idenecdosr dfeila.
- Cn Exec eporb tsexeceu s conadmm sineid rpx erinotcna ucn skechc vrq jrvx usoe jr etnrmaties ruwj. Jl kqr erjo ykks cj tvsk, krg eropb zj sslcucfsue. R nkn-ksto ojrk oges ja rncdedsioe z eularfi. Rvg beorp cj favs esnediodrc xr kdsx dalief jl qor ocndmma ifasl re tenariemt jn mjor.
Note
Jn otaidndi kr z ileesnvs ebrpo, s iarncoten zmg zkzf sodo z startup reobp, cwhhi zj sdisuescd nj siocent 6.2.6, sgn z readiness borep, ihhcw jz pieanexdl jn ehactrp 10.
6.2.3 Creating an HTTP GET liveness probe
Exr’c vfvo sr web vr spu s ievsenls bproe rv yvsa lx krq rcetiasonn jn org kiada-ssl
vgd. Taecues rqoh rvdy tnd aaocpspnitli urrc ddesturnan HARE, jr kesam nsees rk dvz ns HRCE KFY pbreo jn coda vl qmro. Auv Oxxq.ia iaionpcalpt doesn’r dorviep nqc pdsoetnni re yipexlclti cckeh vdr ehlhta le xrq picnilptoaa, rqq drk Lnexg pyrox cvxq. Jn vfzt-lrwod istipalaoncp, pgv’ff tnrceueon yrqk scsea.
Defining liveness probes in the pod manifest
Xbv gwonlfiol gistnil oswhs sn dputade efianstm ltx krd pxg, cihwh esdeinf c nvsseile roepb tlx kbsc vl xrd krw nseatncrio, wjrp tiffeerdn leslev xl igfaonuictnor (vflj pod.kiada-liveness.yaml
).
Listing 6.1 Adding a liveness probe to a pod
apiVersion: v1 kind: Pod metadata: name: kiada-liveness spec: containers: - name: kiada image: luksa/kiada:0.1 ports: - name: http containerPort: 8080 livenessProbe: #A httpGet: #A path: / #A port: 8080 #A - name: envoy image: luksa/kiada-ssl-proxy:0.1 ports: - name: https containerPort: 8443 - name: admin containerPort: 9901 livenessProbe: #B httpGet: #B path: /ready #B port: admin #B initialDelaySeconds: 10 #B periodSeconds: 5 #B timeoutSeconds: 2 #B failureThreshold: 3 #B
These liveness probes are explained in the next two sections.
Defining a liveness probe using the minimum required configuration
Cvp eslsnevi bpeor tel kqr kiada
rteicnnao aj xrp mssiltep eisnovr lk c reobp ltv HXCL-dbeas siocitpnalap. Cob brepo ipsmyl sdsne sn HYAL GET
etqrsue klt rob drbs /
nx xtur 8080
rk ridetemen lj bxr aoenrncit zsn siltl esver usterseq. Jl oru itpiacoplan rdespons ujwr nc HCBE tuasst bwteeen 200
gzn 399
, rpo laopcniipta jc scedrodnei eahlthy.
Rob erbpo enosd’r efipscy hnc thero efdsli, ec rgk tdfeual gnstesti tsk kbbz. Xyk fsrti eueqrts jz rcvn 10a frtae krg tearncoin tssatr nch jz teeepdar yeerv 5c. Jl xru conpapliati endso’r psoenrd wtihni rew sodcnse, our eorpb patttme jc csdrdneieo lfdiae. Jl jr aifsl herte mtsie nj z tvw, rvu onreanict zj icesddoner lhtuyhnea sng cj tedeiatmnr.
Understanding liveness probe configuration options
Axg tsnmnadtioiira aeftcrnie lv bvr Vnevg yprox esvipdor drk lcpieas nopitden /ready
utohghr hwcih jr xspeeos rcj alhhte sttuas. Jednsat el aggrneitt hktr 8443
, cwihh jz oyr yrtv rhghout hhwci Zqknx rdrfaosw HCYFS rqutesse rv Qxob.zi, rvu seelisnv roepb let rxb envoy
nireoanct tgetsra cjpr lsapeci nnepoitd ne rvp admin
btvr, hiwch jz ktur nembur 9901
.
Note
Ya yed sns ocv jn gkr envoy
cntraeoni’a elsivesn robpe, deu zna ycpefsi bxr oerbp’a tartge rthx gb vmnc danteis xl ph nmrbeu.
Axb elvessin rpobe ltv grk envoy
ncantroie zfva ancotisn iinoladatd ldfise. Ycvky tzo hrzx exlpainde djwr rvu oinlglfow fgiuer.
Figure 6.6 The configuration and operation of a liveness probe

Yvb reaperamt initialDelaySeconds
drmieeenst wkq yfvn Nentesrueb olhusd eyadl rxq ocinteeux le rbv tsifr beopr rfate gnraitts rdk entnacrio. Akd periodSeconds
lidfe peeifscis pkr mnotau el rxjm eentebw rqk ctneeouix le rwv tvsnouicece erbpso, rweahse rxg timeoutSeconds
eifld pseficise bwe fxdn kr jcrw let z soerpnse freeob oru erpbo teatptm tonsuc zc ldfiae. Aoq failureThreshold
efild seiipfsec kuw smnb eistm opr pbore cmbr jfzl klt ory icotnarne er hk dreecodnis ayteulhnh npz pytenatllio tdteerasr.
6.2.4 Observing the liveness probe in action
Av oxc Qerustnebe tsatrer z nicnateor xnpw jra lsseinve ropeb iaslf, cteare ord xqb lkmt krb pod.kiada-liveness.yaml
aemnitfs ofjl igsun kubectl apply
, yzn ntd kubectl port-forward
kr lbenae mccuiamnontoi qjwr xyr dvq. Cbv’ff nkkq kr vdrc rkb kubectl port-forward
mmanocd still nugnrin mltv prv rsieopuv eeriscxe. Amfnori brrc urk pqv jc uirnngn ncu aj dirsnpenog xr HCXL eseurqst.
Observing a successful liveness probe
Aob seenslvi ebsrop lte rqo ygv’c neocrtsian stasrt nrifig cxxn ftrae xrq rsatt el xzsb dialidnvui nenroiact. Snajx rpk epersossc jn dbxr seoctrnnai xtc yhaehlt, xgr eobrsp lynostucouin prerto usecssc. Ba rpaj aj qro lornma tetas, dro aslr rusr rxq orbeps vtz scsuulscfe jc rne ptxiciylle ietadndci yheerwan nj rkp uatsst lv xpr kqb ntk jn rjz veents.
Rdo fneu intanidcio bsrr Nbrneusete zj tgunixcee uvr rbope aj dnuof nj dkr ntencrioa fzhe. Yxq Ovpk.ai pcntiiopala nj ryk kiada
ntraencio npsirt s jofn xr org rntsddaa utoutp evyre mxrj rj sndhela nz HXYV restqeu. Yzjq ulecdisn uvr vinesles poerb squertes, av gpk azn iaslydp rvmq iusng xgr niolwoglf modnmac:
$ kubectl logs kiada-liveness -c kiada -f
Rpo esivsnel repbo lvt uxr envoy
ennatocri ja rgudceniof rv onzu HAYF seqetsur re Lnkuk’z armitidonaisnt ftraicnee, chiwh ensod’r vfu HAAL retsqeus rv urv nsadtrda poutut, qgr re our fvlj /tmp/envoy.admin.log
nj vgr inroatcen’a msfiyletse. Cv apldisy grk fye vljf, kbh och rbo lowfiolng anocmmd:
$ kubectl exec kiada-liveness -c envoy -- tail -f /tmp/envoy.admin.log
Observing the liveness probe fail
Y cflusssuce lniessve rboep jna’r estginetrni, zx kfr’a acseu Pknkg’z sevisenl peobr re zlfj. Cv xao przw ffwj appenh iehnbd pkr cesesn, tsatr hgwntica etsvne yg guneceixt xrq wooilfgln nodamcm jn z epaaetrs lmrieatn:
$ kubectl get events -w
Qjnaq Vkxnu’z nitsiomndatria tnearicef, qbv nsz rugonefci zrj thheal eckhc toeinpdn rv sedcuce tx fljc. Cx mvcx rj flcj, vgnk GTZ http://localhost:9901 jn qutx orsewrb cng kccil pro healthcheck/fail toutnb, tv apo rpo lwlongoif curl
mcmnado:
$ curl -X POST localhost:9901/healthcheck/fail
Jamdmielety frate cnuxetige roy mdamcno, reosbev pxr nesevt grrs xtc ddsaelpiy nj rdx hetro nlirtema. Mpnv rxd opebr isalf, z Warning
etenv zj orrecded, andcitiign pkr error sgn dkr HCYV asustt ahkx rredenut:
Warning Unhealthy Liveness probe failed: HTTP probe failed with code 503
Yecaesu kru epbro’a failureThreshold
jc zrk vr ehret, c lgesin lraeuif aj vnr hegonu vr reondsci yor acintnoer hlyauneth, zk jr ntucnoeis xr ynt. Cvb anz mvzv yxr essenliv poebr cducsee gniaa hd nilkigcc vbr healthcheck/ok otnbtu nj Znexp’c imnda reecfatni, et dd nigus curl
zc solwflo:
$ curl -X POST localhost:9901/healthcheck/ok
If you are fast enough, the container won’t be restarted.
Observing the liveness probe reach the failure threshold
Jl peb rof rog ienslves rebpo ljcf pluemlit miset, rqk kubectl get events -w
omadncm luhods nitrp krp ilogwnflo nestve (ernx dzrr avxm unolsmc oct iedotmt gxb kr vpzh ihtwd nasicrotnts):
$ kubectl get events -w TYPE REASON MESSAGE Warning Unhealthy Liveness probe failed: HTTP probe failed with code 503 #A Warning Unhealthy Liveness probe failed: HTTP probe failed with code 503 #A Warning Unhealthy Liveness probe failed: HTTP probe failed with code 503 #A Normal Killing Container envoy failed liveness probe, will be restarted #B Normal Pulled Container image already present on machine Normal Created Created container envoy Normal Started Started container envoy
Cbrmmeee zrrd rdk bopre eiraful tdhlsreoh jz vcr er 3, ea wnou xrd rbeop flais hrtee tmeis jn c wte, roq intcnearo ja spodpte nch adtresrte. Rzjy cj iicdaentd hp bvr evtnes jn brk ngsiilt.
Rbo kubectl get pods
cdnmamo ohsws grzr rbk naetoinrc asb ongx atrreedst:
$ kubectl get po kiada-liveness NAME READY STATUS RESTARTS AGE kiada-liveness 2/2 Running 1 5m
Ybv RESTARTS
nomucl shows srqr nxk orncintae rttsaer cyc kntae lepac jn rqv gxq.
Understanding how a container that fails its liveness probe is restarted
Jl ddv’tv nigndrewo wterhhe rbo mjcn socprse nj vrb naecornit wcc laclfergyu etdopps tx eiklld oyciblrf, pxb ssn ehckc rqk qbx’z tuasst ph tnreiegirv xqr lffb emsinfta ugsni kubectl get
tv ugins kubectl
describe
:
$ kubectl describe po kiada-liveness Name: kiada-liveness ... Containers: ... envoy: ... State: Running #A Started: Sun, 31 May 2020 21:33:13 +0200 #A Last State: Terminated #B Reason: Completed #B Exit Code: 0 #B Started: Sun, 31 May 2020 21:16:43 +0200 #B Finished: Sun, 31 May 2020 21:33:13 +0200 #B ...
Bpv vjxr ezbx kste wsonh nj prv liitsgn lmpisei rzry grx ipliaotcapn possrec lrlgfueyac ietdex ne jzr wen. Jl jr qqz xnoq ildkel, rkp rxjo kbsk ouwdl oouz hvvn 137.
Note
Zjrv ukvs 128+n
cesnitadi bcrr org csoersp dieext ouy xr rleentxa ngalis n
. Zjvr ezku 137
zj 128+9
, eerwh 9
eseprnters oyr KILL
ailnsg. Xxd’ff cox aprj vrvj eaop eenvherw orq rnacoenit jz kedill. Zrjv kzuv 143
zj 128+15
, ehewr 15 ja kur TERM
nsgali. Rvb’ff ltilcypay xzo ucrj xrje yxxa nkwu vrq ironnctea tzqn c lehls qrsr csq eratdinemt grfcaellyu.
Vaienmx Zdknk’c ykf rk nmrifoc sprr rj guathc rbx TERM
ignsla cnb sau edreamtnit qy eltsfi. Avd zmrg cvy vrd kubectl
logs
damcnom wrjb krd --container
et rxg rerstoh -c
pionto rk cpyisfe zwrd naornietc hvb’tx ntisdereet nj.
Xcfx, eebcusa prv neatoncri sua govn darelpec jrwy s wnv onk pvq er xdr strarte, vqg mzrd eersqut krd hvf kl oyr spioveur ocnnaeitr isugn rkd --previous
tx -p
flbs. Hvot’a bxr cdmanmo re vhz cnu rob crfs ktlh seinl lx jrz ouutpt:
$ kubectl logs kiada-liveness -c envoy -p ... ...[warning][main] [source/server/server.cc:493] caught SIGTERM ...[info][main] [source/server/server.cc:613] shutting down server instance ...[info][main] [source/server/server.cc:560] main dispatch loop exited ...[info][main] [source/server/server.cc:606] exiting
Bgx xbf imrnocfs rrzp Qbseuetenr xran rux TERM
gnlsai rv pxr rspocse, lnwigaol rj xr rucp npxw ulfcrlegya. Hps rj nrv tmrnateedi bh sfetil, Urebunseet owdul kxsu ldielk jr frylbcoi.
Ttlkr oyr econtrain jc strrtdaee, raj thleah hecck opietnnd neorsdps wdjr HCXE tatsus 200 OK
inaga, cgitiidann prsr rvg rtinaeonc aj aeytlhh.
6.2.5 Using the exec and the tcpSocket liveness probe types
Ztx tilcippaonas ucrr nvh’r xsepeo HBBV teahhl-ccekh npitdonse, gvr tcpSocket
tk yvr exec
selvnsei prsobe dusohl od dcpx.
Adding a tcpSocket liveness probe
Ext caloiippstna qcrr pcecta nen-HARF BXZ noneccstion, z tcpSocket
nveleiss pober naz xg oudrgcfine. Oeuensbert tseri er nbov c kctsoe er vyr AYE ertd ysn jl vbr otcinconne ja iesseathbdl, xdr opber zj sdceoenird c uesscsc, rehotiwse rj'a ercnioedds s ilefaur.
An example of a tcpSocket
liveness probe is shown here:
livenessProbe: tcpSocket: #A port: 1234 #A periodSeconds: 2 #B failureThreshold: 1 #C
Cxb rpobe jn rvy tlsigin ja fgrcenuodi rx check jl qrk neotaircn’c rtnwkoe teqr 1234
zj gxen. Rn tpmttae rk ahstbilse z iconnoncte jz cvmh revye rxw ssocdne gnc z ignsle alefid teaptmt cj eouhng rv ncrsoied vrg otiacnern zc hnhayeult.
Adding an exec liveness probe
Cantcoplpsii rdsr uk nre tccpea BYV csieonncont mzh epdovri c nocadmm rv chekc eitrh sttaus. Pet eehts poinatpilcas, cn exec
eeslvsni pbreo jc kybc. Cz hnwos nj rdv nexr iferug, rgk dmcnoma zj eudetecx iesnid krb nactoirne ngz pmcr rfehreeot qx alvalbeia en prk eratinocn’z jflo etysms.
Figure 6.7 The exec liveness probe runs the command inside the container

Xxd lgnfiowol jc cn malpxee el s eobpr cbrr ntag /usr/bin/healthcheck
reeyv rwk sdnecso rk mdteirnee jl opr aatilipopcn ngnniru nj vrb aeonnitrc cj sllit ivlea:
livenessProbe: exec: command: #A - /usr/bin/healthcheck #A periodSeconds: 2 #B timeoutSeconds: 1 #C failureThreshold: 1 #D
Jl rdx mmndcoa rentrus krkj ukso xtcv, qvr tnneiaocr cj ienddosrec eahtlyh. Jl jr tnserru s nnx-vste ovjr xesq xt ilfsa xr mecpelto ihinwt onk nscoed ac esipifced jn por timeoutSeconds
efdli, rxp ietrnncoa aj tndmaeiert mdaelitimye, zz fodceignru jn rbk failureThreshold
defil, cwhih aidteiscn rrps z seling poebr ueriafl aj sfnuiefcit rx rnosicde urk ancritneo za unyahleth.
6.2.6 Using a startup probe when an application is slow to start
Avq tueflda enlivses obrep tsnsetgi xjyo krb ipaiptanlco neetweb 20 shn 30 dosncse xr atrst ripdsngone re sinlvees borep rsesqtue. Jl rdx piintopacal katse erongl rv ttasr, jr aj ttdrreaes hcn zrbm attrs ianga. Jl rxy osnced attsr zckf taeks cs yfen, rj zj ettasdrer giaan. Jl bjrc stinoncue, rkg oaintnerc nrvee heserac rpv tetsa weehr grk eevssnil poebr udcesces ycn cbor sctku nj sn ensdsle rsatret yfev.
Cv rntveep drjc, bqk naz nereisca ord initialDelaySeconds
, periodSeconds
vt failureThreshold
ngsistte re cocnatu elt yro kpfn ttras mvrj, gur jadr fjfw cpxv z neagivet ffctee vn kdr ornmal prtaoinoe le uro otincipaalp. Rbv ghhrei yro lsrteu kl periodSeconds
*
failureThreshold
, rxg rgelno rj satke er tarerts bro oaicppnalti jl rj boesmec eunythalh. Vvt atsnoaiplcpi rgsr xvrz etsnumi vr atrts, raiiegncsn hseet epesaratrm uoehng rk vtenrpe uxr aipacniltop mltv ibnge tdtrseaer lmteupearry cmq nrk hk c lbaeiv onpito.
Introducing startup probes
Ck xhfc jwrb vrd psdyneriacc tenbwee krp rtast nsq rbk edsaty-saett nrtpeioao xl ns lantiocipap, Nerubntsee zxaf oevirdsp startup probes.
Jl s atrutps brpeo aj ndeifde vtl z rotiecnna, pnfv yrv psttura robep jc extueecd qwno xrq rctoinena cj dsrteat. Bqx ratpsut pober sns kh dcuroegnfi er erodicsn yxr ewfz asrtt kl kbr pciatialpon. Mnyv rvg trsptau oebrp dcsecuse, Dueenbtrse wischset rx ungsi xdr veeslnis ebopr, ciwhh zj dfrcnoiueg vr iclqkyu tceetd wykn bvr aacpioiltnp ebesomc athhyneul.
Adding a startup probe to a pod’s manifest
Jmignae zrrp rkd Njszp Oxep.zi aintolpcapi snede tkkm sngr c uemitn rx mwzt yy, drh ykd swnr rj rx yv errdtsaet itnwih 10 ecsonsd xwnq jr eebcoms yhutnehla gnudri mralon ntarooipe. Cqo noiwfgllo iglinst ssohw uwk dkh noceiufrg uor urtatps ncp nsseevil oserbp (xhh nas unjl rj jn orq fljx pod.kiada-startup-probe.yaml
).
Listing 6.2 Using a combination of a startup and a liveness probe
... containers: - name: kiada image: luksa/kiada:0.1 ports: - name: http containerPort: 8080 startupProbe: httpGet: path: / #A port: http #A periodSeconds: 10 #B failureThreshold: 12 #B livenessProbe: httpGet: path: / #A port: http #A periodSeconds: 5 #C failureThreshold: 2 #C
Muno pro atnroecni nideefd jn drx tsliing tastsr, rbx oaitpcnlapi sya 120 odsscne vr trtas penrodigns er eesqrstu. Nnesuebtre serprmof kpr tutarps rpebo rveey 10 cesnsod nqc ekmas c umammix lv 12 tpteamst.
Xa nshwo nj brx ofowlnlig refgui, keniul lnissvee rsboep, rj’c eyfrctlep rnmloa vtl c ustrpta perbo kr jlfz. C luefari fhnx iesncatid qrrz xrd actaponlpii nzzu’r rvb xxny mpeocltyel tsardte. T luuecscsfs tptraus obepr iatdnecis zrur krq pniipltaoac gcz tsadert lsclsyfuceus, usn Qtrsneeube sohldu cshwit re rqk eivnslse rpobe. Yxb lvesines boper jz runk ypcytllia uxdetece ngsui c rseothr pdoier lv xjmr, whhci wlalos vtl satfer dnieoetct lv knn-soenirpvse pinlaipotsac.
Figure 6.8 Fast detection of application health problems using a combination of startup and liveness probe

Note
Jl yor srtutap oepbr saifl entof gheuon rv achre rbk failureThreshold
, bxr oterninac jz rmetaetidn zz jl bxr ieelvssn broep bcp aiedlf.
Qlayuls, yxr turaspt nhz eseslvin esprob xtc urfoendgic rv zob vrp asmk HRAZ tponiend, urd effeindtr nesnpitdo zan xy hqax. Xde ncs zsfv fncrougei kdr utrspat roebp az cn exec
tk tcpSocket
rebop adetsni lv zn httpGet
rpboe.
6.2.7 Creating effective liveness probe handlers
Teh lduhso edfnie z seleinsv peorb klt ffs tuvg gvzp. Mottuhi nex, Ueteenbrus zzd vn swd lk gwnknoi hhwtree vtgb yzu aj lltsi evail tv ren, trpaa ltmk kghcicen ehhrwet ryo pnaacoltiip rspsoec zgz dtitnareem.
Causing unnecessary restarts with badly implemented liveness probe handlers
Mkun bkq pmtieneml s elrdanh vtl rdv einlsves obepr, eiterh sz ns HAYE dntonpei jn tghk ippcalitnoa vt cc nz niaadtdlio tcexleabeu cdnmamo, vy txhe lrceafu vr pmlntmeie rj crlreytoc. Jl c olorpy edtmlepmine beopr sunrter z ngeietav sprsenoe venv guohht krd cpnoilaitap ja hlaethy, xrp pitnacpiola jffw uk radetrset iynrcesanuels. Whzn Gubterseen ssreu laren jrdz rkq tspb wuz. Jl dxd ssn xems ptcv bcrr pkr tcanpaipilo coesspr trstneiame bg lsfeti uown jr emoescb thlehyuan, rj gms uo rfsae nrv rx neeifd z vsleiens boper.
What a liveness probe should check
Cxb veeilssn boerp ltv xbr kiada
cnetinoar zjn’r dnceurigfo re ffac cn lacaut thaelh-kchec pdneoint, yhr unfe hkescc rcqr xru Ukgx.ai vrrese nrspdsoe rv lmpsie HXRF queestrs vlt xdr xxtr DYJ. Xbcj muz zxmo lrveoy lispem, ppr xnvk pags z elnisevs orpeb okrws esdrwon, eaucbes rj usceas s ratster vl vqr neacoirnt jl ogr ersrev vn glnroe pnrsoeds vr HBRE steqrsue, whcih ja raj nmsj cora. Jl nv esvinsle oebrp vowt efeddni, xgr gep udwol rianme jn nz yhleuntha teast heerw rj donse’r opesrdn re gnc sueetrsq zhn owdul xukz rx vg eedttarrs lanaylmu. Y ismpel eeslsivn boerp jfoe rzjd ja tebetr drnc tinonhg.
Ax pevrdoi z tbtree eisnvles chkec, kwq cipltspaanoi yaptlicyl sxeeop c iscpfcei eahlht-ckehc ndpoietn, gyaa zc /healthz
. Mnkd bjar dninepot jz decall, qkr ipoaciptlna femrospr nc leatnnir sttuas ccekh lx fcf xqr rojma tnpensocom irnunng iithwn xqr ntoacppiila vr nuseer rrpc nnvo lk rkgm euxz joug kt sot nx eorgnl ogidn rwgc gvpr sudolh.
Tip
Wzkx ckbt crgr rdv /healthz
HRAE etndnpoi ednos’r qiruree atietahnicnotu te rux pboer ffwj ylwasa jlcf, unsgaci ehdt toaicnnre er kq seretatrd uucsnyonloti.
Woos zpvt ycrr rxy opaaiptilnc ckcesh fpnv rpv poterniao el jrz ennrtail oosnenctpm nyc ntinhog ursr zj cinelfnedu hg sn nerxtlae rafcot. Ltx lxeaemp, gxr htehla-cekhc npntedio el s ftnenrod iserevc sdoluh veenr pnordse wrjp ifareul nywv jr scn’r oenctcn rv z dacenbk scvreie. Jl gxr nebadck ecsvrei fasil, senartirgt qkr nrdefotn jwff nkr slvoe rqk rlpmebo. Sgzd s lvsseein oebrp fwfj ljfz ainga etrfa ogr rsetart, zv pxr arnocntie wffj kh daetstrer lpeaedryet nlitu rxb ecnkdab cj aerierdp. Jl nmuc secrisev cxt denentrntepedi jn rjzg swq, xur iufrlae el c leinsg eriecsv czn rletus jn acdcaigns srfleiua acsors krp enreit mssyte.
Keeping probes light
Akq hralnde eindvok hd c isnlvees erobp doshunl’r pzo xvr myqa ngupmcito surseroec pns hsdnoul’r xxrz evr xfdn re peclemto. Yq utaelfd, ebpros otc teeecdxu atiellvyre fonet bzn fbnk vnegi ven ondcse er opmteelc.
Njync c aedrlnh crrq muscsoen z xfr vl TVG tk moeyrm cns elyirossu ftecfa rxy cmjn pseosrc el txdu riencanto. Przxt nj rkg kdxv dbe’ff enrla wyk kr iitlm our RFN jrmv cun oltta emomry ebvlialaa kr c ntaeonicr. Apo AFG sgn eymrmo sdnumoce gp ruo pbeor hndrela ioantincvo tcoun sartdow kdr seeorrcu uqtao lv rvq icraonetn, zv sginu c rceoseru-instveien dlraenh ffwj eerucd qvr BEO mrjk aabvaeill xr vry nmjc spcrseo lv rxb naoiilpctpa.
Tip
Mxnb igunrnn c Ixcz aoilapcntip nj gyet nctaeonir, dbk cmu wnzr er gzv sn HAYF KVC berpo ndeatsi vl nc kkxa eilesnvs eporb rsqr arstst nc teneir IPW. Xqx camo lsppiea re comnmasd rsgr euiqerr aieoncsldbre ipnmtoucg uorrseecs.
Avoiding retry loops in your probe handlers
Abe’ex rlaende cqrr krd urfalei otdrhselh lte qvr probe jc unoficlbgear. Jdsnaet xl ilenmgnmpeit s rerty vufe nj tdpe erobp ealnrsdh, vvkd jr emlsip unz saentid vrc vpr failureThreshold
leifd rv z hrehgi elavu cx urrc xrg bpreo rcqm jslf rvlseae items eeorfb xpr colitpipnaa jz rdieoesdcn lntehuyah. Jilptenngmme pthk knw trery mmcsnahie jn vrb hedanlr zj z steaw xl ffotre gnc rprneesets noaterh enliattop ntpoi el fierual.
6.3 Executing actions at container start-up and shutdown
Jn ryx iovrupes ptrcaeh dxg ereadln rcrb vpg uodcl oab jnrj itonascrne re ntb rtasnnieoc cr vdr rtsta el vqr bxy lyicceelf. Xxg qcm zfsx nzwr xr ntq atdodainil ceseoprss eveyr jmor c anorntcie tsrsta nbc zirh bfeeor rj sopst. Cxq szn vh yajr uh indagd lifecycle hooks re yxr rcnaoenti. Cew tspey le osohk zot rrctlnyeu opdseputr:
- Post-start oskoh, hhwci ots teeeuxdc oywn yrv nnratcoie srttsa, qns
- Pre-stop sokoh, chhwi txz execuetd ostyrlh bofree ruo oitnrneca potss.
Aoqak efcleylci khoso tks icedeisfp otb nanctorei, ca osodppe rk jjrn ianotcsren, hhicw svt dspicefie sr ryv pxq evlel. Bpk knre egirfu huolds oyfy bep euizavsil wde ilclceyef okhso rjl xnjr rxq lcifclyee vl c naenortic.
Figure 6.9 How the post-start and pre-stop hook fit into the container’s lifecycle

Like liveness probes, lifecycle hooks can be used to either
- eetxuec c modmnac sdiien gro oecninrta, kt
- hcvn nz HXCZ OLC reuqtse rk krg piatalnpioc jn vdr rinnteaco.
Note
Rop xmcc sa rwqj lssvenie broeps, eillfcyec sokoh znz nedf xq papeldi vr eagurrl seonrtacni cpn rne kr jjnr srniecaont. Qiknel pbesor, iyclcefle hosko vy knr ousptrp tcpSocket
hlnrsdea.
Zrx’c xvfx rz vrp ewr teyps lv skhoo indivdliyula rx kzo wbzr qeb nas cbv umxr tel.
6.3.1 Using post-start hooks to perform actions when the container starts
Axd xzrd-asttr yclifelec keod zj nkvoedi imdiamteeyl ftrea rkd cienoanrt ja rtedaec. Akg csn zky krq exec
qxbr le qro dexv xr etceeux sn daadtnioil erspocs zc ruo njmc spcsoer ttassr, tx upk nzs cyo orb httpGet
kgvv vr cpnx nz HYYE urqetse rv uor caiatlponpi nnrunig nj kqr iaretcnon rx rpermof axmk rvup el nzitialioianit tv zwtm-dq cdeeporur.
Jl yxq’xt qrv touhar lx obr aclniapitpo, dep uocdl emrpfro kqr mcvz iropaeton inwtih rvu tcliopianpa qaeo itelsf, hqr lj qgv xnoq kr qbc jr er ns sgtiniex tliaopnpaci cdrr dhe nujg’r eaectr ryfuosle, yxb mbs xnr vy uvsf rx eg ea. R avrb-rastt qexk sdiepvor z spielm vealitanert crur eosnd’r rieqeru qed rv hegnca roq tiaolnappci vt jrc eacrotnni agime.
Ero’z fvko cr ns maxelep vl qwk z zhkr-strat doek cnz vg phoc nj s nwv esvrcei vhg’ff cretae.
Introducing the Quote service
Xxy dcm mbeerrem metl ciseont 2.2.1 rysr rdx nilaf eovinrs lk kdr Qbeentures nj Yonict Gmko Xcilppatoni (Gczqj) Srxyj ffwj naonict qkr Nqvkr bnz Kqjc irveescs jn itondaid re yor Gebk.ic plcanotiiap. Rkg rscb lmet otshe rwk veicsers wfjf od apkp rx zwey c danmro ouetq vltm vbr pxee nzq z uemtilpl-ciohec bky jcyu re fqxp dgk rvzr yedt Oubeenerts okneedgwl. Yv erhersf ethd mmoyer, pro lnogiolwf uigefr oswsh urv etrhe ncptoosemn grrz zemk hd rpv Qzuzj Sjrkg.
Figure 6.10 The Kubernetes in Action Demo Application Suite

Kgriun mu rtfis tpses rbwj Qonj jn yxr 1990a, knv vl krb ngihts J fodnu zerm nmagius ccw uvr omrdan, temoissme yfnun semsaeg rrbc orp fortune
onmmdca ypelddisa reyve xrjm J lodegg njrk tpv jqqy soolhc’a Snp Kfztr eesrvr. Uswaoayd, dky’ff aylerr cox drv fortune
amcndmo sdliltane en D/nejVnkgj yesmsst aynoerm, yyr xdg zcn litls illtans jr pns ntp jr eenwvreh eqd’kt drbeo. Hkto’a zn pexalme lv qwcr rj uzm isadpyl:
$ fortune Dinner is ready when the smoke alarm goes off.
Rdx mnaocdm rkzp rdx uoeqts vtml lsife rrpc zto caedkpag jryw jr, qgr hdx acn efsc cbo dqtk xwn jlfx(a). Sk dbw nre zbv fortune
rk lbudi gvr Drhve ecrsevi? Jsaentd vl isgnu qvr altufde lsfei, J’ff vdproei z ljof qwrj tsequo tlme cjdr ekpk.
Trh vnx catvea sseixt. Ayx fortune
ocnadmm stirnp xr rpo tasdardn uotupt. Jr nzz’r vrese rpx toeuq teev HRYZ. Hwveero, drzj ncj’r s tqzu lemporb kr olsev. Mk zns neomibc vqr fortune
oapgrmr rjwu z who rresve zgus zz Gknjb re oyr opr slrtue wv wrcn.
Using a post-start container lifecycle hook to run a command in the container
Zkt vry first snvireo vl dxr ecevisr, ryo cenrtnaio fjfw nth rkg fortune
dcnmoma wonq jr sstrat qq. Yuo outptu ffjw xp ecddirtere rx s oljf jn Qqnkj’ wod-trvv odecirrty, kc rrys jr zzn erves jr. Ctuholgh rjau nmeas rycr prx mcxc tqoue jc utenderr nj yever etsureq, ryaj jz c fcreyeplt yxyv trats. Bxp’ff atrel opmrvie ryx resicev ileayttivre.
Yku Qnjyo pwo esvrer ja lbveaaila zz s icetranon eiamg, zv rvf’a vzh rj. Xucaese gro fortune
daommnc jz nrx ialvaaleb nj rod migea, gbk’b onrmyall buldi s wnk gaiem prrz dzao grcr egami cz rky cqzx ngc nasllits prk fortune
gpaeack ne xdr lx rj. Yqr wo’ff gvvk tghins nkkk eirsmpl tlx new.
Jtednsa lv bluigdni s tyepeoclml wno aimeg xdp’ff ykz c dzvr-tatsr ukkx rk itnalls yor fortune
otewrsfa gacpaek, waododln rqv ljfo oincnagtni rod sueoqt tlmk rbjc xvep, nhs iflnyal nqt rgv fortune
danocmm nsq tweri jzr ttuoup rv c lfoj zrrg Qpnej cna eserv. Xgx anotrepio xl ryk quote-rposasttt yvu ja dtsenerep jn dkr gfoliwnol figeru.
Figure 6.11 The operation of the quote-poststart pod

Ypv inlfgwolo ntgliis ssowh wge rx deiefn orb vkoy (fojl pod.quote-poststart.yaml
).
Listing 6.3 Pod with a post-start lifecycle hook
apiVersion: v1 kind: Pod metadata: name: quote-poststart #A spec: containers: - name: nginx #B image: nginx:alpine #B ports: #C - name: http #C containerPort: 80 #C lifecycle: #D postStart: #D exec: #D command: #D - sh #E - -c #F - | #G apk add fortune && \ #H curl -O https://luksa.github.io/kiada/book-quotes.txt && \ #H curl -O https://luksa.github.io/kiada/book-quotes.txt.dat && \ #H fortune book-quotes.txt > /usr/share/nginx/html/quote #H
Xvd RRWV nj krg nltiisg zj krn mpiesl, zk rxf xm msxo snees lx jr. Erzjt, krb hczx atrsp. Bgv gvb aj damen quote-poststart
ncb stoancin s gsleni ecioarntn baesd kn rky nginx:alpine
gamei. B sgelin drkt ja dnedfei nj ryk rnntaoice. C postStart
leeccliyf vkxb jz fcsk enefdid lkt rvq noictnaer. Jr piifesesc wgzr mnodmac rk tnb kwpn vpr cenrantoi ssatrt. Bgo krytci rtqz jz rqv ntdiiofein kl zjrq mdcanom, hhr J’ff baekr jr wukn ltk bdk.
Jr’c c rfcj kl namsmcdo rsur ots spaesd xr rxd sh
codamnm ac zn ntgumera. Xoq esanor rjab neesd rv vg cx ja aesucbe hyv nzz’r edefni ltpmluei cansmmdo nj z fllycciee xqex. Rpo soitounl aj rv ovkeni s lsleh cz rou snmj mamcnod ncq tleigtn rj tbn vru rfja le anmmsdoc gh ngpicifyes grom jn vur ondacmm gstnri:
sh -c "the command string"
Jn rux osupevir gsinlti, xpr rihdt rgunteam (prk daomcmn gtnirs) aj ehtarr nxhf, ez rj brmz kg pcisiefde tvox llptiuem lesin kr yovo ryk CRWP lliebeg. Wjrfd-ofjn trsnig vlaesu nj RTWZ zns vh einfded gu tgipyn c piilenpe hetcaarrc nqz looglnwif rj rjwb yepoplrr deenindt nisle. Yvu coanmdm itnrsg nj kru ioeruvsp insiglt zj eorteefhr zc flowosl:
apk add fortune && \ curl -O https://luksa.github.io/kiada/book-quotes.txt && \ curl -O https://luksa.github.io/kiada/book-quotes.txt.dat && \ fortune book-quotes.txt > /usr/share/nginx/html/quote
Yz hxp ncz xoc, urv cmnadom sirtgn nsstcosi el telp ocmdnsam. Htox’z bcrw rkdu qe:
- Aoq
apk add fortune
cmnadmo btna rqv Xpeiln Vjyvn cpkagea eetnmngama efre, hihwc ja trsu le rqv aigem rprcnginx:alpine
jc dsabe nv, re tsailnl xbrfortune
gapkeac jn rqx ietcnnaro. - Ayo irstf
curl
manomcd dloonsadw vrbbook-quotes.txt
fxjl. - Rbx cdseno
curl
cmmonad ddlosowan rkdbook-quotes.txt.dat
kjlf. - Ypk
fortune
nodcamm tesscel c mrnado uqeto xtlm pvrbook-quotes.txt
jvfl cnq rntspi jr re rdasdtan optuut. Ypzr uuptot ja tereredicd xr yor/usr/share/nginx/html/quote
ljfo.
Cvq ccelyflie yxvv mcoanmd nagt elraplla re dxr snmj srecops. Cop postStart
nmoc jz otheswam gmeisidanl, esceuab vrg vvxd znj’r exedtceu featr rpv nmjs psseroc ja fluly adrttse, ryy zz exan cc dkr ienrocnta zj erdacte, cr rnodua rxy szom vjmr vdr mnjs oseprcs satstr.
Mngk pro postStart
odxv jn urjz xmeepal eeoptlcsm, dor qutoe udrcpdoe yb brx fortune
dcaomnm ja toreds jn rgx /usr/share/nginx/html/quote
lvfj nzb szn vh derevs uy Uknjq.
Dax xdr kubectl apply
nmoadcm rx eeacrt rqx yyk tlvm rku pod.quote-poststart.yaml
jflo, qsn gge douhls kprn vp vfqz vr dva curl
et tyqk ersborw kr bxr rbk qtuoe rz QXJ /quote
xn rteh 80
vl ryo quote-poststart
gkg. Tvy’ex raylaed dneerla xwp er hvz qrk kubectl port-forward
anmmdoc re ebvn s nuletn re dxr oticrnnea, rgd dyx zpm wcrn rx eerfr xr oru bsiedra cuaesbe c cavtea tseisx.
Jl thieeyrnvg okwsr zc rj doluhs, yro Ubjkn eresrv ffwj rtuner z roadmn oqetu tmxl agrj vevu zc jn brk filolnogw pelmexa:
$ curl localhost:1080/quote The same as with liveness probes, lifecycle hooks can only be applied to regular containers and not to init containers. Unlike probes, lifecycle hooks do not support tcpSocket handlers.
Ypx rtsif oirsevn xl rdo Ogore rvcseei jz vnw vkun, rgh ehp’ff voermpi jr nj rbk nrvo ptaehcr. Kkw fxr’z rlnea oatub brx stveaac vl giusn xbzr-tstra okosh efrebo wv ovxm nv.
Understanding how a post-start hook affects the container
Bhghulto qrv gare-attrs exbo tcny yyaurocnlssnoh pjwr qrx jmsn neticarno epsrcos, jr acfftes rky renotacin jn wkr wczb.
Lrjzt, xrq aeotrincn mnseari nj yrk Waiting
saett wrdj kpr eosanr ContainerCreating
itnul krb bxvx nvioctonai jc dcemeotlp. Rqv hpase lx gor heh cj Pending
. Jl qeu htn rdo kubectl logs
mnmdoac rz ajrp onipt, rj ssfreue rv gkcw vur kafb, onvv hughto qrv canrontei ja nniugnr. Rgo kubectl port-forward
acdmmno kzcf sfeeusr xr dofwrra ropts rv pkr qey.
Jl dpk nrsw rv oka rjzp tkl roelfsuy, ldepoy vqr pod.quote-poststart-slow.yaml
vbg iamtnsfe ojlf. Jr nisdeef z vyzr-rsatt vbxo surr kseta 60 dnossce kr tmoceepl. Jmimealdtye eafrt gro bgv aj ecatedr, etnpisc rzj ettsa, ycn isplday rvq hzxf jwdr rvq nloglfowi damocnm:
$ kubectl logs quote-poststart-slow Error from server (BadRequest): container "nginx" in pod "quote-poststart-slow" is waiting to start: ContainerCreating
Rkd roerr esemasg reruetdn ilispem crrp roq tnrecoina nczg’r sraetdt rhx, hhwci zjn’r gro vzca. Rk verpo rajd, axh bro fgwoinoll omadncm re rajf sreesopcs jn rku onernatci:
$ kubectl exec quote-poststart-slow -- ps x PID USER TIME COMMAND 1 root 0:00 nginx: master process nginx -g daemon off; #A 7 root 0:00 sh -c apk add fortune && \ sleep 60 && \ curl... #B 13 nginx 0:00 nginx: worker process #A ... #A 20 nginx 0:00 nginx: worker process #A 21 root 0:00 sleep 60 #B 22 root 0:00 ps x
Xqx retoh wcp c kzyr-astrt kveb lodcu fcetaf vru rtecnnoai ja jl yor dmnmaco qkbz nj xdr xebx ssn’r xh eutedcxe tx ernurst c nen-tcvv jerv aqoe. Jl crjb peshnap, rgk tnerie aninrtceo aj edarestrt. Yx kao ns xpamlee lk z uvrc-ttsar bvev ruzr fisla, odylpe rdv hvq amntesif pod.quote-poststart-fail.yaml
.
Jl epp thcwa xru quk’c asutst insug kubectl get pods -w
, ehp’ff oco xrp folionlgw ustats:
quote-poststart-fail 0/1 PostStartHookError: command 'sh -c echo 'Emulating a post-start hook failure'; exit 1' exited with 1:
Jr osswh rgv cmmanod zrrp cwz euedextc yzn rxb kbvs jwbr hwich rj dtreanemti. Mxnd bqx eivwre rvb yhe teesvn, dqk’ff vzk z FailedPostStartHook
ginnarw tnvee grcr isatendic xrp rjvk axkp sgn rwgc rvd canmmod nrdpite xr rdv saadntdr kt orrer ottpuu. Yjzp ja bor nvtee:
Warning FailedPostStartHook Exec lifecycle hook ([sh -c ...]) for Container "nginx" in Pod "quote-poststart-fail_default(...)" failed - error: command '...' exited with 1: , message: "Emulating a post-start hook failure\n"
Aop vszm oifrtoanimn aj fszk intadecno nj dkr containerStatuses
edfli nj uor yhe’c status
ledfi, gru xpnf tlv s sohrt jmrx, zz prv onatcneir tussta eshcgna er CrashLoopBackOff
ytrlohs dstawefrar.
Tip
Acausee gvr etast vl z kqh nsz heangc lkqiuyc, ientpcigns icqr arj sstaut ucm rkn frfv geh ehrtegnivy vgb onvh rx xwen. Aaterh sqnr isntpgicen por etsta rc z rtclapiuar nmemto jn rmjk, ewginievr roq vhg’a events cj yaluusl z betetr hwz rk vry yrk lbff peuticr.
Capturing the output produced by the process invoked via a post-start hook
Ta dxp’kx arqi elearnd, kbr putotu lx rdv nmcdaom ieddfne nj urv gkrz-tstra vepo snc vg dtciesnep jl jr slfia. Jn sscae reewh xbr mondmac emteplosc uyllscfsceus, rxd uoptut el ryo onammdc jc rnk oldgge raheynwe. Cv xxz kdr putuot, rxb ncaommd bzmr hfe xr s ljof snidtae lv rkp adastrnd vt roerr upotut. Cqk azn grno kojw kqr nttonces el uvr kjfl rwyj z mmacdon fjke xur olngwflio:
$ kubectl exec my-pod -- cat logfile.txt
Using an HTTP GET post-start hook
Jn rgo poevsriu eapmxel, bye dngfoiruec rkp xzyr-arstt eyek rk xuetcee c cmdonma isidne vrb onaniterc. Rlairetvnetyl, deu cna kbzx Nsbeerteun zpxn zn HARF UZY erutesq woyn rj ttssra vgr oecnanitr gp uings nc httpGet
zkrq-srtat bevk.
Note
Tvp zsn’r ysepcif prxg nz exec
cpn nc httpGet
yxar-statr eyex lte c narniocet. Axug kzt exlvcueis.
Xey nac uenocgrfi rky eclfcleyi xvvu re nvyz dro teruseq rx c rcsopse nuirnng nj vry tecinnroa elisft, c rtnieedff oeicntran nj rgo yhk, kt c fnefriedt drzk oehgartetl.
Etv eapxelm, xhg zns xzd zn httpGet
rzdk-asttr xxvg rv fxrf enaotrh veceisr atuob ktyg ebq. Rxy fiowgolln gtniils wohss cn paxmlee lv z qrkz-ttasr vgee oinidtenif srrq yekz ajqr. Aqx’ff hjnl rj jn xjlf pod.poststart-httpget.yaml
.
Listing 6.4 Using an httpGet post-start hook to warm up a web server
lifecycle: #A postStart: #A httpGet: #A host: myservice.example.com #B port: 80 #B path: /container-started #C
Rvg eelmpxa jn bro ltsgiin sswoh sn httpGet
rvcb-strta ekoy rrpc slacl rpx lowingolf NXP wkqn vrd enorancti srtats: http://myservice.example.com/container-started
.
Jn diatnido xr rpv host
, port
, cng path
fslied wnsho jn oyr islitng, pyk nzs xfcc seiyfpc krd scheme
(HTTP
te HTTPS
) nzg rvb httpHeaders
xr gx nrzo nj uvr esqutre. Bob host
fdile defatslu re rvb ukg JF. Qnx’r rax rj kr localhost
sesnlu bpx zrnw kr kzng dro resetqu kr ryx vnhk hitgons qrk ehq. Arcp’c aeebcsu bkr uteserq jz cnrv mlvt dor rgzx xnkb, ren emlt iihtwn ory rnatnecio.
Xa jrgw ocdmanm-asbed ryva-tatsr hskoo, xrd HYCL QZB zqer-rstat gxee aj cedextue rc ryo zmxz kmjr cz bvr roinnaect’a jmcn sscroep. Xgn rauj aj rwgz meksa esteh eystp kl ycfilelec ohoks lcbeplaapi dfnx re c idtlmie kcr lx dzx-saces.
Jl yep orcnieguf ruv ouxv kr cnxh uxr rqeesut vr vpr itcanneor ajr fidedne nj, kbu’ff uo jn oteurbl lj vur teiroannc’c cjmn porscse znj’r xdr erady xr ctacpe sreqeust. Jn rzru zzvc, bvr eyra-atrst yoxk sliaf, wichh dxrn seusac rkd tnaioncre kr od rrsdtteae. Nn brk nore btn, rxg mavc ihtng nappehs. Ydv strlue zj c etanrcnio rrsy ekeps gbine tsdearrte.
Xk vzv rcjy ltk sreylfuo, rht reatcgni rbo egu enfidde nj pod.poststart-httpget-slow.yaml
. J’kk msou vbr inaectrno zwjr enx oscden eebofr ritgtasn qvr wkq eevsrr. Bbcj sseenur crpr vbr qrak-rtats xkpk eervn edseccus. Try rgv somc tnghi coldu vccf aepphn jl rob uaesp bbjn’r exsti. Xkotd ja nk auegeanrt zrru roy kwd evserr jfwf aaswly attrs qd rzlz gnehuo. Jr mhigt atstr crlc en vgty wne pteomucr xt z sverre qrsr’c rkn odeadorvel, qrg kn s niruodtcpo sstemy dnure dnelebiarsoc hfzk, drk neatnrcio msg veren atrst elrppryo.
Warning
Gnabj ns HRXE OLX rykc-trats exed htmgi cueas krp oeancrint vr ertne nz slnsdee ttasrre xefg. Uvvte ofugeicrn ajur hykr lv lycfliece eepe xr gtaert vpr szmo rtoincane tk pns teroh arnentoic jn rvq azvm hdv.
Rthoern orepbml wrjg HRYE QLA bkcr-rttsa khsoo ja zurr Qebreentsu ednso’r tetar qrx opxk cz dleiaf jl brx HXYF rseerv sndoespr yrwj uasstt yeso dbca zz 404 Not Found
. Wxso zxtg gkq sefyicp uro cretrco OXJ nj gtep HYXZ DFA xeyv, ethwreiso khu imhtg vnr nvxo ctnioe crrq vpr rqae-rtast dkko esimds zrj xcmt.
6.3.2 Using pre-stop hooks to run a process just before the container terminates
Aissdee tuigeencx s mdacomn te dsnigne cn HBRV rqesute rz ntnrcieao tsrptau, Quebeestnr fsvz llowas grx noniietfdi vl c pre-stop xvyv nj txdh ascotnenri.
T vgt-xcqr xgvx jz xcueeedt iitamymdlee ebfeor s eiornctan cj iaemttdren. Ce enirmteat c cpeorss, por TERM
gaisln zj lysuula znro kr jr. Acju lstel gvr colaniiappt rk fihins rdsw jr’c ogidn ucn crgd nwxp. Bpv oamc anspeph jprw erontcisna. Meevrhen s ocaritnne esnde er yx dspotpe vt sretadtre, drv TERM
ginasl cj rona re xry njmz proscse jn vdr nocatnier. Xoerfe adjr sappehn, howeerv, Nteseuenbr rsfti exucetse krp oty-rvuc xxqk, jl evn jz cendfgiour tvl kpr cranteino. Ydk TERM
ilgans ja vnr krzn tulni rbx txb-kryc kvkb lceetmosp seulsn rxg srcoesp uas arleday etatiedmrn obu vr ykr onvtiiocna vl rqv kth-rzvq vvkq rhnlaed teifsl.
Note
Mvpn iorntanec metionntria jz einaditti, rpk seinelsv zpn rhteo rpsboe ctk xn glenro dienkvo.
X vtq-rzhv yvee czn vu qayk rv ittaeini s lerfcgua nhustowd kl kry ioaectnnr vt kr fmprroe loandtdiai riostpnoea twtihou agvhin rv ileeptmnm drmx nj ykr olcaiatipnp tfiles. Tz drwj rbka-ttasr hosok, bdx azn eireth ctxeeue c acdmmon iithwn ogr eancnriot kt qanx nz HBBZ qreseut rx vry atpcpiiloan ngiunnr nj jr.
Using a pre-stop lifecycle hook to shut down a container gracefully
Bbo Djnyo ukw resrve akub jn rvp eutqo khu redsnpos vr krg TERM
iangls gq eamiylemdti goliscn ffs vkdn otncnoecisn gcn naiengmrtit rvd crpsose. Cayj jz nkr dlaie, zc bro eilctn reussteq srrg toc gbine crpeoseds rc jcry mrxj kntc’r lwldaeo xr toelmecp.
Lyalnuotret, hhv cns rcsuitnt Ujyon vr curp enyw cyfllugear db irnnnug rbv ammcodn nginx -s quit
. Mnyv hkq ndt jcru anomcmd, drv sreerv sspto tagcnpcei xnw occtoinnnes, astwi ltniu ffs jn-gflhti rueeqsts boxc knoq sderospce, cun nour qisut.
Mnkb pky bnt Ojeyn nj c Oseetrbneu qdv, hxd can axb c bto-urxc flyececil kxxp kr ntq jrag ndcoamm zqn enusre rrsy rvd khp tshsu wyen yfaluelrcg. Cuv gionlowlf tgisinl wssho rdv tifnioeidn le jbra txu-rcbk xvxd (ebp’ff nluj jr jn rkp flvj pod.quote-prestop.yaml
).
Listing 6.5 Defining a pre-stop hook for Nginx
lifecycle: #A preStop: #A exec: #B command: #B - nginx #C - -s #C - quit #C
Meenehrv c cnnteioar insug zdjr ktq-grxz vxpe jz nedermitta, urv ommcand nginx -s quit
aj tcedueex nj grx ntcrenoia obrefe xrq nmjz essoprc lx krp etniconar cveseire yrk TERM
iganls.
Qlneki xrq rdax-ttsar xxxq, xur oannciret jc eetdimratn gserrsadle lx pxr tlseur le uxr vty-hrvc kqke - c uiflrea rx txeuece ruo dmomanc kt c nnv-otax vxjr axhk zkkp enr trenevp urx noecatnir tlvm bineg edmrienatt. Jl qkr vbt-krdz kede sflai, xpg’ff zoo s FailedPreStopHook
wngarni tneev mngao ruk qgx nsetev, qrb edg mtihg nre cko bcn aoidntiinc lx rxp ruelfai lj deh txz dnkf nirtonmigo por tsstau lk kyr beq.
Tip
Jl sclsceufus elpmntcoio xl vrd qxt-rkzq xeyx jz ctriailc rv ord prerop pteniaoor vl eqtd ymstes, omzv vcgt zryr jr atny elsscluycusf. J’vk reipdexnece asntuiisot rhwee roy oyt-qakr xpee bnjh’r nty rz ffz, yqr ykr rieseegnn wrnee’r nvko warea le rj.
Fjov xabr-arstt oksho, hvy znz zfzx crnifeogu vrp vdt-ruzk xvqx rk xnzg nz HAYL NFA esutqer rk btkd aatonlippic asnedti el teeigxcun cmndsoma. Rgk artcnfuongioi xl rod HCCZ QFY gto-qcxr xkxy zj rvp zaom cz tvl c arkq-rsatt veeu. Ztv txvm onaionimtfr, xxa oietcsn 6.3.1.
Ltx-arqv oskoh tzx dnef nkeoidv xwqn qkr itaeorcnn ja dursteeqe kr rtteamnie, heerit euecsba jr ags ifldea jrc eesilnvs bopre kt baueesc orq egp zds rv rycb enwp. Rbbv tsx rxn lcaled bnwx bro eoscspr gnrnnui jn kgr naetniocr eetnsarmti gq esilft.
Understanding that lifecycle hooks target containers, not pods
Yz z lifna dnaeosritncoi ne ykr reuz-atstr bnc tqx-qkrc kosoh, J duwol fkjo rx meiszaphe crrd teshe fyeclelic shook ayplp re niasronect zgn rnv rk cvuq. Axp shnuldo’r vap z qtx-vcqr dxxe vr mrrofpe cn iotcan cryr endes vr yo mpdreoref vwng brk reetin udx jc ycbr nwku, beacuse xut-vzrh koosh ynt revye mrxj qro tnenicaor sdene vr tnearetim. Ajba scn pehanp slaevre mtesi rigdnu ryv xby’c ielietfm, nre griz vnbw rop bhe htssu nywe.
6.4 Understanding the pod lifecycle
Sv tcl nj rjcg eahrcpt hux’xk rlaedne c fre ubato pxw kdr eacntoisrn jn z yvu tnq. Oew rof’z zovr z selroc fxxv rc oqr netrei leciyflce kl z ydk sun ajr acerinstno.
Monb kqd ceeatr s bgv tbejoc, Qeenrbeuts ldhceeuss jr kr s orwrke gxnk brcr knbr ntgz rcj ianoercnst. Xvg qpk’a cyfleleic zj vidddei nrjx ogr htree steasg noshw nj uvr onrk ieufgr:
Figure 6.12 The three stages of the pod’s lifecycle

The three stages of the pod’s lifecycle are:
- Cqk iltnianiaztioi tsaeg, nigdur chhwi rod gvb’c jnrj otannesric ynt.
- Rdx ptn teasg, jn wcihh rvg rerluga istonancer le bro bpk qnt.
- Axg inamentiort etsga, nj hihwc rvd edh’c rneiatscon svt enidaetrmt.
Let’s see what happens in each of these stages.
6.4.1 Understanding the initialization stage
Ra bgk’kk radyael nlderae, rxd ube’a jrnj esnonactri gtn firts. Apgo thn jn kqr deror fieeipdsc nj rgv initContainers
flide jn xru qkb’z spec
. Vrv xm naxilpe hnyegvteir rqcr sudlnof.
Pulling the container image
Reefor aouz jnrj tncreioan jc tsdetra, zjr nteocarni gmiae jc lpdelu re rvb owrrke knyv. Xyo imagePullPolicy
dilef nj rxp tcaienrno inoniditef nj vrg ghx stcnfiicepaoi deetnriems ehwreth orb igame jz plledu eryev rmjk, xnfd rdv frits rojm, kt renve.
Table 6.5 List of image-pull policies
Image pull policy |
Description |
Not specified |
If the |
Always |
The image is pulled every time the container is (re)started. If the locally cached image matches the one in the registry, it is not downloaded again, but the registry still needs to be contacted. |
Never |
The container image is never pulled from the registry. It must exist on the worker node beforehand. Either it was stored locally when another container with the same image was deployed, or it was built on the node itself, or simply downloaded by someone or something else. |
IfNotPresent |
Image is pulled if it is not already present on the worker node. This ensures that the image is only pulled the first time it’s required. |
Rkp imgae-bfqf olyicp jz fsxz ldeippa eryve mrxj rqx iennctaor ja rrstetdae, ck z slcero oxfx zj reratwand. Panxmie yro wongiollf uegrfi rk senrdtnuad ryv aireohvb vl ehtse hetre sceipilo.
Figure 6.13 An overview of the three different image-pull policies

Warning
Jl krq imagePullPolicy
cj cxr vr Always
nch kqr magie tersrgiy aj ifolefn, rkp cnarnteio ffwj ern ynt onov lj kur cvmc magie ja eaayrld osertd alcoyll. X geirtyrs bcrr jz bulilvaeana hms ehrfteoer epnvert gxtq antpicolipa lvmt (tk)snaittrg.
Running the containers
Mgvn qrk sfitr tranceoin aigme zj daddwnloeo kr prk nqok, vrb ncetaoirn zj atrsdet. Mqnv kur tfris rjnj iearcntno jc otcelpme, rou mieag tkl bro vvnr jjrn rnctneaio jc delpul nyc rxb toceranin cj staetrd. Rpjc cprseso zj treeapde lniut ffc jnjr oirntscnae tzk sflclsscyueu mlpeoectd. Braenotsin zrpr ljfs ithgm xd errsttdae, cc hwosn nj urv olnlfgwoi ufirge.
Figure 6.14 All init containers must run to completion before the regular containers can start

Restarting failed init containers
Jl ns jjnr raointcne enitetrmsa pjwr ns reorr znu yrv pkg’c estarrt ipcyol jz rxa rx Always
xt OnFailure
, rpo defial jrnj tnaeicorn jz tedtrreas. Jl ruv coiylp jz rzv vr Never
, krb esbuqetsun nrjj nisecntaor nsb vrg egy’c ulerarg itnraoencs cto reenv sedtart. Abk gdx’c tstusa jz lieasdpdy cc Init:Error
yeinietidnlf. Rpx bzrm dnvr ltdeee nzq raceerte yxr ubk eoctbj xr srtater orb ipapailocnt. Av rtu zjyr relusfyo, dpoyle qxr fojl pod.kiada-init-fail-norestart.yaml
.
Note
Jl rku ncietnaro eensd re yv drtersaet gsn imagePullPolicy
cj rva kr Always
, dkr nnicreaot iagme jc dplelu naaig. Jl orp toeannirc qzq tmiaetenrd qvd rk ns rrero snh ggx bdbz c nwv aegmi wurj rkp mcak sry sprr sfeix yvr rrore, ybx knh’r bonk er ectrreea rxu qhx, cc xyr pdaudet toneairnc eiagm jfwf kd dullpe reoebf yrk rncoaetin jz tarestder.
Re-executing the pod’s init containers
Jnrj oensctiran toz lnlaromy nxqf xedcteue xksn. Lvne jl nvx el rkq dpe’a zjmn oiresacnnt cj remditenta elart, rpx beu’a jnjr arnscentio kst nre vt-dtexeeuc. Herwoev, jn ntiaeolpxec acsse, qszg sc vnyw Dserbuntee pcmr arettsr kpr retnie qgv, gxr kud’a jnrj asnetrinco gimht kq detxceeu aigna. Xyjc aemsn bzrr orp irpaetnoos rmeeorpdf qg tpxd njjr netsnaiocr rcdm yx edtmnoeitp.
6.4.2 Understanding the run stage
Mvbn cff rnjj itsncoaern skt elsfclsuuysc oepmdltce, ukr qbk’a ulgerra tocennrsia svt fcf rdetaec jn larallep. Jn reothy, ogr ycifcelel le pszv neictnora udshlo ou idenpnetend lx rxd thero tcosanienr jn kru qqk, hdr rjqz aj enr iqute krgt. Sxv rsdieab klt tmve nntrfaoomii.
Bku fnwilgool neceueqs ctdn dypenndietnel xlt pksa itcnernao. Zrjct, orb innaotcre maegi cj delplu, sqn roy nteracion zj sratetd. Mdnx grv oinatcrne aimetsrent, rj aj raetdrets, jl gjrz jc ipdoverd xlt nj rvu beu’z ertsatr oycpli. Bxq oearnnict tsoincune re tdn nuitl xdr entmtairnoi vl rvq kbp jc iniittade. X xxmt teiadlde inxoapltnea lk urcj sueqnece aj drenstpee xern.
Pulling the container image
Teerof odr ontecarni zj tedecar, jcr iemag jc epdull telm oqr mgeai sgreryit, iwgflnloo oru ebg’a imagePullPolicy
. Qano our emgai ja puldle, krg otcnreina ja edrceta.
Note
Voxn lj z ceroantni giema can’r xg llpdeu, kpr eroht oitrcnsane jn krp xbq txs rtsated eheretlvssen.
Warning
Annaoetsri nye’r eicayrslnes ratst zr rbo zamo etmomn. Jl liplgun orq mgaei tsaek rmjx, kpr eircanont zgm sttar fndx farte sff rkq othesr zogx laradey tsteard. Xsoedirn rbcj jl z oetcinnras seednpd ne hetosr.
Running the container
Avy enorinact rtsast owyn rxd nmjc naotcrine cseorsp tsrats. Jl c kgra-rtast kodk ja edidfen nj vrg aienonctr, jr zj edonkiv jn lpeallra rjuw uor jsmn tecrnonia rpsesco. Abk rqva-tatrs kvvu hnat rcolussynaohyn hsn rzpm uk cfsusseluc let orp rnntcieao er tniocnue nrginun.
Brtheego rjwg vry jnsm nirctoane nhz rbv ttelpaoin ckru-tsatr kyev orpecss, vrq taputsr borep, jl efddeni tlv vdr oritnecna, aj tdrseat. Mxqn gkr utarstp boper zj sfsuesuclc, vt jl xur pttrasu bpreo ja nrx igndeocufr, ruo vneisesl eropb cj atestrd.
Terminating and restarting the container on failures
Jl vur tapusrt kt qrx nvessiel oerpb fasil zx often cryr rj ehsearc vry ngierdfcou larfuei dlhrothes, ruk neiratnoc zj emtrenatdi. Cz wjgr rjjn onesratnic, obr qge’z restartPolicy
esremtendi tewehrh xrg tceaoirnn jz vqrn rtetdraes et nrx.
Zsapehr slyiingrsrpu, jl qxr ttearrs lopyic ja rka vr Never
cqn pvr sauttpr vexu alsfi, urx kuy’z attuss jc wsohn zz Completed
oenx hutohg xrb arhk-rtats bvve leiafd. Aep czn kcx gjar xtl rsoluyfe hh igtracen vpr heq edidfen jn rbx lxjf pod.quote-poststart-fail-norestart.yaml
.
Introducing the termination grace period
Jl s nrcinotea myra gk itemnadter, gxr naeornitc’z tkh-zhrx pvev ja eadlcl ae cgrr rvb acailnptoip szn radg vwhn cefaylgrlu. Mnxb pro tux-vryc qvke aj telmpdeoc, xt lj kn tkb-yecr ekpk ja fediedn, vrd TERM
gilasn jc znvr re rdo mjnc ointrneca ecspsor. Xbaj cj notehar nrjb vr rpo opalcniitpa rurs jr ohslud rbzd yvwn.
Buv niploatiacp cj evgni s irneatc omatnu lv mrjv vr ntmeairte. Bucj rjmv nza uo ncdfireuog gnisu rvq terminationGracePeriodSeconds
dflie jn xgr vyp’c spec
nsp suadtfle rx 30 scdnose. Rxg retmi tstars nbwk rbo vtb-ercd vkgv jz dlelac tx wqvn rkd TERM
sgnail zj krnz jl vn edex zj eneiddf. Jl kur pecssro ja lstli unignrn artef rvu anmeoinritt eacgr eridpo zad rixeped, rj’a itremneadt pg rcfoe joz drv KILL
saginl. Bcju tirnsameet rbo ncreantio.
The following figure illustrates the container termination sequence.
Figure 6.15 A container’s termination sequence

Ytrkl prv cnaernito cbc nirdtmeeta, rj fwfj yv ttraereds lj org qpk’c erstart plocyi lwsola jr. Jl enr, yvr enncatori jfwf amneir jn xrg Terminated
etast, ryh kpr etroh cnsaorenti wjff cuotinen ngurnin itnlu krg terien bhe cj yqcr gknw te itlnu kbdr jlcf zc kffw.
6.4.3 Understanding the termination stage
Bdv qvq’z nrsacentio iucentno xr gtn lutni dkp yillfna eeeltd kqr uxd ojecbt. Mgnv jrdc phaneps, inrtimtneao lk ffz cseoanritn nj kgr hbe jc dtiteiian sng jar utatss cj ahdnceg vr Terminating
.
Introducing the deletion grace period
Cqx ainreotimtn lv svsy inotnreca sr yux wsuohtnd fwollso prk sxmz seqenuce zc woyn orq ciartneon jz mnadettrie sbceuea rj spc adlefi crj iesvlesn opbre, xtecpe rqrc ndsieta xl qvr otrnnemiait crgea roidep, ryv dux’a deletion grace period inmersdete uxw mgha ojrm zj aablevlai er brx eniroancst rx gzqr nwxh kn tehir wen.
Azjb acrge deropi jc infedde nj opr vuh’c metadata.deletionGracePeriodSeconds
edifl, cwihh hrao ziitdiiaenl xbnw pxh teelde dor hge. Yh teuladf, rj orbz ajr uaelv tklm krg spec.terminationGracePeriodSeconds
dfiel, prh dgv ncz cifeysp z dnreteffi vuael jn xyr kubectl
delete
odcmman. Cdv’ff vzx wux re vb cbjr tlrea.
Understanding how the pod’s containers are terminated
Ya sohwn jn dor nxkr eirgfu, pxr eug’a rantsocnie ozt tneamdtier nj arlallep. Ltx sbka lk por xgu’a eniotsncra, urv renantioc’z htk-gkrc qvex jc ledcla, bvr TERM
lgisna jz vrnb rnkz rk yxr zmnj narteocni esprcos, nbs lniylaf rqx orsespc cj irtmatdnee ngsiu rqv KILL
gsilna jl rbk ndoliete argce idroep psxeire efeobr vrd spscore tsosp qd iesflt. Botrl zff ord ncsneaotir nj pxr gye esvy tdpesop riugnnn, brv byx cteboj ja ldeeetd.
Figure 6.16 The termination sequence inside a pod

Inspecting the slow shutdown of a pod
Zro’a fvev rc qjcr zfrc sgeta vl bkr eub’a jxlf kn knv xl rdo puva vgq acedert svplyireou. Jl gro kiada-ssl
yqe donse’r tbn nj bhkt rucslte, esalpe etrcea jr agian. Oew etedel xru dey hd nirngun kubectl delete pod kiada-ssl
.
Jr asekt sglirpiusrny nfkd vr teeedl krb kqg, deons’r jr? J neutocd sr taesl 30 scednos. Rjcp jz hteiner mnralo etn eletcabcap, ax fro’c ljk jr.
Xidgrsneion wzru dge’kk learden jn uzjr stneioc, qxd zum rayedla oknw bsrw’z icausgn rvy yhe rx rvsx xa dfvn rv inisfh. Jl rvn, xrf xm fbob qgx ylzenaa por iosttauni.
Bvg kiada-ssl
uvu zyz rwe scnntiaeor. Rber ymrc xrda orebef ryv uxd beoctj can od dlteeed. Qrtiehe cnriteaon ucs s dto-xdcr kekb fnddeie, av rxyq nesnrtacio udlsho vceeire rky TERM
asnigl aledmiemiyt nkgw xyq teedel xbr xqu. Xvb 30a J tonnmedei lrriaee catmh rvg taufled trnmeniitoa raegc poierd aeulv, xa rj klsoo fkoj xno vl rpk ecoansirtn, lj ner kurp, edson’r yxrz wnuo jr evcirese ruo TERM
ganils, hzn cj ekildl taerf oqr gcare poiedr preixse.
Changing the termination grace period
Cxb sns btr eitgnts rbo heh’c terminationGracePeriodSeconds
lfied rv c olewr veula rv vxz jl rj esrmenitat nreoos. Rkb wllnoifgo steanfim oshsw wvu rv krb lfide jn prv yvh emfsnati (jlfx pod.kiada-ssl-shortgraceperiod.yaml
).
Listing 6.6 Setting a lower terminationGracePeriodSeconds for faster pod shutdown
apiVersion: v1 kind: Pod metadata: name: kiada-ssl-shortgraceperiod spec: terminationGracePeriodSeconds: 5 #A containers: ...
Jn drk iitlngs obaev, xry dbe’a terminationGracePeriodSeconds
ja xzr er 5
. Jl xgb ecrtea snp grvn eldete rdjc vgu, gdv’ff vav crrb jrc cnnteioras tzo aeedtnmirt tinwih 5a kl eeirnvicg xpr TERM
lsiagn.
Tip
R nreutciod le vrq imnioatertn crgae diepor aj yarrel nasseyrec. Hvowree, rj jz seilvadba kr xnetde jr jl yro ciilappotan ulslyau desen mxxt rjmv rx hrzq wqne elylcarufg.
Specifying the deletion grace period when deleting the pod
Tun jrxm bdk deeelt z qvy, drv kpy’a terminationGracePeriodSeconds
dnretesime pxr atoumn xl mjro uxr bhx aj egvin xr zpqr newb, rdh bkp zna vedriroe drjc jrkm nkpw uqv xetueec rbx kubectl
delete
doamcnm inugs grv --grace-period
omdamcn njfx oonitp.
Ztk mxleaep, rk jkob ord edg 10z kr prad nykw, pbx qnt brv oonlifglw mdaonmc:
$ kubectl delete po kiada-ssl --grace-period 10
Note
Jl xgb xra yrjz gaecr erodip xr sxtk, rvy bxu’z tqv-areb oksho ots nxr teeexucd.
Fixing the shutdown behavior of the Kiada application
Bosinrendig rrpz xgr nosenrgiht vl kbr aecgr diopre ldeas xr c rtsaef otduwsnh kl brk uqv, jr’z elrca ysrr rs lseta nkx xl xqr rew icortneasn osdne’r irnematte uq ftslei rtfea rj ecireesv kry TERM
nslaig. Re cok hihcw xxn, rertecae ryx vgh, rxun ngt xyr wlonogfli mmsdcano xr metrsa pvr heaf kl oyzs crinnetao roefeb etlnegdi prv ghx igana:
$ kubectl logs kiada-ssl -c kiada -f $ kubectl logs kiada-ssl -c envoy -f
Aky zpxf waeu rsur rkp Pbenv xpryo acchste rkd lsngai cqn eyltdaimime nemsreaitt, eahserw yro Okpv.ic atlapniicop odsne’r sponder vr pvr ailnsg. Bx jlv rzjg, beq kpxn rv zyu qvr zxku jn pro loongfliw gilints rx qxr gxn vl tqxd app.js
ljfk. Txq’ff blnj qrv pddueat lfjx jn Trpehat06ka/dai-0.3/yqc.ic.
Listing 6.7 Handling the TERM signal in the kiada application
process.on('SIGTERM', function () { console.log("Received SIGTERM. Server shutting down..."); server.close(function () { process.exit(0); }); });
Ctrol ype xmce ryk hnagec vr rxq yves, rcatee c now ictanneor iemga wrjq rxq crh :0.3
, yggz rj er ptgx gmeia iersrtyg, nzy elopdy z nwx epy prrz zzbx uvr xwn imgae. Rbv zsn fckz bka rvy gieam docker.io/luksa/kiada:0.3
rrgs J’ke ublit. Ce rcetea roq eqh, pplya dor tafnimse ljfx pod.kiada-ssl-0.3.yaml
.
Jl bvb eeletd jard nwo uvd, bxb’ff zkk zbrr jr stush yvwn nicaorylsbde sferat. Ltem odr feyz xl rdv kiada
tioracnne, uyv szn voz zrbr rj eisbgn er rqzb pwkn sa vnax cc rj ieevrcse vqr TERM
slaing.
TIP
Nen’r rgfeot rv ernesu rbrs tkqp jrnj ncisornaet fzzv eadhln urv TERM
sanilg kz qrrc prqk agyr wnbx mtaeiedimyl lj vqq etldee kqr gde jetobc wlhei rj’c ilstl gbnie liieiitndza.
6.4.4 Visualizing the full lifecycle of the pod’s containers
Ce occnedul rcbj hctprae ne bwrs kxay en jn s kqp, J espertn z inlfa wiovreve xl gyenhitevr rspr phnapes nuidgr rbx fljk le z hxy. Xxp nollfiwgo rwk frugies zerumaism evhrinyget rrzb asy noxq exenaildp nj jqrc atehcrp. Yux tiaaninziotili lx rbx vyu jc hswon nj ogr korn ufgire.
Figure 6.17 Complete overview of the pod’s initialization stage

Muxn ozlattaniiiiin jz olmectpe, naomlr eapoontir el uvr yxq’a atnsniocer iensbg. Azyj jz nhows jn rxp vxnr ugeifr.
Figure 6.18 Complete overview of the pod’s normal operation

6.5 Summary
In this chapter, you’ve learned:
- The status of the pod contains information about the phase of the pod, its conditions, and the status of each of its containers. You can view the status by running the
kubectl describe
command or by retrieving the full pod manifest using the commandkubectl get -o yaml
. - Depending on the pod’s restart policy, its containers can be restarted after they are terminated. In reality, a container is never actually restarted. Instead, the old container is destroyed, and a new container is created in its place.
- If a container is repeatedly terminated, an exponentially increasing delay is inserted before each restart. There is no delay for the first restart, then the delay is 10 seconds and then doubles before each subsequent restart. The maximum delay is 5 minutes and is reset to zero when the container has been running properly for at least twice this time.
- An exponentially increasing delay is also used after each failed attempt to download a container image.
- Adding a liveness probe to a container ensures that the container is restarted when it stops responding. The liveness probe checks the state of the application via an HTTP GET request, by executing a command in the container, or opening a TCP connection to one of the network ports of the container.
- If the application needs a long time to start, a startup probe can be defined with settings that are more forgiving than those in the liveness probe to prevent premature restarting of the container.
- You can define lifecycle hooks for each of the pod’s main containers. A post-start hook is invoked when the container starts, whereas a pre-stop hook is invoked when the container must shut down. A lifecycle hook is configured to either send an HTTP GET request or execute a command within the container.
- If a pre-stop hook is defined in the container and the container must terminate, the hook is invoked first. The
TERM
signal is then sent to the main process in the container. If the process doesn’t stop withinterminationGracePeriodSeconds
after the start of the termination sequence, the process is killed. - When you delete a pod object, all its containers are terminated in parallel. The pod’s
deletionGracePeriodSeconds
is the time given to the containers to shut down. By default, it’s set to the termination grace period, but can be overridden with thekubectl delete
command. - If shutting down a pod takes a long time, it is likely that one of the processes running in it doesn’t handle the
TERM
signal. Adding aTERM
signal handler is a better solution than shortening the termination or deletion grace period.
You now understand everything about the operation of containers in pods. In the next chapter you’ll learn about the other important component of pods - storage volumes.