You are on page 1of 68

Kubernetes Fundamentals: A

Step-by-Step Development and


Interview Guide 1st Edition Himanshu
Agrawal
Visit to download the full and correct content document:
https://ebookmass.com/product/kubernetes-fundamentals-a-step-by-step-developmen
t-and-interview-guide-1st-edition-himanshu-agrawal/
Kubernetes
Fundamentals
A Step-by-Step Development
and Interview Guide

Himanshu Agrawal
Foreword by Krishna Prasad P
Kubernetes Fundamentals: A Step-by-Step Development and
Interview Guide
Himanshu Agrawal
Pune, India

ISBN-13 (pbk): 978-1-4842-9728-5 ISBN-13 (electronic): 978-1-4842-9729-2


https://doi.org/10.1007/978-1-4842-9729-2

Copyright © 2023 by Himanshu Agrawal


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Divya Modi
Development Editor: James Markham
Copyeditor: Kimberly Wimpsett
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York,
1 New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201)
348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer Science + Business Media
Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail booktranslations@springernature.com; for
reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub (github.com/apress). For more detailed information, please visit
https://www.apress.com/gp/services/source-code.
Paper in this product is recyclable
For my mother, my sister, and my Pittar Baavji.
Love you, Papa, Unnat, Yashi, Jiju, Bittu, Shanu, Kanak,
Mamaji, Mamiji, and Naaniji.
कर्मण्येवाधिकारस्ते मा फलेषु कदाचन।
मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि॥
Bhagavad Gita Chapter 2, Verse 47:
You are only entitled to act (karma),
not to the fruits of your act.
Do not become attached to the fruits of your actions. At the
same time, do not become attached to inaction (no karma).
Table of Contents
About the Author������������������������������������������������������������������������������xvii

About the Technical Reviewer�����������������������������������������������������������xix

Acknowledgments�����������������������������������������������������������������������������xxi

Introduction�������������������������������������������������������������������������������������xxiii

Foreword���������������������������������������������������������������������������������������� xxvii

Chapter 1: Welcome to The World of Containers!���������������������������������1


Fundamental Questions We Need to Ask��������������������������������������������������������������2
How Has Application Deployment Evolved?����������������������������������������������������2
What Is a Hypervisor?��������������������������������������������������������������������������������������4
What Is Virtualization?�������������������������������������������������������������������������������������6
What Is Distributed Design?����������������������������������������������������������������������������7
What Are Different Application Design Architectures in
Distributed Design?�����������������������������������������������������������������������������������������8
What Is Cloud Computing?����������������������������������������������������������������������������10
What Is Containerization?������������������������������������������������������������������������������12
What Are the Advantages of Containerization Over Virtualization?����������������13
Can Containerized Applications Run on a Cloud Infrastructure?�������������������16
What Is the Microservices Architecture?�������������������������������������������������������16
How Is Containerization Different from the Microservices Architecture?������19
What Is the Future of Containerization?��������������������������������������������������������19
Understanding Key Container Technologies��������������������������������������������������������20
What Is Docker?��������������������������������������������������������������������������������������������20

v
Table of Contents

What Is Kubernetes?�������������������������������������������������������������������������������������21
What Is Red Hat’s OpenShift Container Platform?�����������������������������������������21
What Does Being “Cloud-Native” Mean?�������������������������������������������������������22
What Is Serverless?���������������������������������������������������������������������������������������23
Why Use Docker and Kubernetes?����������������������������������������������������������������24
Comparing Key Container Technologies��������������������������������������������������������������25
What Are the Alternatives to Docker?������������������������������������������������������������25
What Are the Alternatives to Kubernetes?�����������������������������������������������������26
How Are Kubernetes and Docker Related?����������������������������������������������������27
How Is Kubernetes Different from Docker Swarm?���������������������������������������27
How Is Kubernetes Different from Red Hat OpenShift,
Google Kubernetes Engine, and Others?�������������������������������������������������������28
Summary������������������������������������������������������������������������������������������������������������28

Chapter 2: Kubernetes Deep Dive�������������������������������������������������������31


History of Kubernetes�����������������������������������������������������������������������������������������32
How Did Kubernetes Come into Existence?��������������������������������������������������32
What Is the Linux Foundation?����������������������������������������������������������������������34
What Is the Cloud Native Computing Foundation?����������������������������������������34
Kubernetes Architecture�������������������������������������������������������������������������������������35
What Is the Architecture of Kubernetes?�������������������������������������������������������35
What Are the Key Features of Kubernetes?���������������������������������������������������36
What Is Kubernetes Not?�������������������������������������������������������������������������������38
Master Node (Control Plane)�������������������������������������������������������������������������������39
What Does the Master Node Do?�������������������������������������������������������������������40
What Are the Different Components of the Master Node?�����������������������������41
What Is the API Server (kube-apiserver)?������������������������������������������������������41
What Is the Scheduler (kube-scheduler)?�����������������������������������������������������42

vi
Table of Contents

What Is the Controller Manager (kube-controller-­manager)?������������������������42


What Is etcd?�������������������������������������������������������������������������������������������������43
What Is cloud-controller-manager?���������������������������������������������������������������43
Can the Master Node and Worker Nodes Run on the Same Machine?����������44
Worker Node�������������������������������������������������������������������������������������������������������44
What Are the Components of a Worker Node?����������������������������������������������45
What Is the Node Agent kubelet?������������������������������������������������������������������45
What Is the Node Agent kube-proxy?������������������������������������������������������������46
What Is the Container Runtime?��������������������������������������������������������������������46
What Is the Container Runtime Interface?�����������������������������������������������������47
Communication Between Worker Nodes and Master Nodes�������������������������������48
How Does the Worker Node Communicate with the Master Node?��������������48
How Does the Master Node Communicate with the Worker Node?��������������48
Object Management and Garbage Collection������������������������������������������������������49
What Are Objects in Kubernetes?������������������������������������������������������������������50
What Are the Important Elements of a Kubernetes Object?��������������������������50
How Do You Manage Objects in Kubernetes?������������������������������������������������54
What Is Garbage Collection in Kubernetes?��������������������������������������������������56
Installing Kubernetes������������������������������������������������������������������������������������������58
What Are Several Kubernetes Installation Configurations?���������������������������58
What Are Several Options for Running a Kubernetes Cluster on
Any Local Box?����������������������������������������������������������������������������������������������59
What Is Kubeadm?����������������������������������������������������������������������������������������59
What Is Minikube?�����������������������������������������������������������������������������������������59
Summary������������������������������������������������������������������������������������������������������������64

Chapter 3: Fundamental Objects in Kubernetes Clusters�������������������67


Containers�����������������������������������������������������������������������������������������������������������68
What Is a Container and a Container Image?������������������������������������������������69

vii
Table of Contents

Are Containers Immutable and Stateless?����������������������������������������������������69


Can Containers Self-Heal?�����������������������������������������������������������������������������70
Which Kubernetes Component Creates Containers Within a Pod?����������������70
Do We Always Need to Pull the Container Image?�����������������������������������������70
How Do I Create a Pod with a Single Container?�������������������������������������������71
What Are Container Life-Cycle Hooks?����������������������������������������������������������73
What Are the Possible Container Life-Cycle States?�������������������������������������75
What Are Init Containers?������������������������������������������������������������������������������76
Explain Ephemeral Containers�����������������������������������������������������������������������79
What Are Different Multicontainer Pod Patterns?������������������������������������������80
Pods��������������������������������������������������������������������������������������������������������������������81
What Is a Pod?�����������������������������������������������������������������������������������������������81
Can a Pod Have More Than One Container Running Inside It?����������������������82
Is It Recommended to Have More Than One Container in a Pod?�����������������82
Can You Add a New Container After the Pod Has Been Created?������������������83
Can Pods Self-Heal?��������������������������������������������������������������������������������������84
Do Containers Inside a Pod Share Resources like IP Addresses?�����������������84
Within a Pod, Can Containers Have the Same Names?���������������������������������84
What Is the Threshold for the Number of Pods You Can Create
on a Node?����������������������������������������������������������������������������������������������������85
What Are the Different Pod Life-Cycle Phases?���������������������������������������������85
Pod Status vs. Pod Phase Status�������������������������������������������������������������������87
What Are the Different Pod Conditions?��������������������������������������������������������87
How Do You Control Container Restarts Within a Pod?����������������������������������88
How to List Pods from All Namespaces?�������������������������������������������������������89
What Is Pod Networking?������������������������������������������������������������������������������89
Within the Same Pod, Can Containers Share the Pod’s Storage Volume?�����90
How Are Pods Created or Managed?�������������������������������������������������������������90

viii
Table of Contents

What Are Static Pods?�����������������������������������������������������������������������������������90


What Happens to Pods When a Node Dies, and Can the Same
Pod Get Rescheduled to Another Node?��������������������������������������������������������91
What Happens to Terminated Pods?��������������������������������������������������������������91
Can the Pod Be Forcefully Deleted?��������������������������������������������������������������92
What Are Affinity and Anti-affinity in Kubernetes?����������������������������������������92
What Happens When More Than One Node Selection Term Is
Specified with Node Affinity?������������������������������������������������������������������������97
What Happens When More Than One Match Expression Is Specified
with Node Affinity?����������������������������������������������������������������������������������������98
How Will You Make Sure That a Certain Pod Gets Created on a Certain
Node?������������������������������������������������������������������������������������������������������������98
How Will You Make Sure That Your Pod Gets Scheduled Only on a
Node That Is Already Running a Certain Pod?���������������������������������������������101
How Will You Ensure That Two Pods Get Scheduled on the Same Node?����101
How Can You Control Pod Security?������������������������������������������������������������105
What Is the Runtime Class?�������������������������������������������������������������������������106
Summary����������������������������������������������������������������������������������������������������������107

Chapter 4: Advanced Objects In Kubernetes Clusters����������������������109


Workload Resources�����������������������������������������������������������������������������������������110
What Are Workload Resources?�������������������������������������������������������������������110
What Are Several Built-in Workload Resources?�����������������������������������������110
DaemonSet and StatefulSet������������������������������������������������������������������������������111
What Is DaemonSet?�����������������������������������������������������������������������������������111
What Is a DaemonSet Object?���������������������������������������������������������������������111
What Is StatefulSet?������������������������������������������������������������������������������������114
Can You Explain a StatefulSet Object?��������������������������������������������������������114
How Does StatefulSet Different from Deployment?������������������������������������116
How Do You Delete a DaemonSet and StatefulSet?������������������������������������117

ix
Table of Contents

ReplicaSet: Providing a Stable Set of Running Pods�����������������������������������������118


