Open Questions
- As
ConfigMaps are scoped in its namespace, how to haveConfigMaps in multiple namespaces without duplication?
- One option is using high level of abstraction such as
cdk8s
Networking
-
Container
Containercommunicates with anothercontainerin the samePodoverlocalhost.- As a
Podbehaves like a virtual host,containersbehave like applications,containersof the samePodcan't listen on the sameport. - By default,
containerscan use a port of thePodwithout explicitly specifying it, andpo.spec.containers.ports.containerPortis only documentation. Containercrashes and restarts doesn't changePod'sIP address.
-
Pod-
Each
Podhas its ownnetwork namespace(opens in a new tab), behaving as if a virtual host. -
A
Podgets assigned anIP address(ClusterIP) on creation and loses it on deletion. -
PodtoPodcommunication- Same cluster: use
cluster IPPodorService - Different cluster: use
Service
- Same cluster: use
-
-
Port
-
po.spec.containers.ports.containerPort- Informational purpose, specifying which
portof thePodthecontaineris using. - The port being unspecified does not stop it from being published by the container, e.g.
nginxuses port 80 on thePodno mattercontainerPort: 80is specified or not.
- Informational purpose, specifying which
-
po.spec.containers.ports.hostPort- Only bound on
nodesthat are actually running thePod
- Only bound on
-
svc.spec.ports.nodePort- Bound on all
nodes
- Bound on all
-
svc.spec.ports.port- The port of the
Service
- The port of the
-
svc.spec.ports.targetPort- Should match
po.spec.containers.ports.containerPort - If unspecified, the value of the
svc.spec.ports.portwill be used.
- Should match
-
-
Resources
Kubernetes Object Manifest
spec
What state you desire for the object
-
- Start with a
!to exclude a label, such askubectl get pods -l '!app'
- Start with a
-
initContainersInit containersare always executed before the main application containers, regardless of the definition order in the manifest.
-
spec.containers[].commandOverride the
ENTRYPOINTinstruction ofDockerfileof the container image -
spec.containers[].argsOverride the
CMDinstruction ofDockerfileof the container imageTwo forms of array can be used for
commandorargs.-
Array
Array form needs more typing as every argument has to be quoted, but therefore also supports special characters better.
args: ["wget", "-O", "-", "google.com"] -
List
- Some arguments of special characters or numbers must be quoted. Rule of thumb: if any argument doesn't contain letter, it needs to be quoted.
args: - wget - -O - "-" - google.com
-
Kubernetes Resource
Label
List resources with specific labels regardless of values
-
k get po -l environment,tier -
Equality-based requirement
kubectl get pods -l
environment=production,tier=frontend -
Set-based requirement
Must be single-quoted
kubectl get pods -l
'environment in (production),tier in (frontend)' -
Two forms can be used together
kubectl get pods -l
'environment in (production),tier in (frontend)',tier=frontend
Pod
-
Probe
-
Readiness Probe
- When the probe returns
Yes, thePodwill start receiving incoming traffic. - A
Podis consideredreadywhen all of its containers are ready. - When a
Podis notready, it is removed fromServiceload balancers.
- When the probe returns
-
Liveness Probe
- When the probe returns
No, thePodwill be restarted. - Configure
initialDelaySecondswhen using aliveness probe, as aliveness probefailure causes thePodto restart. You need to make sure the probe doesn’t start until the app is ready.
- When the probe returns
-
Startup Probe
- When the probe returns
Yes,ReadinessandLivenessprobes will be enabled. - Only executed
at startup - The
kubeletusesstartup probesto know when a container application has started. If such a probe is configured, it disableslivenessandreadinesschecks until it succeeds, making sure those probes don't interfere with the application startup.
- When the probe returns
-
-
Node affinity
Taintsapply tonodes, whileaffinityrules apply toPods.
ConfigMap
-
Usage
-
Environment variablesfor acontainer -
Add a file in read-only
volume, for the application to read -
Write code to run inside the
Podthat uses theKubernetes APIto read aConfigMap- You have to write code to read the
ConfigMapand its data. However, because you're using theKubernetes APIdirectly, your application can subscribe to get updates whenever theConfigMapchanges, and react when that happens. By accessing theKubernetes APIdirectly, this technique also lets you access aConfigMapin a differentnamespace.
- You have to write code to read the
-
-
Sources
-
Literal values, which are
key-value pairsas plain text--from-literal=<KEY>=<VALUE> -
A file that contains
key-value pairsand expects them to beenvironment variables--from-env-file=config.envNote: A running
Podmust be destroyed and recreated for the updatedenvironment variablesto take effects. -
A file with arbitrary contents
--from-file=config.txt -
A directory with one or many files
--from-file=<CONFIG_DIR>
-
Job
-
job.spec.activeDeadlineSecondsThe
activeDeadlineSecondsapplies to the duration of thejob, no matter how manyPodsare created.Once a
JobreachesactiveDeadlineSeconds, all of its runningPodsare terminated and theJobstatus will becometype: Failedwithreason: DeadlineExceeded. -
job.spec.backoffLimitSpecify the number of retries before considering a
Jobas failed.
CronJob
-
A
CronJobcreates aJobobject about once per execution time of its schedule. -
cj.spec.startingDeadlineSecondsThe grace period for how long can elapse after the scheduled time without being count as a missed job
Deployment
-
A
Deploymentensures a desired state is maintained at any given time. -
By default, a
Deploymentis created with a labelapp=<DEPLOYMENT_NAME>. -
spec.selector.matchLabelsmust be the same asspec.template.metadata.labels. -
Strategies
-
RecreateAll existing
Podsare killed before new ones are created. Successful removal is awaited before anyPodof the new revision is created.+More economical-Downtime
-
RollingUpdate+No downtime-More instances, more costs
-
PersistentVolume
-
spec.capacity -
spec.accessModesReadWriteOnceReadOnlyManyReadWriteMany
-
StorageClassNameMust match that of the intended
PersistentVolumeClaim
PersistentVolumeClaim
Podsneed to claim aPVby usingPVC, which states the storage requirements but not the volume implementation.- The binding to an appropriate
PersistentVolumehappens automatically based on the criteria defined inPersistentVolumeClaimmanifest. PersistentVolumeClaimserves as the middle layer to decouplePods andPersistentVolumes
ReplicaSet
-
A
ReplicaSetensures that a specified number ofpodreplicas are running at any given time. -
Deploymentis preferred overReplicaSet. -
Use
kubectl scalecommand to manually scale up and down replicas
ResourceQuota
-
Resource Unit
OneCPU is equal to1000 millicores.- Memory is measured in
bytes. - Kubernetes accepts both
SInotation andBinarynotation for memory definition.SInotation (K,M,G,T,P,E)Binarynotation (Ki,Mi,Gi,Ti,Pi,Ei)
-
If a
Podrequests moreCPUorMemorythan any node has, it will never be scheduled. -
A container using more CPU than allowed will not be killed but throttled.
-
A container using more memory than allowed may be restarted or evicted.
-
Type
Secret
-
Create a Secret
Secret value must be in plain text, kubernetes will encode it with base64.
-
Create a Secret from literal(s)
-
value: unencoded plain text
-
k create secret generic --from-literal=key=value
-
-
Create a Secret from file(s)
-
key: file name (including extension), can be overridden by explict key
-
value: file content (unencoded plain text)
-
k create secret generic --from-file=file-name
-
-
Create a Secret from file(s)
-
Similar to creation from files, and all files under the specified directory will be used for creation.
-
k create secret generic --from-file=dir-name
-
-
-
Get the contents of a
Secretk get secret <secret_name> -o jsonpath='{.data}' | jq -
Get the
base64encoded token:kubectl get secret <secret_name> -o yaml -
Get the
base64decoded token:-
kubectl get secret <secret_name> -o yaml -
Copy & paste the encoded secret string
-
Use
base64 -dto decode the secret
-
Ingress
-
Resources
-
IngressClass- Usually installed as part of
Ingress controllerinstallation, used to register the associatedIngress controllerinto the cluster. - Global resource
- Usually installed as part of
-
IngressIngressresources define routing rules and config. Will only take effect ifIngress controlleris already deployed)Namespaced, and must reside in the namespace where the app that they configure reside.- The IP of an
Ingress(ing.status.loadBalancer.ingress.ip) is the external IP of the load balancer, therefore the entrypoint. - When multiple
IngressClassexist or no defaultIngressClassspecified,Ingressmust explicitly choose anIngressClasswithing.spec.ingressClassName. ing.spec.rules.host[]specify theFQDNexpression which requests are matched against.
-
-
Ingress controlleris essentially a separatePod/Deploymentalong with aServicethat implementsIngressfunctionality behind the scene such as routing and proxying. -
Ingressis able to expose low-numbered ports.Serviceshave been hard-coded not to expose ports lower than 1024. -
Conflicting
Ingress ruleswill causeIngressresource not getting IP address. -
If
Ingressresource has noIngressClass, specify one by usinging.spec.ingressClassName. AvailableIngressClasscan be retrieved withk get ingressclass.
Service
-
A
Serviceis an abstraction layer which defines a logical set ofPodsand enables external traffic exposure, load balancing and service discovery for thosePods. -
Type
-
ClusterIPExposes the
Serviceon a cluster-internalIP. Choosing this value makes theServiceonly reachable from within the cluster. This is the default value.ServiceoptionclusterIP: Nonelets theServiceDNSname resolve directly to thePod'sIPaddress. This is optimal when you have only onePodbehind aServiceand you don't intend to increase the number ofPods. -
NodePortA
Serviceof the typeNodePortincludes the functionality of the typeClusterIP. Traffic is routed from theNodePortto theClusterIP. Only high ports can be used.-
Obtain Node IP
minikube:minikube ip
-
-
LoadBalancerA
Serviceof the typeLoadBalancerincludes the functionality of the typeNodePort.Exposes the
Serviceexternally using a cloud provider's load balancer.NodePortandClusterIPServices, to which the external load balancer routes, are automatically created. -
ExternalNameA special type of service without selectors, is used to point to an external
DNSserver.Use of the service returns a
CNAMErecord.
-
-
Selector
- Select any
Pods having the specifiedLabels(intersection)
- Select any
-
-
ServicesinKubernetesexpose their endpoint using a commonDNSpattern:<Service Name>.<Namespace Name>.svc.cluster.local -
Normally, the
Servicename is adequate. If you need to access aServicein anotherNamespacejust use theServicename plus theNamespacename. -
Servicename must beDNScompliant, which is lower case alphanumeric characters or-, start with an alphabetic character, and end with an alphanumeric character.
-
-
Expose a
Servicefor aResoruce-
Use
kubectl exposecommand, with following flags:--name: aDNScompliant name--type: the type ofService, if not explicitly set,ClusterIPwould be used.--port: theServiceport--target-port: target port on containers
Note: the
Resourcebeing exposed must already exist -
Use
kubectl create service <service_name> <service_type>command, with following flags:--tcp=<port>:<targetPort>: theServiceport and target port on containers
and edit the manifest or
Resource:spec.selectormust be the same asDeployment'sspec.selector.matchLabels
-
-
Resources
EndPoint
- An
EndPointis created whenselectorof aServicefinds matchingPods, and noEndPointwill be created if no matchingPodexists. - An
EndPointIP address is aPodIP address, meaning traffic will be directed byServiceto thisPod. ServicecontrolsEndpoint. If anEndPointis deleted, a new one will be created byService. If aServiceis deleted, the correspondingEndPointwill be deleted too.- Use
EndPointto check if theServicehas found any matchingPodto serve traffic.
NetworkPolicy
-
Must install a Network Policy provider (opens in a new tab) first for
NetworkPolicyto work -
You can only write rules that allow traffic.
spec: podSelector: {} # empty selector selects all Pods ingress: [] # empty array indicates nothing is whitelisted -
NetworkPolicyare scoped to thenamespacethey are deployed to, sonetworkpolicy.spec.podSelectordoes not selectPodsfrom othernamespaces. -
By default,
Podsare non-isolated; they accept traffic from any source.Podsbecome isolated by having aNetworkPolicythat selects them. Once there is anyNetworkPolicyin aNamespaceselecting a particularPod, thatPodwill reject any connections that are not allowed by anyNetworkPolicy. OtherPodsin thenamespacethat are not selected by anyNetworkPolicywill continue to accept all traffic. -
Network policiesdo not conflict; they are additive. If any policy or policies select aPod, thePodis restricted to what is allowed by the union of those policies' ingress/egress rules. Thus, order of evaluation does not affect the policy result.
ClusterRole & ClusterRoleBinding
- Both
ClusterRoleandClusterRoleBindingare global, not scoped to anamespace ClusterRolevia aRoleBindingis also confined to itsnamespace.ClusterRoleBindingcan not referenceRoles.ClusterRolecan define common permissions expressed in a singlenamespacewhen referenced by aRoleBinding. This removes the need to have duplicatedRoles in manynamespaces.
Role & RoleBinding
-
The permissions can only be given to the resources that are in the same
namespaceas theRoleand theRoleBinding. -
A
RoleBindingcan only reference aRolein the samenamespace. -
But
subjectsof aRolecan be from a differentnamespace. -
User Impersonation
kubectl <verb> <resource> --as=<user/serviceaccount> -
Verify API Access
kubectl auth can-i <verb> <resource> --as=<user/serviceaccount>
ServiceAccount
-
If not assigned explicitly, a
Poduses the defaultService Account. The defaultService Accounthas the same permissions as anunauthenticated user. This means that thePodcannot view or modify the cluster state nor list or modify any of its resources. -
Specify a custom
Service Accountwhen running aPodkubectl run nginx --image=nginx --serviceaccount=custom -
The authentication token of
Service Accountwith which aPodis run can be found at the path/var/run/secrets/kubernetes.io/serviceaccountin the containers. -
--asglobal option--as=system:serviceaccount:{namespace}:{service-account-name}
StatefulSet
Node
Taint
kubectl
-
kubeconfig(opens in a new tab)- A file that is used to configure access to
clustersis called akubeconfigfile. This is a generic way of referring to configuration files. It does not mean that there is a file namedkubeconfig. kubectlcommand-line tool useskubeconfigfiles to find the information it needs to choose a cluster and communicate with theAPIserver of acluster.- Each
contexthas three parameters:cluster,namespace, anduser. - By default, the
kubectlcommand-line tool uses parameters from thecurrent contextto communicate with thecluster.
- A file that is used to configure access to
-
kubectl [command] [TYPE] [NAME] [flags]-
command-
create- Not every
RESOURCEtype is supported to be created from command line. Use-hto check supportedRESOURCE.
- Not every
-
-
TYPETYPEis case-insensitive and can be abbreviated, e.g. Pod:po. Usekubectl api-resourcesfor full list of abbreviations.
-
-o wideDisplay extra columns in output, such as
IP,NODE,SELECTOR,IMAGES, etc.
-
-
Use cases
-
Pod-
Create and
run(opens in a new tab) aPodUsing
runcommand to create aPodwill assign thePoda labelrun=<POD_NAME>.-
Options
-
--labelsA comma-separated list of labels to apply to the
Pod, eg:--labels="app=hazelcast,env=prod" -
--portThe port to expose on the container, equivalent to
$.spec.containers[0].ports[0].containerPortin object -
--env-
Specify environment variables of the container
e.g.
--env="DNS_DOMAIN=cluster". -
To specify multiple environment variables use multiple
--envoptionse.g.
--env="DNS_DOMAIN=cluster"--env="POD_NAMESPACE=default"
-
-
--command -- <COMMAND> <arg1> ... <argN>Start the
Podusing a different commandIf
--commandis present, the first argument follow--will becomecommandin manifest, and the remaining arguments will becomeargs.If
--commandis absent, the following arguments will become the array ofargs. -
--rmIf true, delete resources created in this command for attached containers.
Use this option to run a temporary one-off
Pod -
--restart=NeverBy default,
--restart=Always, setting it toNeverwill prevent aPodfrom restarting.
-
-
-
-
-
JSONPath Support
- Use
double quotesto quote text insideJSONPathexpressions. - Use the
range,endoperators to iterate lists. - Use
negative slice indicesto step backwards through a list. Negative indices do not "wrap around" a list and are valid as long as-index + listLength >= 0. - The
$operator is optional since the expression always starts from the root object by default. - The result object is printed as its
String()function. - JSONPath regular expressions are not supported.
e.g.
-
-ojsonpath='
{range .items[*]}{.metadata.name}{","}{.spec.containers[0].image}{"\n"}{end}'rangeandenddefines a loop to iterate all eligible items. -
-ojsonpath='{range .items[*]}
{.metadata.name}{","}{.spec.containers[0].image}{"\n"}{end}'Use a JSONPath expression to specify an object field
-
-ojsonpath='{range .items[*]}{.metadata.name}
{","}{.spec.containers[0].image}{"\n"}{end}'Use any string as delimiter. Also, use line separator at the end of line. String must be double quoted.
- Use
-
Resources
kubectl - Cheatsheet
Display the current context
k config current-context
or
kccc
Switch context
Set the current-context to CONTEXT_NAME in a kubeconfig file
k config use[-context] <CONTEXT_NAME>
or
kcuc <CONTEXT_NAME>
Describe one or many contexts
k config get-contexts
or
kcgc
Show merged kubeconfig settings
kubectl config view
Get Kubernetes cluster information
kubectl cluster-info
List all available Resource types
kubectl api-resources
List every instance of every Resource type in a specified Namespace
kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found -n <NAMESPACE>
List all namespaces
kubectl get ns
# or
kgnsList resources filtered by the specified namespace
kubectl get <...RESOURCE> -n <NAMESPACE>
List resources across all namespaces
kubectl get $RESOURCE_TYPE1, $RESOURCE_TYPE2, ... -ACreate a namespace
kubectl create ns $NAMESPACEChange current namespace
k config set-context --current --namespace=$NAMESPACEChange current namespace of a specified context
kubectl config set-context <CONTEXT_NAME> --namespace=<NAMESPACE>
Delete a namespace
kubectl delete $NAMESPACENote: deleting a namespace also deletes all resources in it.
List resources filtered by the specified Label
-
kubectl get all -l <KEY1>=<VALUE1>[,<KEY2>=<VALUE2>]kubectl get all -l '<KEY> in (<VALUE1>, <VALUE2>...)'
List Resources with their Labels
kubectl get all --show-labels
List Resources with specified Labels as additional columns
kubectl get all -L <LABEL_KEY_1>[,<LABEL_KEY_2>...]
Pretty print all Labels of a specified Resource
kubectl get <TYPE> <RESOURCE> -o jsonpath='{.items[*].metadata.labels}' | jq
Update existing Label
kubectl label <TYPE> <RESOURCE> <KEY1=VALUE1...> --overwrite
Remove existing Label
kubectl label <TYPE> <RESOURCE> <KEY_1>-
List resources
-
kubectl get <...RESOURCES>e.g.
kubectl get <..po,svc|all>
Get specified resource details
kubectl describe <RESOURCE_TYPE> <RESOURCE_NAME_PREFIX>
Get documentation for a field in manifest
-
kubectl explain <RESOURCE>[.<FIELD>]...-
e.g.
kubectl explain po.spec.containers.volumeMounts.mountPath -
e.g.
kubectl explain po.spec.containers.envFrom.configMapRef | grep -P '\s+<.+>'Print all fields of the specified field.
-
e.g.
kubectl explain po.spec --recursive | vim -R -Print all fields of the specified field recursively, and open with
vimfor easier navigation, which should be used as the main manifest reference method.
-
Print Events of all Resources in the current Namespace
kubectl get ev
Update Kubernetes object
-
Use
kubectl editdirectly update resourcesSet up
KUBE_EDITORbefore using the command.In the event of an error, the changes would be lost.
-
Edit and save local
manifest, then usekubectl apply -f <manifest>Less directly, but the changes are saved first.
-
Use
kubectl patch -
kubectl replace --force -f <filename>Delete and recreate the
Resourcespecified in the manifest
Update annotations
-
kubectl annotate <TYPE> <RESOURCE...> <KEY1>=<VALUE1>...e.g.
kubectl annotate po pod-1 pod-2 env=dev
Update labels
-
kubectl label <TYPE> <RESOURCE...> <KEY1>=<VALUE1>...e.g.
kubectl label po pod-1 pod-2 env=dev
Apply all manifests in a directory recursively
kubectl apply -R -f <directory>
List all Pods in the current namespace
kubectl get po
Get a running Pod's manifest
-
kubectl get po <POD> -o yamlNote:
-o yamlcan also be-oyaml.
Use JSONPath expression to extract information
kubectl get po <POD> -o jsonpath='{<JSONPATH_EXPRESSION>}'
Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied
kubectl diff -f <manifest>
Print the API objects into manifest file with dry run
kubectl run <POD> --image=<IMAGE:TAG> -o yaml --dry-run=client > pod.yaml
Execute a command in the container
-
Options
-
-cSpecify the
containername to run the command in the case ofmulti-containers
-
Get logs from a Pod
-
Options
-
--all-containers=trueGet logs from all
containersin thePod -
-cSpecify a
containername that you want to retrievelogsfromThis can be omitted by directly appending container name:
kubectl logs <POD_NAME> <CONTAINER_NAME> -
-fSpecify if the
logsshould be streamed
-
Delete a Pod
-
Options
-
--force, false by defaultForce delete a
Pod
-
Run a command one-off
kubectl exec <POD> -- <COMMAND> <...args>
Open a shell interactively to a running Pod
kubectl exec <POD> -it -- <SHELL>
Attach to a running Pod's main process
-
kubectl attach <POD> -it [-c <CONTAINER>]When exiting, the
Podcould be completed and restarted.
Copy a file out of a Pod
Path in Pod cannot have leading slash.
-
kubectl cp <POD>:<SRC_PATH> <TARGET_PATH>e.g.
kubectl cp b3:etc/passwd ./passwd
Forward a port on a Pod to a port on localhost
kubectl port-forward <RESOURCE_NAME> <LOCALHOST_PORT>:<SERVICE_PORT/POD_PORT>
List revisions
kubectl rollout history deployment <DEPLOYMENT_NAME>
Roll back to a previous revision
kubectl rollout undo deployment <DEPLOYMENT_NAME> --to-revision=<REVISION_NUMBER>
Create a Service when running a Pod
-
kubectl run nginx --image=nginx --restart=Never --port=80 --exposeNote the
--exposeoption
Expose a Service for a specified Resource
kubectl expose <RESOURCE_TYPE> <RESOURCE_NAME> --type=LoadBalancer --port 80 --target-port 8080
Configure application resources
-
kubectl set <SUBCOMMAND>Append the
--recordflag to save thekubectlcommand that is making changes to the resource, because imperative commands do not keep changes.
Update environment variables of a Resource
-
kubectl set env <RESOURCE_TYPE> <RESOURCE_NAME> KEY1=VALUE1 [KEY2=VALUE2] ...You cannot change environment variables of a
Pod, but you can change that of aDeployment.
List all environment variables across all instances of a Resource type
-
kubectl set env <RESOURCE_TYPE> --all --listIf you want to inspect a specific instance, replace
--allwithResourcename.
Update image of a Resource
kubectl set image <POD/RC/DEPLOY/RS/DS> <Resource_name> <container_name>=<image>:<tag>
Observability
-
Test connectivity from inside of a container
kubectl run t --image=busybox -it --rm --restart=Never -- wget -O - <IP:PORT>
Production
-
Challenges
- Integration with cloud or on-premises infrastructure
- Management across teams, learning curve
Administration
-
Metrics
-
Metrics Server (opens in a new tab)
-
Enable
Metrics ServerforDocker DesktopInsert
–kubelet-insecure-tlsinto the existingargssectionargs: - --kubelet-insecure-tls -
Query the
Metrics APIkubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes/<NODE_NAME> | jqkubectl get --raw /apis/metrics.k8s.io/v1beta1/namespaces/<NAMESPACE>/pods/<POD_NAME> | jq -
View metrics snapshot
kubectl top node
-
-
Web UI (Dashboard) (opens in a new tab)
- Run:
kubectl proxy(The command does not return) - URL: http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/ (opens in a new tab)
- Run:
-
Resources
-
Kompose
-
Translate Docker Compose to Kubernetes resources
Kustomize
-
Generate
kuztomizedmanifestYAMLfilekustomize build <directory containing kustomization.yaml> -
Directly apply resource config
kustomize build <directory containing kustomization.yaml> | kubectl apply -f -Using
kustomizeCLI is preferred tokubectl -k, askustomizeis more up-to-date. -
Resources
Helm
-
Resources
-
Artifact Hub - Find, install and publish Kubernetes packages (opens in a new tab)
# Search via CLI helm search hub $keyword
-
Pros
- The grouping of related Kubernetes manifests in a single entity (the chart)
- Basic templating and value support for Kubernetes manifests
- Dependency declaration between applications (chart of charts)
- A registry of available applications to be deployed (Helm repository)
- A view of a Kubernetes cluster in the application/chart level
- Management of installation/upgrades of charts as a whole
- Built-in rollback of a chart to a previous version without running a CI/CD pipeline again
Helm - Add a Helm chart repository
helm repo add $REPO_NAME $REPO_URLHelm - Get the list of installed chart repositories
helm repo listHelm - Search for charts in a repository
helm search repo $REPO_NAME $keywordHelm - Install a chart
helm install $RELEASE_NAME $CHART_NAMEHelm - List releases in all namespaces
helm ls -AHelm - Show release status
The status consists of:
- last deployment time
- k8s namespace in which the release lives
- state of the release (can be: unknown, deployed, uninstalled, superseded, failed, uninstalling, pending-install, pending-upgrade or pending-rollback)
- revision of the release
- description of the release (can be completion message or error message)
- list of resources that this release consists of
- details on last test suite run, if applicable
- additional notes provided by the chart
helm status $RELEASE_NAME -n $NAMESPACEHelm - Get resource YAML of a release
helm get all $RELEASE_NAME -n $NAMESPACEHelm - Upgrade a chart
helm upgrade $RELEASE_NAME $CHART_NAME -n $NAMESPACEHelm - Uninstall a chart
This removes all the Kubernetes resources associated with the chart and deletes the release, except for the CRDs, those will have to be removed manually.
helm uninstall $RELEASE_NAME -n $NAMESPACEHelm - Download a chart archive without installing it
helm pull $CHART_NAME -d $CHART_DIRSkaffold
-
Deploy
-
Kubectl- By default,
k8s/*.yamlare loaded for deployment.
- By default,
-
-
Build
-
Image pruning
skaffold dev --no-prune=false --cache-artifacts=false- Remove image at the end every time
- Force the build of image
-
-
Resources
minikube
-
Limitations
- The
ingress, andingress-dnsaddons are currently only supported onLinux.
- The
-
Troubleshooting
-
Sometimes newer versions of Kubernetes might not work, so in those use an earlier version might just work.
minikube start --kubernetes-version=1.24.8Explicitly specify the Kubernetes version
-
-
Resources
Access a LoadBalancer Service in minikube cluster from host
-
Run
minikube tunnel, and the terminal must stay open.This will open connection to
LoadBalancerservices. -
Update the
Servicetype toLoadBalancerif not. -
Run
kubectl get svc <service_name>, and use theEXTERNAL-IPto access the service from host.
Getting the IP of minikube node
minikube ip
Access Kubernetes Dashboard
minikube dashboard
Mount host path to the minikube node
minikube mount <source directory>:<target directory>
Access host from within minikube
- Use domain name
host.minikube.internal
Network Policy Provider
- Calico:
minikube start --network-plugin=cni --cni=calico
Shell completion
minikube completion <SHELL>
Switch to minikube's Docker daemon
eval $(minikube -p minikube docker-env)
Switch back to host Docker daemon
eval $(minikube -p minikube docker-env -u)
Push an image to minikube's Docker daemon
-
minikube image load <image>:<tag> [--daemon]This avoid the need to download images again.
minikube's Docker daemon
-
minikuberuns its own instance ofDockerdaemon process.Use
ps -fww -p $(pidof dockerd)to check. Whileminikuberunning, there should be 2dockerdprocess, one ofminikube, the other ofDocker engine. -
Containers started by minikube Docker Daemon can be access from minikube host IP ( Can be retrieved by
minikube ip)e.g.
d run --name=jenkins -p 8080:8080 -d jenkins/jenkins:lts-jdk17` curl -I http://$(minikube ip):8080
krew
Certifications
CKAD
-
Outline (2021 (opens in a new tab))
-
Application Design and Build – 20%
- Define, build and modify container images
- Understand Jobs and CronJobs
- Understand multi-container Pod design patterns (e.g. sidecar, init and others)
- Utilize persistent and ephemeral volumes
-
Application Environment, Configuration and Security – 25%
- Discover and use resources that extend Kubernetes (CRD)
- Understand authentication, authorization and admission control
- Understanding and defining resource requirements, limits and quotas
- Understand ConfigMaps
- Create & consume Secrets
- Understand ServiceAccounts
- Understand SecurityContexts
-
Application Deployment – 20%
- Use Kubernetes primitives to implement common deployment strategies (e.g. blue/green or canary)
- Understand Deployments and how to perform rolling updates
- Use the Helm package manager to deploy existing packages
-
Services and Networking – 20%
- Demonstrate basic understanding of NetworkPolicies
- Provide and troubleshoot access to applications via services
- Use Ingress rules to expose applications
-
Application Observability and Maintenance – 15%
- Understand API deprecations
- Implement probes and health checks
- Use provided tools to monitor Kubernetes applications
- Utilize container logs
- Debugging in Kubernetes
-
-
Shell setup
-
.bashrcalias k=kubectlalias kg='k get'alias kga='kg all'alias kgp='kg po'alias kaf='k apply -f'alias kex='k explain'alias ke='k exec'alias kc='k create'alias kr='k run'alias kd='k describe'alias kl='k logs'alias kdel='k delete'alias kpf='k port-forward'source <(kubectl completion bash)complete -F __start_kubectl kexport EDITOR=vimexport KUBE_EDITOR=vimexport do="--dry-run=client -oyaml"alias v=vim
-
.vimrcse etse ts=2se shiftwidth=2se nopastese isse hls
-
Patterns
Multi-container Pods
-
Init container
po.spec.initContainersdefines init containers -
Adapter
-
Sidecar
-
Ambassador (opens in a new tab)
- As a proxy, responsible for splitting reads & writes, and sending them on to the appropriate servers
- Application just needs to open a connection on
localhostand find the proxy without any service discovery. - Commonly used with databases
Resources
-
Official
-
Kubernetes.io - Overview of kubectl (opens in a new tab)
- Abbreviated aliases
-
Kubernetes.io - Kubernetes API Reference (opens in a new tab)
KubernetesObjectmanifest reference- Alternative is using
kubectl explaincommand
-
Guides and API References for Kubectl and Kustomize (opens in a new tab)
-
Spring
-
IBM Developer
-
Google Cloud - Your guide to Kubernetes best practices (opens in a new tab)
-
9 Best Practices and Examples for Working with Kubernetes Labels (opens in a new tab)
-
GitHub - ramitsurana/awesome-kubernetes (opens in a new tab)
A curated list for awesome kubernetes sources