What Is ReplicaSet, and What Is Its Purpose?���������������������������������������������119
What Is a ReplicaSet Object?����������������������������������������������������������������������119
How Do You List All ReplicaSets from All Namespaces?�����������������������������121
How Do You Delete a ReplicaSet?���������������������������������������������������������������122
How Does ReplicaSet Work?�����������������������������������������������������������������������122
Is ReplicaSet Self-Healing?�������������������������������������������������������������������������123
Which Kubernetes Object Creates a ReplicaSet?����������������������������������������123
Do You Need to Explicitly Create a ReplicaSet?�������������������������������������������123
Can ReplicaSet Be Used Independently of the Deployment Object?�����������123
When Do You Explicitly Use ReplicaSet?�����������������������������������������������������124
Deployment�������������������������������������������������������������������������������������������������������124
What Is the Kubernetes Deployment Workload?�����������������������������������������124
Can You Explain Several Elements of the Deployment Specification?���������125
Can You Explain a Simple Deployment Object?�������������������������������������������127
How Do You List All Deployments from All Namespaces?���������������������������129
How Do You Delete a Deployment?�������������������������������������������������������������130
Is a New ReplicaSet Created Each Time a Deployment Is Created?������������130
What Are Deployment Rollout and Revision?����������������������������������������������130
What Are the Different Deployment Life-­Cycle Statuses?���������������������������132
How Can You Restart a Deployment?����������������������������������������������������������134
What Is a Rolling Update?���������������������������������������������������������������������������136
How Can You Roll Back a Deployment?�������������������������������������������������������142
How Can You Scale a Deployment?�������������������������������������������������������������144
What Is Horizontal Autoscaling?������������������������������������������������������������������145
How Can You Pause and Resume a Deployment?���������������������������������������146
Can You Delete a Pod from a Running Deployment, and What
Happens Then?��������������������������������������������������������������������������������������������146

x
Table of Contents

Can You Update a Deployment While an Existing Deployment Is


Rolling Out?�������������������������������������������������������������������������������������������������146
What Is the Difference Between the matchLabels and labels Fields
of Any Object’s Template?���������������������������������������������������������������������������147
What Are Common Deployment Strategies?������������������������������������������������148
What Is the Blue-Green Deployment Strategy?�������������������������������������������149
What Is a Canary Deployment?�������������������������������������������������������������������151
How Do You Deploy a Feature with Zero Downtime in Kubernetes?�����������154
Summary����������������������������������������������������������������������������������������������������������155

Chapter 5: Objects Important For A Secure Kubernetes Cluster������157


Jobs: Seeing the Task to Completion����������������������������������������������������������������158
What Is a Job in Kubernetes?����������������������������������������������������������������������158
How Do Jobs Differ from Other Workload Resources?��������������������������������159
Can You Use a Job to Run Multiple Pods in Parallel?����������������������������������159
Where Can a Kubernetes Job Be Used?������������������������������������������������������159
What Are Alternatives to Kubernetes Jobs?������������������������������������������������160
What Is a Simple Nonparallel Job Object?��������������������������������������������������160
How Do You Specify How Many Tries the Job Controller Should
Make to Finish the Job?������������������������������������������������������������������������������162
How Do You Specify the Maximum Time for Which a Job Should Run?������164
How Do You Delete a Job?���������������������������������������������������������������������������166
What Are Parallel Jobs?�������������������������������������������������������������������������������167
What Is a Cron Job?������������������������������������������������������������������������������������173
How Do You Delete a Cron Job?������������������������������������������������������������������175
What Happens If a Cron Job Is Already Running and It Is Time for
the Next Job?����������������������������������������������������������������������������������������������176
How Do You Control the History of Cron Job Execution?�����������������������������177
Namespaces: Virtual Clusters Within Kubernetes Clusters�������������������������������177
What Is a Namespace?��������������������������������������������������������������������������������177

xi
Table of Contents

Can You Have Multiple Objects with the Same Name in


One Namespace?����������������������������������������������������������������������������������������178
How Do You Create a New Namespace?�����������������������������������������������������178
How Do You Create an Object in a Particular Namespace?�������������������������179
How Do You Delete a Namespace?��������������������������������������������������������������181
How Can You List All the Namespaces?������������������������������������������������������182
Which Namespaces Are by Default Present in the Kubernetes System?����182
Do All Kubernetes Resources Fall Under Some Namespace?���������������������184
How Can You Explicitly Set the Default Namespace?����������������������������������185
Labels and Label Selectors: All About Filtering and Selection��������������������������187
What Are Object Names and Object UIDs?��������������������������������������������������188
Labels����������������������������������������������������������������������������������������������������������188
Label Selectors��������������������������������������������������������������������������������������������191
What Are Annotations?��������������������������������������������������������������������������������196
Authentication, Authorization, and Admission Control��������������������������������������198
How Does Access Control Work in Kubernetes?������������������������������������������198
What Is Authentication?�������������������������������������������������������������������������������199
What Is Authorization?���������������������������������������������������������������������������������204
What Is Admission Control?�������������������������������������������������������������������������207
Summary����������������������������������������������������������������������������������������������������������209

Chapter 6: Networking In Kubernetes����������������������������������������������211


Fundamentals of Kubernetes Networking��������������������������������������������������������212
Basic Computer Networking Concepts��������������������������������������������������������212
What Is Kubernetes Networking?����������������������������������������������������������������215
What Are the Fundamental Restrictions in Kubernetes Networking?����������216
How Do Two Containers Within the Same Pod Interface with
Each Other?�������������������������������������������������������������������������������������������������217
How Do Two Containers, Running in Different Pods, Interface
with Each Other?�����������������������������������������������������������������������������������������217

xii
Table of Contents

How to Expose Applications Inside and Outside of the Cluster?�����������������218


Service: Exposing Applications to the Outside World����������������������������������������219
What Is Service, and Why Do We Need It?���������������������������������������������������219
What Are Endpoints and EndpointSlice?������������������������������������������������������220
What Are a Service Object and Pod Selection?�������������������������������������������221
What Are the Different Service Types?��������������������������������������������������������226
What Is the ClusterIP Service?��������������������������������������������������������������������227
What Is the ExternalName Service?������������������������������������������������������������232
Can You Expose Two Ports in the Same Service?����������������������������������������234
How Can You Add Session Affinity to Your Service?������������������������������������235
What Are the Service Discovery Mechanisms in Kubernetes?��������������������235
Ingress: Consolidate Routing Rules�������������������������������������������������������������������235
What Is Ingress and the Ingress Controller?������������������������������������������������236
What Is an Ingress Object?��������������������������������������������������������������������������237
What Are the Possible Values of the Path Type, and How
Does Path Matching Work?�������������������������������������������������������������������������242
What Are the Different Ingress Types?��������������������������������������������������������243
Summary����������������������������������������������������������������������������������������������������������246

Chapter 7: Kubernetes Storage System��������������������������������������������249


Volumes: Store Your Data����������������������������������������������������������������������������������250
What Is a Volume in Kubernetes, and Why Is It Needed?����������������������������250
What Is the Ephemeral Volume Type?����������������������������������������������������������252
What Is the Persistent Volume Type?�����������������������������������������������������������255
What Are PersistentVolume and PersistentVolumeClaim?��������������������������257
What Are the PersistentVolume and PersistentVolumeClaim Objects?�������260
Can You Demonstrate the Creation and Use of Persistent Volumes?����������264
How Do You Delete PersistentVolume and PersistentVolumeClaim
Objects?�������������������������������������������������������������������������������������������������������267

xiii
Table of Contents

ConfigMap: Store Configuration Data in Plain Text��������������������������������������������268


What Is ConfigMap, and What Is Its Purpose?���������������������������������������������269
What Are Several Ways to Create a ConfigMap Object?������������������������������269
How Can You Use ConfigMap Inside a Pod?������������������������������������������������274
Is ConfigMap Data Immutable?�������������������������������������������������������������������278
Secrets: Store Configuration Data in Encrypted Format�����������������������������������279
What Is Secret, and What Is Its Purpose?����������������������������������������������������279
What Are Several Ways to Create a Secret Object?�������������������������������������280
How Can You Use Secret Inside a Pod?�������������������������������������������������������286
What Is the Difference Between ConfigMap and Secret?����������������������������290
Summary����������������������������������������������������������������������������������������������������������290

Chapter 8: Manage Your Kubernetes Cluster Efficiently�������������������293


Probes: Health Check Your Containers��������������������������������������������������������������294
What Is a Probe?�����������������������������������������������������������������������������������������294
What Are Several Mechanisms for Performing a Probe?�����������������������������294
What Are Some Outcomes of a Probe?��������������������������������������������������������295
What Are Several Types of Probes?�������������������������������������������������������������295
What Are Important Configuration Parameters for Probes?������������������������298
Can You Create an exec Liveness Probe?����������������������������������������������������299
What Is a httpGet Liveness Probe?��������������������������������������������������������������303
What Is a tcpSocket liveness Probe?����������������������������������������������������������305
Can You Create a Readiness Probe?������������������������������������������������������������306
Resource Management: Requests, Limits, and Quotas�������������������������������������312
What Are Requests and Limits?�������������������������������������������������������������������313
What Are Resource Quotas?������������������������������������������������������������������������317
What Are Limit Ranges?������������������������������������������������������������������������������320
Can You Create a Pod with Explicit CPU and Memory Requests and
Limits?���������������������������������������������������������������������������������������������������������323

xiv
Table of Contents

What Happens When You Create a Pod with Unreasonably High


Requests and Limits?����������������������������������������������������������������������������������325
What Happens When You Create a Pod That Breaches Resource
Quota Limits?����������������������������������������������������������������������������������������������326
How to Automatically Assign Default Requests and Limits for Pods?���������328
How Do You Define Minimum and Maximum CPU and Memory
Constraints for Pods?����������������������������������������������������������������������������������330
What Happens When You Create a Pod Without Any Explicit CPU
and Memory Requests and Limits?�������������������������������������������������������������333
What Is Pod Priority, and How Is It Useful?��������������������������������������������������334
Taints and Tolerations���������������������������������������������������������������������������������������338
What Are Taints and Tolerations?�����������������������������������������������������������������338
What Are the Different Effects of Taints And Tolerations?���������������������������342
Can a Node Have More Than One Taint?������������������������������������������������������342
Summary����������������������������������������������������������������������������������������������������������346

Chapter 9: Docker Overview And Kubernetes Best Practices�����������349


Docker: All You Need to Know to Get Started����������������������������������������������������350
Fundamentals of Docker�����������������������������������������������������������������������������350
Understanding Primary Technologies in Docker������������������������������������������364
Primary Docker Commands�������������������������������������������������������������������������369
Docker Best Practices���������������������������������������������������������������������������������������373
What Are Docker Development Best Practices?������������������������������������������373
What Are Dockerfile Best Practices?�����������������������������������������������������������375
What Are Docker Security Best Practices?��������������������������������������������������377
Kubernetes Best Practices��������������������������������������������������������������������������������378
What Are Kubernetes Development Best Practices?�����������������������������������378
What Are the Best Practices for Large Clusters?�����������������������������������������381

xv
Table of Contents

What Are the General Security Best Practices?�������������������������������������������381


What Are the Secret Configuration Security Best Practices?����������������������383
Summary����������������������������������������������������������������������������������������������������������384

Chapter 10: kubectl: The Command-Line Tool����������������������������������385


Fundamentals of kubectl����������������������������������������������������������������������������������385
What Is kubectl?������������������������������������������������������������������������������������������385
How Does kubectl Find the Details of the Kubernetes Cluster?������������������386
Can You Explain a Sample kubeconfig File?������������������������������������������������387
What Is the General kubectl Syntax?�����������������������������������������������������������388
Important kubectl Commands: A Cheat Sheet��������������������������������������������������392
General Commands�������������������������������������������������������������������������������������393
Namespace Commands�������������������������������������������������������������������������������396
Pod Commands�������������������������������������������������������������������������������������������397
Commands to Customize the kubectl Output����������������������������������������������398
Workload Resource Commands�������������������������������������������������������������������401
Deployment Commands������������������������������������������������������������������������������402
Jobs and CronJobs Commands�������������������������������������������������������������������404
Networking Commands�������������������������������������������������������������������������������406
Storage Commands�������������������������������������������������������������������������������������407
Node Commands�����������������������������������������������������������������������������������������408
Summary����������������������������������������������������������������������������������������������������������410

Index�������������������������������������������������������������������������������������������������413

xvi
About the Author
Himanshu Agrawal is an accomplished IT
professional with more than a decade of
experience in designing and implementing
complex solutions with JEE technologies. He
is a technical reviewer for a published book on
JVM and specializes in niche technical areas
such as JVM, Multithreading, TLS, Apache,
and Kubernetes, to name a few. Himanshu
has certifications from prestigious universities
such as Harvard and MIT.
Himanshu is an Oracle Certified Java
Developer, an Oracle Certified Web Component Developer, and certified
by Google Cloud for Architecting with the Google Kubernetes Engine.
Himanshu has also worked on .NET technologies in his early career and is
a Microsoft Certified Professional.
Currently Himanshu works as an Associate Consultant with CGI,
counted among the largest IT and business consulting services firms in
the world. He is a distinguished engineer and a recognized professional
within CGI, having received many quarterly and annual awards. Himanshu
extends his technical expertise to teams primarily in the finance and
telecom domains.
Himanshu actively contributes to online technical communities
including StackOverflow.com. In his spare time, Himanshu enjoys
watching movies and reading books.

xvii
About the Technical Reviewer
Nikhil Jain is an Ansible expert with more
than a decade of DevOps experience. He has
been contributing to and using Ansible since
its inception. He currently works closely with
Ansible engineering.
He is an open-source enthusiast and is part
of the Ansible Pune meetup-­organizing team.
He has presented multiple Ansible sessions
at various global and local events. In addition
to automating things using Ansible, he loves
watching sports and is a regular player on the
local cricket team.

xix
Acknowledgments
I would like to thank Apress and its editorial team for giving me the
opportunity to write this book.
A special thanks to Divya Modi, acquisition editor, for working with
me throughout the project. Without her, this book would not have seen
the light of day. Thanks to the book’s production editor, Sowmya Thodur.
Thanks also to the book’s development editor, James Markham, and the
technical reviewer, Nikhil Jain, for their feedback.
I would like to thank God for everything He has given me.
Finally, I would like to thank my parents, my sister, and my Pittar
Baavji, without whom I would not have gotten this far in my life.

xxi
Introduction
This book is a step-by-step development guide designed with an
interview-driven approach. This book will walk you through the breadth
of Kubernetes concepts required to develop, deploy, and manage
applications on Kubernetes, and as you do so, you will be getting ready for
job interviews. Each concept in the book is presented in the form of a Q&A,
with questions being framed exactly as they would be in an interview. This
book can be of great advantage if you are preparing for a job interview that
involves working with Kubernetes.
Specifically, in Chapter 1, “Welcome to The World of Containers!”
you will understand how application development and deployment have
evolved over the decades and led to containerization. We will discuss a
broad range of concepts such as virtualization, hypervisors, microservices,
and more.
In Chapter 2, “Kubernetes Deep Dive,” we will enter the world of
Kubernetes. We will start our discussion with the Kubernetes architecture
and how all its components work together to form a Kubernetes cluster.
You will also be taken through the history and evolution of Kubernetes.
In Chapter 3, “Fundamental Objects in Kubernetes Clusters,” and
Chapter 4, “Advanced Objects in Kubernetes Cluster,” you will learn about
all the important Kubernetes objects: containers, pods, deployments,
ReplicaSets, and more. We will go into detail about how to work with each
of them to maximize their potential. We will also go through Kubernetes
deployment strategies and concepts related to rollout and rollback.
In Chapter 5, “Objects Important for a Secure Kubernetes Clusters,”
you will learn about Kubernetes objects such as namespaces, jobs, etc.,
that play a pivotal role in creating a secure Kubernetes cluster. You will

xxiii
Introduction

learn how labels, label selectors, and annotations work in Kubernetes. You
will also understand Kubernetes access control mechanisms, covering
authentication, authorization, and admission control.
In Chapter 6, “Networking in Kubernetes,” and Chapter 7, “The
Kubernetes Storage System,” you will learn about two critical components
in any computing ecosystem: networking and storage. We will discuss
Kubernetes services and ingress. We will also go over the various storage
options available in Kubernetes for both normal and confidential data.
In Chapter 8, “Manage Your Kubernetes Cluster Efficiently,” you will
gain an understanding of how to manage a Kubernetes cluster using health
checks, probes, resource quotas, and resource limits. You will also learn
about taints and tolerations.
In Chapter 9, “Docker Overview and Kubernetes Best Practices,” you
will get an overview of Docker. We will also cover some best practices for
using Kubernetes and Docker together.
In Chapter 10, “kubectl: The Command-Line Tool,” you will be
introduced to the kubectl command-line tool. We will also provide a
summary of key kubectl commands.
Over the course of the book, you can expect to learn about the
following:
• How application design and deployment have evolved
over the past decades, including all the related
technologies such as virtualization, hypervisor,
distributed computing, containerization, microservices
architecture, and more

• The architecture and history of Kubernetes

• The two most fundamental objects of Kubernetes:


containers and pods

xxiv
Introduction

• Advanced Kubernetes objects and workload resources:


Deployment, ReplicaSet, StatefulSet, DaemonSet, Job,
and CronJob

• Kubernetes deployment strategies

• Creating virtual clusters within the same Kubernetes


cluster, using the Namespace object

• Access control in Kubernetes, covering authentication,


authorization, and admission control

• Filtering, selection, and tagging using labels, label


selectors, and annotations

• The Kubernetes networking and storage system

• Managing a Kubernetes cluster using health checks,


probes, resource quotas, and resource limits

• The kubectl command-line tool and a cheat sheet of


important kubectl commands

xxv
Foreword
The technological landscape is evolving at an unprecedented pace. Over
the last three decades, I have seen a lot of advancements and am more
excited and optimistic about technological advancements now than ever.
We are making momentous, responsible progress across the technological
spectrum, from human intelligence to machine learning and artificial
intelligence, manual tasks to automation and RPA, distributed ledgers to
blockchains, on-premise to cloud computing, and so on. They all have one
thing in common: a piece of software, an application, on top of the stack
that requires a container to run on.
Along with these technological advancements, we are also making a
significant shift in application design and deployment strategies. Moving
from a monolithic to a microservices architecture is no longer a choice
but rather a fundamental need, a strategic decision in order to maintain
a competitive edge in a world where scalability and resilience are the
foundations of customer expectations. This is where containerization
comes into play. It is expected that, eventually, all production-grade large
to medium-sized applications will be migrated to a containerized platform.
Kubernetes as the best container orchestrator is almost becoming
cliché. Kubernetes sits in the center of any greenfield or brownfield
application architecture and is changing the way applications are
developed and maintained. Container orchestrators such as Kubernetes
are also critical components of the DevOps architecture. And today we
cannot imagine a production design that is not woven with the fabric
of DevOps. This brings us to our central point: Kubernetes is quickly
becoming an indispensable technology for application development and
deployment, and it is a must-learn for anyone working in the field.

xxvii
Foreword

Himanshu begins his book Kubernetes Fundamentals by discussing


how application design and deployment have evolved over time,
eventually leading to containerization. Then he delves into Kubernetes
application development concepts in depth. Himanshu is a distinguished
engineer who has grown from being a software engineer to a technical
architect and is well-known within CGI and various technology forums for
his technical expertise. Himanshu has brought his best knowledge to this
essential book on Kubernetes.
I am pleased to present Himanshu Agrawal’s Kubernetes
Fundamentals.

Krishna Prasad
Vice President Consulting Delivery, CGI

xxviii
CHAPTER 1

Welcome to The World


of Containers!
In this chapter, we will lay some solid groundwork by introducing key
technologies involved in the evolution of containerization. We will start
by covering how application deployment has evolved over the decades.
We will discuss what virtualization is and how hypervisors are key to the
process of virtualization. We will extend that discussion to understand
distributed architecture, cloud computing models, and how virtualization
and distributed architecture are at the core of cloud computing. We will
also discuss the microservices architecture and how containerization is
different from the microservices architecture.
Next, we will start our discussion of two key containerization
technologies: Docker and Kubernetes. We will explain why container
orchestrators like Kubernetes and Red Hat’s OpenShift Container
Platform (OCP) are needed, what it means to be “cloud-native,” and what
serverless is.
Lastly, we will review some popular alternatives to Docker and
Kubernetes and explain how these technologies are related to each other.
We will also compare and contrast two popular container orchestration
platforms: Kubernetes and Docker Swarm.
With those expectations in mind, let’s begin!

© Himanshu Agrawal 2023 1


H. Agrawal, Kubernetes Fundamentals, https://doi.org/10.1007/978-1-4842-9729-2_1
Chapter 1 Welcome to The World of Containers!

Fundamental Questions We Need to Ask


In this section, we will go through several fundamental concepts related
to how application design and deployment have evolved over the past
several decades, as well as key technologies involved in the evolution of
containerization.

How Has Application Deployment Evolved?


We can categorize the evolution of application deployment into three
deployment models: the traditional deployment model, the virtualized
deployment model, and the containerized deployment model. Figure 1-1
depicts the evolution of the application deployment model.

Figure 1-1. Application deployment models

Traditional Deployment Model


In the traditional deployment model, the application runs directly on the
operating system, and the OS runs on the hardware. This deployment
model clearly has a problem because a bad application can end up
hogging most of the server’s resources while other applications are starved

2
Chapter 1 Welcome to The World of Containers!

for the server’s resources. A typical solution used for this problem is to
run each application on a different physical server, but running a set of
physical servers is expensive even for big organizations.
Suppose we have four applications and a 5GB physical server (for easy
understanding, we are only considering RAM size). So, to overcome the
problem, we would deploy our application on different physical servers of
1GB each, guaranteeing a fixed set of server resources to each application.

Virtualized Deployment Model


In the virtualized deployment model, an application runs on a (guest)
OS, and the (guest) OS, instead of running on the hardware as in the case
of the traditional deployment model, runs inside a VM. The VM runs
on a hypervisor, the hypervisor runs on an OS, and the OS runs on the
hardware. The only major problem with this deployment model is that
virtual machines are too heavy, and therefore scalability and performance
become bottlenecks.
Using the same example as before, in the virtualized deployment
model, we would create four 1GB virtual machines on our 5GB physical
server and then deploy each of our four applications in a separate virtual
machine.

Containerized Deployment Model


In the containerized deployment model, an application runs inside a
container, and the container runs on a container runtime (like Docker).
Now, this container runtime runs either on an operating system, as in the
case of a traditional deployment model, or on a (guest) operating system,
as in the case of a virtualized deployment model. In this deployment
model, the container runtime virtualizes the operating system.
Using the same example as before, in the containerized deployment
model, we would deploy our four applications in different containers and
assign 1GB of server resources to each container.

3
Chapter 1 Welcome to The World of Containers!

This is the best and most flexible deployment model because if, at any
point in time, we think that one of our applications needs only 500MB of
server resources, then we can make this adjustment within seconds by
reconfiguring the container to use only 500MB of server resources, thereby
freeing up 500MB of server resources that can then be used somewhere
else. And these adjustments are possible because containers are very
lightweight.

What Is a Hypervisor?
A virtual machine is an emulation of a physical computer, and a hypervisor
is software that creates and runs VMs. A hypervisor virtualizes a host
system’s hardware by emulating CPU, memory, and networking resources
so that these resources can be divided and several virtual machines can be
created from them. Since the hypervisor provides hardware virtualization,
each virtual machine can have a different operating system.
Primarily, hypervisors are of two types: type-1 and type-2. Figure 1-2
shows a graphical depiction of type-1 and type-2 hypervisors.

Figure 1-2. Type-1 versus type-2 hypervisor

4
Chapter 1 Welcome to The World of Containers!

Type-1 (Native or Bare-Metal) Hypervisor


A type-1 hypervisor runs on bare metal (or the host’s hardware), so we can
say that a hypervisor type-1 is an abstraction of the hardware. And since
type-1 hypervisors run on bare metal, they have complete control of the
computer resources, and hence type-1 hypervisors can perform resource
management and allocation without interfacing with the host OS.
The stack for the type-1 hypervisor will look like this: at the bottom,
there is bare metal or hardware; on top of the hardware, there is a
hypervisor; and on top of the hypervisor, there are many different virtual
machines.
IBM z/VM, Oracle VM Server for SPARC, Microsoft Hyper-V, etc., are
type-1 hypervisor examples.

Type-2 (Hosted) Hypervisor


A type-2 hypervisor runs on a host operating system, and the host
operating system runs on the hardware. And since type-2 hypervisors
don’t run directly on the hardware, they cannot perform complete
resource allocation and management; instead, the system administrator
performs resource allocation and management and distributes them to the
required number of VMs.
The stack for the type-2 hypervisor will look like this: at the bottom,
there is bare metal or hardware; on the hardware, there is a host OS; on
the host OS, there is a hypervisor; and on the hypervisor, there are many
different VMs.
VirtualBox (a product of Oracle), VMware Player, etc., are some type-2
hypervisor examples.

5
Chapter 1 Welcome to The World of Containers!

What Is Virtualization?
Virtualization is a broad concept that means creating a virtual representation
of something. In the world of IT, virtualization is a technology that allows
us to virtualize computing resources such as servers, networks, storage,
etc. By hardware virtualization, we get virtual machines (VMs). Two core
entities in the concept of virtualization are hypervisors and virtual machines.
Hypervisors were already discussed in the previous section, and virtual
machines are nothing but byproducts of hypervisors.

What Are Different Virtualization Types?


As mentioned, virtualization is a broad concept through which we can
create a virtual representation of something. In terms of IT, different
virtualization types can be as follows:

• Virtualization of server

• Virtualization of storage

• Virtualization of network

• Virtualization of data

• Virtualization of desktop

How Are Virtualization and Cloud Computing Different?


Cloud computing is nothing but the delivery of computing resources
on an on-demand basis, and virtualization is the technology that makes
cloud computing possible. Without virtualization technologies, there
would be no cloud computing. In cloud computing, when you create a
compute instance, technically it is nothing but a virtualized instance of the
physical server.
Another backbone of cloud computing is distributed architecture.

6
Chapter 1 Welcome to The World of Containers!

What Is Distributed Design?


A distributed design, also known as distributed computing or distributed
system or distributed architecture, is a group of computing systems spread
across multiple computing nodes that work together to achieve a common
goal. These computing systems could be software processes or hardware
devices.
A distributed design is in contrast to a centralized design, where
the complete state of the system lies on a central node or a central node
that plays the role of the master. In a centralized design, since all key
decisions are centralized, there are always chances of bottlenecks and
the failure of one node resulting in complete system failure. Chances of
such bottlenecks or cascading failure are greatly reduced with distributed
designs.

Figure 1-3. Distributed design versus centralized design

As shown in Figure 1-3, both in distributed systems and in centralized


systems, there are many nodes (computing systems), but the difference is
that in the case of a centralized system, one node will play the role of the

7
Chapter 1 Welcome to The World of Containers!

master, managing all other worker nodes, while in the case of a distributed
system, there is no such master node. This master node of the centralized
system can result in a cascading failure of nodes, and since this master
node is absent in the distributed system, there is no single point of failure,
making distributed systems very resilient.
In simple words, having a distributed system or design just means
that your system is designed in such a way that there is no single point of
failure.
Cloud computing, the microservices architecture, and
containerization, in some way or another, are all practical examples of
distributed systems.

 hat Are Different Application Design


W
Architectures in Distributed Design?
Depending on how you are designing your application, there can be four
application architectures in distributed computing:

• An architecture with one client and one server

• An architecture with three tiers


• An architecture with n tiers

• An architecture involving peer-to-peer communication

An Architecture with One Client and One Server


This is the most basic type of distributed computing architecture, which
consists of one server and one or more clients. The server is responsible
for providing a service, and the clients consume the service by making
requests to the server. Most commonly, these requests are made using a
lightweight protocol like HTTP. Email servers, web servers, and file servers
are good examples of a client-server architecture.

8
Chapter 1 Welcome to The World of Containers!

And since client-server architecture is a centralized architecture,


it is prone to issues of a centralized architecture like communication
bottlenecks and single points of failure.

An Architecture with Three Tiers


In an architecture with three tiers, on the server side, there is more
than one tier: one tier representing application servers and one tier
representing database servers.
The tier representing application servers commonly plays the role of
the middle tier, sitting between clients and database servers. They contain
all the application and business logic needed for running the application.
The tier representing database servers commonly plays the role of the
data tier that is responsible for data storage and management. There is no
direct communication with this third tier from the client tier; the third tier
communicates only with the middle tier.
The advantage of a three-tier architecture is that it reduces
communication bottlenecks and single points of failure and improves
distributed computing performance.

An Architecture with n Tiers


In an architecture with n tiers, which is commonly known as a multitier
architecture, is an upgrade of the architecture with three tiers in which
server responsibilities are further divided into layers or tiers and each layer
has a specific responsibility.
Suppose the application design is broken down into five parts; then it
becomes a five-tier application architecture. The three-tier architecture is
an example of n-tier architecture.

9
Chapter 1 Welcome to The World of Containers!

Peer-to-Peer
The peer-to-peer architecture eliminates the roles of client and server
because, in this architecture, there is no separate node that performs the
role of a server and there is no separate node that performs the role of a
client; any node can have the role of a client or a server.
The peer-to-peer architecture is the closest form of a decentralized
system. In peer-to-peer architecture, since any node can play the role of a
server or client, the scalability of peer-to-peer architecture is the highest.
Blockchain and instant messaging are the best examples of a peer-to-peer
architecture.

What Is Cloud Computing?


Simply put, cloud computing is the delivery of computing resources on an
on-demand basis, and the client pays on a usage basis. These computing
resources could be ready-to-use applications, servers (either physical or
virtual machines), storage, networking, etc. A cloud provider hosts these
computing resources at a remote data center and makes them available
over the Internet on an on-demand basis.
The cloud computing model is in contrast to the traditional on-­
premises IT model, where organizations either pay huge up-front costs to
purchase the expensive infrastructure or pay heavy monthly bills for all
the infrastructure they have rented or leased, irrespective of whether it is
used. In this way, cost savings are among the many advantages of cloud
computing. Another big advantage of the cloud computing model is that it
makes infrastructure provisioning very rapid. With cloud computing, the
provisioning of resources can be achieved in just a couple of mouse clicks
and within a few seconds or minutes, which is in contrast to the traditional
on-premises IT model, where clients need not go through a tiresome
bureaucratic process and wait for days or weeks to get the requested
infrastructure resources.

10
Chapter 1 Welcome to The World of Containers!

Virtualization and distributed architecture are enablers of cloud


computing. And, containerization and the microservices architecture are
complementary technologies that, when combined, provide a very cost-­
effective, scalable, and fault-tolerant application ecosystem.

What Are the Types Of Cloud Deployment Models?


Broadly, cloud deployment models can be categorized as follows:

• Public cloud model

• Private cloud model

• Hybrid cloud model

A public cloud is a cloud deployment model in which a cloud provider


makes all the computing resources available to users over the Internet.
Google Cloud by Google, Azure by Microsoft, and AWS by Amazon are
examples of public clouds. A private cloud is a cloud deployment model
in which a cloud provider makes all computing resources available to the
client on-premises in the client’s data center. Many companies opt for
private clouds for security and regulatory compliance reasons. A hybrid
cloud deployment model is a cloud deployment model that combines both
public clouds and private clouds.

What Are the Types of Cloud Services?


Broadly, cloud deployment models can be categorized as follows:

• Infrastructure as a Service (IaaS)

• Platform as a Service (PaaS)

• Software as a Service (SaaS)

In IaaS, complete infrastructure—storage, networking, physical


servers, etc.—is rented, and the client is responsible for setting up and
managing everything. In PaaS, infrastructure is managed by the cloud

11
Chapter 1 Welcome to The World of Containers!

provider, and the client gets an environment for developing and delivering
applications. In SaaS, the client gets on-demand access to ready-to-use
applications over the Internet.

What Is Containerization?
Containerization is a form of virtualization, because they both allow for full
isolation of applications from underlying infrastructure so that they can
be operational in different types of environments. With containerization,
we can bundle all of the components of an application needed to run the
code into a single lightweight executable called a container and run it in an
isolated user space on the same shared operating system.
The idea of containerization and process isolation has been around
for a long time, but the architectural shift to microservices and the release
of the open-source Docker Engine accelerated the widespread adoption
of this idea. Another major reason for the widespread adoption of
containerization is that it makes the application totally portable. Once we
have packaged all the components of an application into a single container
image, we can run this image in any environment as long as there is a
container runtime in that environment. The way the JVM makes the Java
platform independent, similarly containerization makes applications
“write once and run anywhere.”
There are many use cases for containerization, but the most popular
ones are microservices and multicloud deployment.

What Is the Open Container Initiative?


The Open Container Initiative (OCI) is an open governance framework
created specifically to develop an open and common industry standard for
container runtimes.

12
Chapter 1 Welcome to The World of Containers!

The rapid growth in interest and use of container-based solutions


has necessitated the development of container technology standards
and methods to bundle the application code. Docker and other
container industry leaders established the OCI in June 2015. The runtime
specification, image specification, and distribution specification are
the three specifications that currently make up the OCI. The image
specification outlines standards for the creation of a container image. The
OCI image specification contains an image index, an image manifest, a set
of file system layers, and a configuration. The distribution specification
outlines how to facilitate and standardize the distribution of content.
The advantage of the OCI standard is that you can easily move your
application between OCI-compliant container runtimes.

 hat Are the Advantages of Containerization


W
Over Virtualization?
Figure 1-4 illustrates the advantages of containerization over virtualization,
which we will explore in detail in this section.

Figure 1-4. Containerization versus virtualization

13
Chapter 1 Welcome to The World of Containers!

These are the advantages:

• Portability: One of the biggest advantages of


containerization over virtualization is portability.
A containerized application will run the same in
all environments, whether it is development or
production, as long as there is an underlying container
runtime running in that environment. And that is
because a containerized application has everything it
needs to run. This is much like how the JVM makes the
Java code platform independent.

• Isolation and allocation: In the case of virtualization,


you cannot put applications in certain resource
boundaries. But with containerization, you can specify
the resource limits of containers, thereby putting
resource boundaries on the application itself. Please
note that here the comparison is between virtualization
and containerization technologies to provide resource
limits directly on the applications; this comparison is
not with runtimes like JVM, which provide an option
to limit memory usage. And even if we compare it with
runtimes like the JVM, with JVM there is no option
to specify CPU and other resource limits, which is
possible in the case of containerization.

• Better fit for microservices: Containerized applications


are an excellent fit for the microservice architecture
because we can deploy and scale containers
individually. So, with the microservices architecture,
we can decompose our application into smaller
services and run each of these services inside a
container that can be scaled up or down as per request
traffic requirements.

14
Chapter 1 Welcome to The World of Containers!

• Scalability and speed: Containers can be created,


replicated, or destroyed much faster as compared to
hypervisors because the OS kernel is shared among
applications. Please note that how fast a container
can start will depend on the size of the application,
but typically containers can start within a few seconds
while virtual machines can take a couple of minutes.
And since containers are lightweight and faster to re-­
create, scaling containers is much easier than scaling
virtual machines.

• Resource efficient: Since containers (container images,


to be more precise) include only the applications
really needed to run, they are much smaller in size as
compared to a virtual machine, and this allows the
underlying machine (whether physical or virtual) to
run more containers on the same server capacity.

• Fault isolation: Each container running on a


container runtime runs in isolation from other
running containers; therefore, if one container fails,
then it doesn’t impact the working of other running
containers. In fact, this is an advantage in the sense
that if we have an e-commerce application with three
services (in turn, containers): account, billing, and
catalog. If for whatever reason the account container
has crashed, then users can still do cataloging and
billing. Please note that fault isolation is not the same
as fault tolerance. Containers themselves don’t provide
fault tolerance, but container orchestration systems like
Kubernetes do.

15
Chapter 1 Welcome to The World of Containers!

• Automation: Designing an automation solution that


would work seamlessly across different platforms and
resources is easier with containerization as compared
to virtualization.

 an Containerized Applications Run


C
on a Cloud Infrastructure?
Yes. Containerized applications don’t depend on the type of hardware
infrastructure. Underlying hardware infrastructure can be our own laptop
or cloud infrastructure spread across multiple data centers.

What Is the Microservices Architecture?


Microservices (or the microservices architecture) is a cloud-native
architectural approach in which an application is decomposed into many
loosely coupled and independently deployable services.
The microservices architecture has many characteristics, but the
following are the most essential characteristics of any microservices
architecture-based application:
• Each application service should be independently
deployable.

• There should not be any tight coupling between the


services of the application. This basically means that if
a change is needed in one service, then another service
should not be significantly impacted.

• Each service should be built around a single business


function or use case.

16
Chapter 1 Welcome to The World of Containers!

• Each service should be designed for failure without


bringing down the complete application. This basically
means that if a service crashes or fails, then the entire
application should not come down.

• Each service should communicate with the other using


a lightweight protocol like HTTP and a lightweight data
exchange format like JSON.

• Preferably, all interfacing with all the services should


pass through some API Gateway.

Figure 1-5 is a simple graphical depiction of the microservices


architecture.

Figure 1-5. Microservices architecture

The microservices architecture has many advantages, but the following


are some fundamental ones:

• Easier to build: The whole idea behind the


microservices architecture is to break down a big
application into smaller pieces, so it gets easier to build
smaller pieces. Different teams can work on each piece
with a total focus on a single business function.
17
Chapter 1 Welcome to The World of Containers!

• Easier to deploy: Since services in a microservices


architecture are smaller, they will have fewer
environmental dependencies and other complications
related to deploying a large application, making them
easier to deploy.

• Easier to maintain: If a bug arises in a large application,


then it can become a major challenge because of so
many moving parts, but if the application size is small,
then it becomes easier to find issues and maintain the
application.

• Higher performance and scalability: Most commonly,


each of the services of the microservices architecture
gets deployed on a containerized platform, and
containers inherently provide performance and
scalability.

Microservices vs. Monolithic


The microservices architectural approach is in contrast to the
monolithic architectural approach, in which everything is bundled into
one application and shipped as a single deployable unit. The biggest
disadvantage of monolithic architectural approach is that if one part of the
application fails or crashes, it brings down the entire application because
everything is tightly coupled. The microservices architecture remedies this
problem by promoting cohesion and loose coupling.

Microservices vs. SOA


The microservices architectural approach is also contrasted with the
service-oriented architecture (SOA) architectural approach, in which
reusable components are designed via service interfaces. The central
component of SOA architecture that performs integrations between

18
Chapter 1 Welcome to The World of Containers!

applications is an enterprise service bus (ESB). The biggest disadvantage


of this architectural approach is that over time, the system can become
more and more complex and end up with several interdependencies
between services. To sum up, SOA architecture is around integration and
has enterprise-wide scope, while microservices are around application
design architecture and have application-wide scope.

 ow Is Containerization Different from the


H
Microservices Architecture?
I think it is incorrect to compare containerization and the microservice
architecture. Containerization and the microservices architecture are not
competing technologies but rather complementing technologies. Using
a microservices architecture, an application is broken down into smaller
services, and then each service is deployed in a separate container that can
be scaled up and down as per the requirements.
A container is a key component of the microservices architecture, and
other key components and technologies are Kubernetes, API gateways,
and messaging.

What Is the Future of Containerization?


Even though containerization has taken center stage in the last decade,
I still think the future of containerization is just getting warmed up.
Eventually, almost all applications (whether enterprise applications or
small applications) will get containerized to take maximum advantage
of the cost benefits offered by the cloud computing model and ease of
application maintenance and scalability.
Many prominent technology research firms have done numerous polls,
and all of the results agree that containerization is the way of the future.

19
Chapter 1 Welcome to The World of Containers!

Understanding Key Container Technologies


In this section, we will understand two key container technologies: Docker
and Kubernetes. We will also discuss Red Hat’s OpenShift Container
Platform (OCP) and what is it means to be “cloud-native.”

What Is Docker?
Docker is an open-source platform that allows you to develop, run, and
ship containerized applications. Simply put, Docker is a container runtime
that enables you to package all your application code along with its
dependencies (external as well as system) into an image and then create
containers by running the image.
A container runtime is a piece of software that knows how to run a
container from a container image. Docker is one of the most popular
container runtimes. There are other popular container runtimes, such as
the following:

• CRI-O: A Kubernetes Container Runtime Interface


(CRI) implementation that makes it possible to use
runtimes that are compliant with OCI standards.

• containerd: A Cloud Native Computing Foundation


(CNCF) project and another open-source container
runtime, which was introduced as an alternative
to Docker with its significant focus on simplicity,
robustness, and portability.

Before Kubernetes v1.24, there was a direct integration with Docker


Engine using a component named Dockershim. Kubernetes v1.27 requires
that you use a runtime that conforms to the Container Runtime Interface.

20
Chapter 1 Welcome to The World of Containers!

What Is Kubernetes?
Kubernetes allows you to deploy, scale, and manage containerized
applications in a regulated and automated manner. Simply put,
Kubernetes is a container orchestrator. Within the technical community,
Kubernetes is also referred to as K8s. Using container runtimes like
Docker, you can package your code, dependent libraries, and runtime into
an image and run it to create containers, but containers are transient; if
your container crashes, you will need to ensure that another container
is created automatically, so these are the kinds of things that a container
orchestrator like Kubernetes does. Kubernetes also enables you to do
resource management, group the containers to create clusters, etc.
There are many technologies and projects that are built on Kubernetes,
for example, Kubeflow. The Kubeflow project aims to simplify the overall
design, portability, and scalability of machine learning (ML) workflow
deployments on Kubernetes.

What Is Red Hat’s OpenShift Container Platform?


The OpenShift Container Platform (OCP) is a highly scalable Kubernetes
platform by Red Hat that allows you to develop and run containerized
applications. Using OCP, you can quickly scale an OCP cluster from a
handful of servers to hundreds of thousands of servers.
The OpenShift Container Platform has its foundation in Kubernetes,
and it integrated very well with other Red Hat technologies, which allows
you to quickly extend and move your application from a single server
or VM to any cloud environment. The OCP provides enterprise-level
enhancements to Kubernetes, such as the following:

• Hybrid cloud deployments: You can deploy your OCP


clusters in a variety of cloud deployment models.

21
Another random document with
no related content on Scribd:
bleus, verts, rouges, jaunes et violets. Je m’enhardissais jusqu’à
entrer dans le chœur, où je soulevais le couvercle de l’harmonium
dont jouait le frère Théodore. Je regardais les touches blanches et
noires, les registres sur lesquels étaient écrits des noms tels que
Bourdon, Clairon, Flûte, Clarinette, Hautbois. Je n’allais pourtant
point jusqu’à souffler du pied ni appuyer du doigt sur une touche : il
me semblait que l’église se serait écroulée pour m’ensevelir sous
ses ruines si j’avais eu l’audace de profaner un instrument dont
pouvait seul s’approcher un homme de la science du frère Théodore.
J’aimais les cérémonies religieuses, non par piété, mais par une
sorte de sentiment de la poésie que je ne pourrais définir. Ces
chants d’église me plaisaient, toujours graves, qu’ils fussent tristes
ou joyeux ; parfois j’aspirais vaguement à devenir un grand
organiste, dans le genre du frère Théodore.
V

— Madame, voulez-vous qu’Albert vienne s’amuser avec nous ?


C’était l’après-midi d’un jeudi d’octobre, le deuxième après la
rentrée des classes. Assis près de la cheminée où deux bûches se
consumaient lentement, Berlâne rêvait à vide, le menton appuyé sur
la paume des mains.
— Mais certainement, monsieur Georges ! dit Mme Dumas. Je ne
demande pas mieux : cela le distraira. Regardez-le donc ! Il est là à
s’abâtardir au coin du feu. Mais il est vraiment mal habillé pour sortir
avec vous. Je vais lui donner son autre blouse noire.
— Vous n’y pensez pas, madame ! répondit M. Georges. Pour
jouer on est toujours trop propre.
La porte de la salle à manger restée entr’ouverte, Mme Dumas
était assise à son comptoir, attendant les clients. M. Georges ne
venait rien acheter, mais elle était plus heureuse que s’il lui avait pris
d’un seul coup pour un louis de mercerie. Ce gamin de dix ans,
qu’elle appelait M. Georges, était le fils cadet des Labrosse,
bourgeois qui se fournissaient chez elle. Elle était leur humble
servante, comme de tous ceux qui voulaient bien lui donner leur
clientèle : même dans une petite ville on n’a entre les commerçants
que l’embarras du choix. Georges venait en éclaireur de la part de
Robert, son aîné. Je ne les aimais ni l’un ni l’autre. Comme Berlâne
et moi, ils étaient élèves de l’école des frères ; ils se distinguaient
parmi les moins appliqués à l’étude et les plus turbulents dans la
cour des récréations. Leurs deux camarades intimes, les fils Rouget,
étaient, au commencement du mois, partis pour le lycée. Et ils
restaient seuls, désemparés et s’ennuyant. Alors ils avaient pensé à
leur plus proche voisin. Ou, plutôt, c’était leur mère qui avait dû leur
dire, les voyant comme deux corps sans âme :
— Allez donc inviter ce pauvre Albert.
Mme Duras considéra que c’était un grand honneur pour elle, en
la personne de son fils. Elle déplorait qu’il restât toujours seul, et elle
souffrait à la pensée qu’il fût si déshérité que personne ne tînt à
rechercher sa compagnie.
Il se leva. Pourtant, lui non plus, il ne les aimait pas, les deux
Labrosse. Ils étaient de ceux qui, l’hiver précédent, lui avaient lancé
des boules de neige en criant : « Sur Berlâne ! » Mais, puisque sa
mère le lui ordonnait, sans protester il suivit « Monsieur Georges »
comme un petit domestique.
Les deux maisons se touchaient presque, mais qu’elles étaient
différentes ! Qu’il y avait loin de l’humble boutique à la demeure des
Labrosse avec ses deux étages ! Au rez-de-chaussée, les trois
fenêtres du salon donnaient sur la grand’rue. Que de fois,
lorsqu’elles étaient ouvertes, il avait, en passant, regardé les beaux
meubles vernis, les cadres dorés accrochés aux murs et la grande
table ronde, au milieu, chargée d’albums, dont il eût voulu caresser
le cuir épais ! Il ne lui venait même pas à l’idée qu’un jour il y pût
entrer. Et voici que Georges n’eut qu’à pousser deux portes, celle du
corridor, qu’il referma sur eux, puis une autre : et Berlâne se trouva
sur le seuil du salon, si interdit qu’il ne pensa pas tout de suite à
enlever sa casquette. Assise dans l’embrasure d’une fenêtre, Mme
Labrosse faisait du crochet avec Mlle Gertrude, sa fille, qui avait dix
ans. Étendu sur le canapé, les mains croisées sous la nuque, Robert
sifflotait comme un homme.
— Maman, dit Georges, voici Albert que je ramène. Il va jouer
avec nous.
— Tu es content, Albert ? lui demanda Mme Labrosse.
— Oh ! oui, madame ! répondit-il en devenant tout rouge.
Il était au supplice. Il regrettait son coin de cheminée ; quelle
bonne après-midi il eût passée là !
— Eh bien, mes enfants, allez ! dit-elle. Et n’oubliez pas de
rentrer pour vos quatre heures.
Il dut, à leur suite, traverser le salon en s’efforçant de ne point
glisser sur le parquet ciré. Il n’avait osé ni lever les yeux pour voir de
plus près les cadres dorés, ni avancer la main pour toucher le cuir
des albums.
— Qu’est-ce que nous allons faire à présent ? dit Robert,
lorsqu’ils furent dans la cour.
— Si nous allions dans le bois ? dit Georges. Nous emmènerions
le chien.
Roux comme un renard, presque aussi gros qu’un loup, Stop
était dans un tonneau, à l’entrée de la cour. Depuis qu’il les avait
vus, il aboyait en tirant sur sa chaîne. Berlâne avait, comme moi,
peur des chiens. Vous croyez qu’ils se promènent par les rues,
pacifiquement, en quête d’une borne ou d’un angle de mur ? Non. Ils
ont des intentions bien pires. Ils passent avec leurs mâchoires
ornées de crocs pour me mordre.
Il pensa dire :
— Il vaudrait peut-être mieux le laisser ici. Dans son tonneau il ne
doit pas être malheureux, pas plus que je ne l’étais tout à l’heure au
coin de la cheminée.
Mais il n’osa encore pas. Le chien avait ici beaucoup plus
d’importance que lui. Nul doute que, si Stop avait pu causer,
Georges ne fût pas venu inviter Berlâne.
Il faut voir cette après-midi d’un jeudi d’octobre. Tout le long du
chemin qui mène au bois, les feuilles jaunes, pour toujours
détachées de leurs branches, volent à l’aventure, égarées. Elles se
réunissent au pied de la haie. Les entendez-vous qui se concertent,
inquiètes ? Elles ne savent ce qui leur arrive.
Dans le ciel, des nuages d’un joli gris passent si vite qu’on a juste
le temps de les voir et de les saluer de loin.
Las de l’été, le soleil commence à prendre du repos, et le vent,
que l’on n’a guère entendu depuis l’hiver dernier, se remet à donner
de la voix, comme Stop, que voici revenir d’une course folle et qui
gambade autour de ses maîtres, autour de Berlâne, qui n’est pas
fier.
Berlâne essayait de sourire au chien pour se concilier ses
bonnes grâces, mais le moyen de voir sans trembler cette gueule
ouverte, langue pendante et dents pointues, de sentir cette chaude
haleine passer sur ses mains qu’il ne retirait pas de peur que Stop,
s’excitant au jeu, ne s’avisât de les lui happer ?
Mais Robert et Georges n’étaient-ils pas là pour le défendre ?
Non : ils ne faisaient pas plus attention à lui qu’à leur chien. Et
Berlâne se contentait de les écouter parler de l’école, des tours de
force que Lagache exécutait au trapèze et des bons tours qu’il jouait
au frère Stanislas. Lagache ? Un parisien dont les parents venaient
de s’installer ici. De tous nos camarades c’était certainement celui
dont Berlâne et moi nous avions le plus peur. Mais Berlâne se crut
obligé de sourire tout le temps que les deux Labrosse en parlèrent :
il souriait bien au chien !

Robert dut éprouver un violent besoin d’action. Il bondit en


poussant un cri qui ressemblait à un cri de guerre, Georges le suivit.
Berlâne, resté seul, hésita d’abord, puis se mit à courir lui aussi.
Mais il n’en avait guère l’habitude. Tout de suite essoufflé, il dut
s’arrêter : son cœur battait trop fort. Un instant il crut que sa tête
allait l’entraîner en avant.
— Eh bien, vrai, lui dit Robert quand il les eut rejoints, tu ne cours
pas vite !
Une fois de plus il essaya de sourire ; mais il ne réussit qu’à faire
une grimace et ne trouva rien à répondre.
Il s’assit près d’eux sur le socle d’une croix qui se dresse au
carrefour de quatre chemins.
— Si on en grillait une ? dit Robert qui tirait de sa poche un
paquet de cigarettes.
Georges en prit une.
— Une cigarette, Albert ?
— Merci bien, dit-il. Je ne pourrais pas fumer : ça me rendrait
malade. Et puis c’est défendu.
— Défendu, ricana Robert. Et par qui donc ?
— Mais maman m’a toujours dit qu’il ne faut pas fumer.
— Oh ! Ta mère… Eh bien, tu vois si ça me gêne, moi.
Heureux de poser à l’homme devant Berlâne, sur la pierre il fit
craquer une allumette : il lui semblait qu’il y eût entre eux non pas
deux ans, mais vingt, de différence.

— Et ta bonne amie, est-ce qu’il y a longtemps que tu ne l’as


embrassée ? lui demanda Robert entre deux bouffées.
Cette fois Berlâne ne sut quelle contenance prendre. Il rougit
beaucoup plus encore que dans le salon : il devint écarlate, comme
dans les grandes circonstances. Ses oreilles bourdonnèrent : que
venait-il d’entendre ! Sa « bonne amie » ! Mais cela aussi était
défendu, comme de fumer. Certes il éprouvait parfois de profonds
désirs de tendresse. Mais c’était en lui-même un jardin secret dont il
n’avait point la clef et qu’il n’apercevait qu’entouré d’un brouillard
bleu pâle. Et voici que quelqu’un brutalement déchirait le voile et
enfonçait la porte…
— Je n’en ai pas, répondit-il tremblant dans l’attente du nom que
n’allait pas manquer de prononcer Robert.
— Tu n’as pas de bonne amie ! Alors pourquoi est-ce que tu es
toujours fourré chez les Chovin, si ce n’est pour embrasser la
Marie ?
Berlâne respira : Robert ne savait rien.
— Laisse-le donc tranquille, dit Georges à son frère. Tu vois bien
que tu l’embêtes.
— Avec ça !… Il est bien content, au fond.
Ah ! oui, Berlâne était content ! Il trouvait l’après-midi
interminable. Est-ce que les Labrosse n’auraient pas pu se
promener sans lui ? Comme tous les fils de riches ils devaient avoir
à la maison beaucoup de jeux intéressants : tirs, soldats que l’on fait
défiler, ménageries avec arbres et animaux en bois peint. Il n’avait
peur des chiens que vivants. Sans doute eût-il encore préféré rester
seul, mais voir et toucher ces beaux objets eût été une
compensation à son ennui. Tandis qu’ici, que faisaient-ils ? C’était
cela qu’ils appelaient s’amuser ? Oui. Car ils étaient bien plus
heureux de fumer en cachette de leur mère que de tirer du fond d’un
placard ces jeux auxquels ils ne s’intéressaient plus : Robert, aux
environs de sa douzième année, Georges lui-même, moins âgé, ne
voulaient plus qu’on les prît pour des gamins. Leur enfance, ils la
considéraient l’un et l’autre comme terminée. Mais Berlâne, lui, était
toujours un enfant : peut-être le resterait-il toute sa vie ?

— Allons voir du côté de l’étang s’il y a des grenouilles, dit


Robert.
Ils entrèrent sous bois, et par des sentiers boueux aboutirent à
l’étang desséché que de récentes pluies avaient légèrement rempli.
Aussitôt qu’elles les eurent entendus, les grenouilles se hâtèrent
de sauter dans la vase : s’ils voulaient venir les y prendre, elles les
attendaient. Elles ignoraient que Berlâne eût peur d’elles, loin de leur
être un ennemi. Il eut un brusque haut-le-corps.
— Tu as donc peur des grenouilles ? lui dit Robert qu’au surplus
cela ne surprenait guère.
— Mais non ! répondit-il d’un tel accent que Robert pensa : Nous
allons bien rire, et dit à voix basse quelques mots à son frère.
Quelques grenouilles, plus confiantes, étaient restées parmi
l’herbe humide. Robert en saisit une et la tint par les pattes de
derrière. Berlâne la trouva horrible.
— Tu vois bien, dit Robert, que ce n’est pas méchant.
Il fit un signe à Georges qui maintint Berlâne par les bras, et il
rapprocha la grenouille de son visage.
— Non ! Non ! implorait Berlâne en se débattant.
Décidément ils avaient eu une bonne idée de l’amener avec eux :
jamais Stop ne se fût effrayé ainsi à la vue d’une grenouille. Et,
puisqu’ils le tenaient, ils ne le lâchèrent pas. Ce n’étaient pas de
méchants garçons, mais ils ne furent pas maîtres de cet instinct qui
souvent pousse les riches à faire des pauvres leurs souffre-douleurs.
Positivement Berlâne sentait le pauvre. Et ce n’était pas seulement
son attitude, mais son corps même, qui le désignaient comme la
victime nécessaire de toutes les plaisanteries et de toutes les
persécutions.
Robert ne se contenta point de rapprocher de son visage la
grenouille : il la lui promena sur la peau. Berlâne poussa un grand
cri, celui que j’aurais poussé dans les mêmes circonstances. Si
Georges avait cessé de le tenir, il serait tombé raide. Que c’était
amusant ! Robert, jetant la grenouille comme un instrument devenu
inutile, se tordait de rire. Il…
Mais qu’y avait-il donc ? Berlâne fermait les yeux ? Pâle
d’habitude, il était maintenant plus blanc qu’un mort. Ils le
regardèrent tous les deux en même temps.
— Il a tourné de l’œil ! dit Robert. Nous sommes frais ! Va vite
tremper ton mouchoir dans l’eau.
Ils lui mouillèrent les tempes.
Deux minutes après il ouvrit les yeux ; mais il ne se reconnut pas
tout de suite : il se rendit compte seulement qu’il sentait la vase. Puis
il se rappela tout. Stop, assis sur son séant, le regardait : depuis qu’il
avait vu de trop près l’horrible grenouille, Berlâne le trouva
sympathique.
— Tu peux te vanter de nous avoir flanqué une de ces
frousses !… dit Robert. C’était pour rire ! Il fallait nous dire que tu
n’es qu’une poule mouillée.
Mouillé, Berlâne l’était en effet. De l’eau avait coulé sur le col de
sa chemise et sur sa blouse : Mme Dumas avait bien fait de ne point
lui donner sa plus neuve. Il prit son mouchoir et s’essuya. Il n’avait
pas encore prononcé une seule parole : il en aurait été incapable. Il
frissonnait.
Le soleil, qui se dégagea de derrière les nuages, descendait vers
l’horizon occidental. Les arbres, qui n’avaient pas encore perdu
toutes leurs feuilles, étaient si serrés les uns contre les autres qu’on
devinait plutôt qu’on ne les voyait les obliques rayons de lumière.
C’était l’heure mélancolique qui dans les petites villes et au-
dessus des champs va sonner l’arrêt du travail et de la vie. Comme
le laboureur qui écoute l’angélus lointain, on se recueille dans le
silence ; partout les bougies s’allument comme pour une veillée
funéraire, et c’est ainsi que chaque soir semble ramener la fin du
monde.
Il sembla soudain à Berlâne qu’une grande tristesse se répandît
par les bois désertés, planât au-dessus de l’étang abandonné, et lui
entrât dans l’âme. Auprès des deux Labrosse moqueurs ou hostiles,
il lui sembla qu’il fût à cette heure à une infinie distance de sa
maison. Ses larmes jaillirent.
— Voilà que tu pleures à présent ? dit Robert. C’est le bouquet !
Allons-nous-en, Georges. Il nous suivra s’il veut.
Si Berlâne avait été un enfant grincheux comme on en voit
beaucoup, qui se privent de nourriture pour punir leurs parents de
les avoir grondés, il serait resté là, tout seul, quitte à avoir peur, pour
se venger des Labrosse en les obligeant à revenir sur leurs pas pour
le supplier de les suivre. Il n’en fit rien. Il leur emboîta le pas ; Stop
était resté derrière ses maîtres pour servir, eût-on dit, de trait d’union
entre eux trois. Stop n’était pas méchant ; Berlâne osa lui passer la
main sur la tête et ne fut pas mordu.

— Eh bien, mes enfants, vous êtes-vous bien amusés ? leur


demanda Mme Labrosse. Mais vous êtes en retard : quatre heures et
demie viennent de sonner.
— Nous ne sommes pas payés à l’heure, riposta Robert qui
traitait avec sa mère de puissance à puissance. En tout cas, nous ne
nous sommes pas ennuyés, n’est-ce pas, Albert ?
— Non, dit Berlâne.
— Qu’est-ce que vous avez fait ? lui demanda Mlle Gertrude qui
disposait sur la table de la vaste cuisine — Berlâne n’était pas un
invité de marque, — des assiettes et des verres.
Il baissa tout de suite les yeux. Il essaya de répondre, mais en
vain, trop ému pour ne pas bégayer : il lui était encore plus difficile
d’adresser la parole à Mlle Gertrude que de réciter une leçon. Avec
ses yeux presque verts qui luisaient dans son visage fin sous ses
cheveux blonds, Mlle Gertrude ressemblait à une jeune fée qui vole
en rasant les herbes de la prairie, et son écharpe bleue flotte
derrière elle au gré du vent du matin ou de la brise du soir.
— Tu es malade, Albert ? lui demanda Mme Labrosse.
— C’est le grand air. Il n’y est pas habitué, répondit Georges à sa
place.
— C’est vrai qu’il ne sort pas souvent, réfléchit Mlle Gertrude.
Plus que dans le salon Berlâne était au supplice. On lui servit des
confitures de coings, qu’il n’aimait pas et qu’il dut manger tout de
même. Assis entre Mme Labrosse et Mlle Gertrude, il maniait
gauchement sa petite cuiller.
— Nous te faisons donc peur ? lui dit Mme Labrosse. Il ne faut pas
être si timide !
Son embarras redoubla. Mlle Gertrude le regardait en souriant, et
Dieu sait si elle avait l’air terrible ! Un doigt de vin pur le réconforta
un peu, sans qu’il reprît confiance en lui-même. Quand le goûter fut
terminé, il eut pourtant le courage de dire :
— Je vous remercie beaucoup, madame. Maintenant je vais
rentrer.
Robert et Georges se gardèrent d’insister pour qu’il restât : ils
avaient assez de lui.
Sa mère lui demanda comme Mme Labrosse :
— T’es-tu bien amusé ?
Elle ajouta :
— Mais tu as ton col de chemise tout sale !
Il n’avait jamais bonne mine : elle ne remarqua point sa pâleur.
— C’est que nous avons joué au bord de l’eau, répondit-il. Je ne
me suis pas ennuyé.
— Tant mieux ! dit Mme Dumas. Je suis contente. Cela te distrait,
et c’est meilleur pour toi que de toujours rester seul. Je remercierai
Monsieur Georges et je lui demanderai qu’il pense à toi, de temps en
temps, quand ça ne les dérangera pas.
VI

Ce fut le recommencement des misères qu’il endura plusieurs


années de suite ; malgré sa timidité, il était trop fier pour s’en
plaindre, même pour en parler à sa mère. Il avait eu la chance que
jusqu’alors les Labrosse n’eussent pas fait trop attention à lui ; on
peut vivre presque porte à porte et être les uns pour les autres
comme des étrangers. Or il avait suffi que cette idée de l’emmener
avec eux leur fût venue pour que sa vie menaçât de changer et de
lui devenir intolérable. Il ne s’en alarma pas outre mesure. Les deux
Labrosse n’en avaient point parlé à leur mère, mais ils eurent vite
raconté à l’école la scène du bois dans ses menus détails, et
Berlâne fut considéré comme un capon tel qu’il était impossible que
la terre en portât un semblable. Il eut beau se faire violence et
affecter de prendre part à tous les jeux les plus périlleux : à lui
étaient réservés les coups les plus secs des balles le plus durement
rembourrées de chiffons et de son, les positions les plus fatigantes
au jeu de saute-mouton, et l’hiver il redevint plus d’une fois une cible
vivante pour les amateurs de boules de neige. Il retenait des larmes
de dépit quand il entendait Robert crier, en le désignant aux plus
enragés :
— Sur Berlâne ! Sur Berlâne !
Il n’était plus l’Albert du jeudi d’octobre : il était redevenu Berlâne,
le pauvre gamin ridicule vers qui convergeaient moqueries, rires et
coups.
Les Labrosse se gardèrent bien de revenir l’inviter le jeudi : Mme
Dumas avait eu beau les remercier et leur faire comprendre que,
s’ils voulaient recommencer, elle en serait heureuse et fière. Il ne le
regretta point : il avait trop souffert dans le salon et au bois. Et
pourtant il lui semblait qu’à la longue, et surtout l’hiver, il aurait fini
par s’habituer à l’atmosphère de luxe de leur maison, et qu’à force
de regarder Mlle Gertrude il aurait cessé d’avoir peur d’elle : peut-
être même aurait-il pu avoir avec elle de longues conversations. Au
lieu de cela il ne l’apercevait guère que le dimanche, et jamais il
n’aurait osé lui adresser la parole. Mme Labrosse, pas fière, causait
un peu avec Mme Dumas qui lui répondait humblement. Mais il n’était
pas question de lui. Elle ne disait pas :
— Il faudra nous envoyer Albert.
Sans doute avait-il laissé à Mme Labrosse une mauvaise
impression.
Son refuge resta la boutique des Chovin. Les premières fois qu’il
y retourna, il ne put regarder Marie sans rougir : était-il possible
qu’elle fût sa bonne amie ! Par des bouts de conversations qu’il
saisissait à l’école, il devinait bien qu’une bonne amie c’est une
gamine, une jeune fille qu’on embrasse en cachette. Avec Marie,
jamais cette idée ne lui serait venue. Avec Mlle Gertrude encore bien
moins, mais pour des motifs tout différents. Elle était si jolie !
Mais en lui s’opérait une transformation que j’étais loin de
soupçonner.
VII

Peut-être sa mère y fut-elle pour quelque chose ? Je n’en sais


rien.
Mme Dumas ne faisait point partie du groupe des femmes
pieuses que l’on rencontrait plus souvent à l’église ou à la chapelle
des sœurs que chez elles. Les nécessités de la vie, surtout depuis la
mort de son mari, l’obligeaient à quitter le moins possible sa
boutique. Mais elle ne manquait pas de fermer sa porte, le
dimanche, pour assister à la messe et aux vêpres. En semaine elle
s’associait par la pensée à celles qui, plus libres, avaient le bonheur
de pouvoir réciter en commun le Rosaire devant la statue de Notre-
Dame de Lourdes et faire chaque vendredi l’exercice du chemin de
la croix.
De beaucoup de manières notre maison était en quelque sorte
une succursale de l’église.
Mon père étant sacristain, il ne se passait pour ainsi dire pas de
jour que soit le curé-doyen, soit le vicaire ne vinssent frapper à la
porte pour annoncer un baptême, un enterrement, un mariage ;
souvent ils s’arrêtaient, prenaient une chaise et restaient longtemps
à causer avec ma mère. C’étaient aussi des gens qui venaient, à
toute heure du jour, se renseigner sur les offices, quand par exemple
ils avaient entendu, la veille au soir, les cloches sonner un glas :
c’était un enterrement pour le lendemain matin, et il y avait de ce fait
une messe supprimée, soit celle du vicaire, soit celle du doyen.
Ma mère faisait partie du groupe des femmes pieuses à qui il ne
suffisait point d’assister le dimanche à la messe. Et ce n’étaient ni
les crucifix, ni les bénitiers, ni les images de sainteté qui manquaient
chez nous. Sur le manteau de notre cheminée il y avait deux
statuettes de la Vierge et de saint Joseph, et sur le coin d’une petite
table de nombreux livres de piété. Ma mère savait nettement
différencier le bien du mal. Elle n’ignorait point que ce fût un péché
de jurer par « sacristie ! » au lieu de « sapristi ! » Chaque année, des
voisines venaient se renseigner auprès d’elle sur la façon
d’accommoder les plats le Vendredi saint ; celles qui emploient le
beurre encourent la colère de Dieu. Elle savait qu’il est nécessaire
de réciter sa prière le matin en se levant et le soir avant de se
coucher ; qu’il ne faut pas se mettre à table sans faire le signe de la
croix, parce que c’est à Dieu, et à lui seul, que nous devons de nous
asseoir devant la nourriture : que chacun de nous est
continuellement guetté par le démon contre les attaques duquel le
protège son ange gardien. Elle parlait du ciel, du purgatoire et de
l’enfer comme de pays dont elle eût connu les moindres accidents,
et plus d’une fois je frissonnai à l’évocation terrible de Lucifer
siégeant, le trident à la main, dans des régions souterraines emplies
des lamentations et des cris de haine des damnés. Elle ne cessait
de me diriger dans la voie du bien. C’était mal de courir avec les
petites filles, mal d’assister aux bals publics et de regarder danser,
mal d’entrer dans l’église sans prendre de l’eau bénite, mal de dire
« le curé » au lieu de « Monsieur le curé », mal de prononcer de gros
mots comme faisaient les élèves de l’école communale, mal de trop
boire et de fumer, et après cela elle me reprochait de n’être pas
comme les autres !
Depuis un an j’étais enfant de chœur, et depuis six mois
j’apprenais le latin. Dans une petite ville personne n’ignore ce que
cela signifie : le latin est la langue de l’Église. Le moment venu je
partirais donc pour le séminaire. On ne m’avait pas demandé si cela
me convenait.
Or, quelques soirs après la Toussaint de cette même année, ma
mère me dit, comme nous nous mettions à manger la soupe :
— Mme Dumas est venue me voir tout à l’heure. Elle voudrait
qu’Albert soit enfant de chœur. Il paraît que c’est lui qui en a parlé le
premier. Elle dit qu’il fera tout son possible pour apprendre.
J’en fus étonné. Il n’y avait pas encore tout à fait un an qu’il était
sorti de l’école communale. Il était arrivé chez les frères avec la
certitude de sa supériorité sur nous qui étions officiellement des
enfants pieux puisque chaque matin nous récitions en commun la
prière. Il avait donc changé sans que je m’en fusse aperçu ? Cela
m’eût d’ailleurs été impossible, puisque je ne le fréquentais pas, tout
en m’abstenant de me moquer de lui : mes rires ne se seraient-ils
pas retournés contre moi ? Mais je ne pouvais admettre qu’il se
rapprochât de moi.
Je dis avec orgueil :
— Lui, apprendre les réponses de la messe ? Il est bien trop bête
pour ça !
Ma mère ne manqua point de me réprimander.
— Ce n’est qu’au bon Dieu, dit-elle, qu’on doit l’intelligence que
l’on a. Et il ne nous tiendra compte plus tard que de notre bonne
volonté et des efforts que nous aurons faits pour le bien servir.
Puisque Albert demande à être enfant de chœur sans que personne
lui en ait parlé, c’est qu’il a été touché par la grâce. Car ce n’est bien
sûr pas l’instituteur qui a pu lui mettre cette idée dans la tête. Avec
du travail on arrive à tout, et il apprendra à servir la messe aussi
bien que toi, et peut-être mieux, car tu ne te tiens guère bien.
Demain j’en dirai un mot à M. le curé.
En ce qui me concernait, elle avait raison. Moi qui n’ai jamais su
ce que c’était que la piété, je baignais de toutes parts dans une
atmosphère religieuse. Sans doute n’étais-je pas, à neuf ans ni à
quatorze, un précoce incrédule, et je n’aurais contesté l’existence de
Dieu, ni de ses saints, ni des anges, ni même du démon : mais il
m’était impossible d’avoir de ces élans affectueux qui vous font
tomber à genoux, les mains jointes devant le visage soudain inondé
de larmes. Sans trembler d’effroi je servais la messe, et, sans être
persuadé de la sublimité d’une vocation que je ne sentais pas,
j’apprenais le latin. Je n’en eus que plus de mépris pour Berlâne. Il
n’était pas intelligent : il ne lui manquait vraiment plus que de devenir
pieux.
Mais ce fut bien pis quand, quelques jours après, ma mère dit :
— Il paraît qu’Albert voudrait aussi apprendre le latin.
Elle rayonnait : c’était une vocation de plus — en comptant la
mienne, — dans le canton. C’était pour elle le dernier coup de la
grâce. Pour moi ce fut le coup de grâce. Ainsi, maintenant, j’allais
l’avoir toujours auprès de moi ? Nous étions une cinquantaine
d’élèves à l’école des frères. Il deviendrait peut-être bientôt, — dès
la première vacance, — un des six enfants de chœur. Et tout de
suite — car je ne doutais pas que « Monsieur le curé » n’acceptât, —
il allait être, avec moi, le seul qui apprît le latin ? Il allait s’attacher à
mes pas, comme mon ombre. D’un pied léger il s’engageait dans
cette voie où l’on m’avait poussé par les épaules. Quel imbécile,
décidément !
VIII

Nous prenions nos leçons dans la chambre qu’occupait au


presbytère l’abbé Bichelonne, le vicaire. Il avait l’accent auvergnat.
Là-bas surabondance, ici disette de vocations : le diocèse de
Clermont-Ferrand prêtait chaque année à celui de Nevers quelques
jeunes prêtres.
Berlâne faisait un petit détour pour me cueillir en passant : je suis
sûr qu’il n’aurait pas reculé devant une lieue. La première fois que
nous prîmes contact — il y avait juste un an qu’il était arrivé chez les
frères, — il me dit respectueusement :
— Je suis heureux de ce que maintenant nous nous allons être
ensemble.
Qu’est-ce qui me retint de lui répondre :
— Eh bien, moi, je ne le suis pas !
Fut-ce manque de cruauté ? Ou que, malgré moi, cette marque
de déférence me toucha ? Je n’en sais rien. Mais je gardai le
silence. Ma supériorité sur lui m’en donnait le droit. Il attendit,
comme l’année dernière dans la cour de l’école. Quoi ? Une bonne
parole, sans doute. J’évitai de le regarder. Sinon je n’aurais peut-être
pas pu m’empêcher de lui répondre :
— Moi aussi.
Mais je ne voulais à aucun prix qu’il se raccrochât à moi comme
un chien galeux que tout le monde repousse, ni qu’il s’imaginât, lui
dont personne n’acceptait la compagnie, que je pouvais être
heureux de le voir auprès de moi : j’avais envie de le renvoyer aux
Chovin et à leur boutique. Hélas ! La douceur et la misère m’ont
toujours ému. Et tout ce que je pouvais faire, c’était de ne pas
répondre.
Le jeudi, jour de la leçon de latin, je partais le plus souvent un
quart d’heure plus tôt, quitte à muser sous les sapins, autour de ce
petit arbre de la Liberté avec qui j’avais fait connaissance de plus
près, depuis l’époque, pas si éloignée pourtant, où j’allais à la salle
d’asile. Mes livres et mon cahier sous le bras, pour m’esquiver je
profitais d’un moment d’inattention de ma mère. Elle tenait à ce que
j’attendisse Berlâne. Elle avait cessé de voir en lui « l’original » qui
me ressemblait pour ne plus prendre garde qu’à ses qualités qui
n’étaient pas les miennes : l’obéissance et la piété.
Quand nous montions ensemble vers le presbytère, j’affectais de
ne pas entendre les questions qu’il me posait de sa voix la plus
douce. Je sifflotais comme un homme. Avec lui, seul à seul, j’avais
beau jeu à prendre des airs de matamore ! Pourtant, je l’ai bien vu
depuis et je m’en doutais alors, ce n’était comme moi qu’un pauvre
gamin qui eût été si heureux de rencontrer une vraie sympathie !
Mais je ne voulais pas de la sienne, pas plus que je n’aurais voulu
faire plaisir à ma mère en devenant tout à fait obéissant. S’il ne me
l’avait pas offerte, peut-être l’aurais-je recherché, qui sait ? Mais
non : nous nous ressemblions sur trop de points pour pouvoir nous
entendre. Certes, il n’aurait tenu qu’à moi que nous fussions amis :
seulement mon orgueil montait bonne garde.

J’avais plaisir à l’entendre bégayer et bafouiller, confondant les


cas des déclinaisons et les temps des conjugaisons. Ses premiers
thèmes fourmillèrent de barbarismes, ses premières versions de
contresens. A la fin des fins, l’abbé Bichelonne s’emportait et
Berlâne, tirant son mouchoir, s’essuyait les yeux. Je haussais les
épaules. S’il s’était évanoui, comme le jour de la grenouille, je crois
que je l’aurais giflé : peut-être cela l’eût-il fait revenir plus
promptement à lui. Moi aussi, plus d’une fois, j’avais pleuré dans
cette même chambre. Maintenant encore, maintenant surtout que
j’abordais le De viris et que je me dépêtrais tant mal que bien au
travers de textes tout exprès, me semblait-il, semés d’embûches, les
larmes souvent me venaient aux yeux : l’abbé Bichelonne était
prompt à se mettre en colère. Il ne comprenait point que l’on ne
comprît pas. Mais devant Berlâne je me tenais à quatre : pour rien
au monde je n’aurais voulu qu’il me vît pleurer.
Plus avancé que lui, j’aurais pu l’aider à faire ses devoirs et lui
éviter ainsi quelques observations. Je m’en gardais bien. Mais je
devins moi-même son professeur, ayant été chargé de lui apprendre
à servir la messe.
Il fallait qu’il sût par cœur tous les répons à l’officiant, depuis Ad
Deum qui laetificat juventutem meam, jusqu’au dernier Deo gratias.
De ses journées il ne perdait pas une minute.
Si ma mère avait de l’estime pour lui, Mme Dumas en avait pour
moi. Elle trouvait en moi telle qualité qui manquait à son pauvre
Albert. Elle me faisait des confidences comme à quelqu’un qui déjà
comprend tout.
— Le soir, me disait-elle, il faut que je le déshabille de force ;
autrement il ne se coucherait pas. Ainsi, croyez-vous !…
Parfois elle disait à ma mère :
— Ah ! Madame, si mon Albert ressemblait à votre fils !…
Mais elle, dédaigneuse :
— Ne vous plaignez donc pas, Madame Dumas. Chacun a les
facultés que le Bon Dieu lui a données. Et j’aimerais bien mieux le
voir obéissant et pieux comme Albert.
C’était dur pour lui. Il lui fallait penser non seulement à ses
leçons et à ses devoirs de latin et de l’école, mais aussi à ses
répons au milieu desquels il s’embrouillait. Dans le Confiteor, d’une
longueur invraisemblable pour lui, il perdait pied, faisant passer les
saints Pierre et Paul après le bienheureux Michel archange. Moi,
vieux routier, qui depuis un an avais servi plus de quatre cents

You might also like