Professional Documents
Culture Documents
Dzone Refcard 292 Advanced Kubernetes 2022
Dzone Refcard 292 Advanced Kubernetes 2022
Dzone Refcard 292 Advanced Kubernetes 2022
CONTENTS
• About Kubernetes
• Kubernetes Basics
• Constructs
• Kubectl
• Manage Nodes
• Test Plan
• Troubleshoot
• Etcd
• Security Checklist
DEEPAK GOEL
• Additional Resources
CTO, D2IQ
https://kubernetes.io/docs/concepts/overview/components/
SCHEDULER
Kubernetes relies on a sophisticated algorithm to schedule Kubernetes
objects. The scheduling takes into account attributes from a given work-
load (e.g., resource requirements) and applies custom prioritization
settings (e.g., affinity rules) to provision pods on particular Kubernetes
worker nodes.
https://kubernetes.io/docs/concepts/scheduling-eviction/kube-
CONTROL PLANE, NODES, AND PERSISTENT
scheduler/
STORAGE
Kubernetes’ basic architecture requires a number of components.
KUBE-PROXY
Each Kubernetes cluster worker node has a network proxy for
API SERVER
connectivity to application services in the cluster. The proxy reflects
The Kubernetes API server handles all requests coming into the
the services defined in the cluster and enables simple stream and
cluster. Users, as well as other Kubernetes components, send events
round-robin forwarding to a set of backends, regardless of which node
to the Kubernetes API Server through HTTPS (port 443). The API Server
they reside in the cluster.
then processes events and updates the Kubernetes persistent data
store, usually etcd. The API Server also performs authentication and https://kubernetes.io/docs/concepts/overview/components/#kube-
authorization depending on how the cluster was configured. proxy
Kubernetes uses a control plane with several types of controllers or SRV records for discernable access by clients or other Services in
to perform non-terminating control loops that observe the state of the cluster.
Kubernetes objects and reconcile it with the desired state. This includes
KUBECTL
a wide variety of functions such as invoking pod admission controllers,
The official command line for Kubernetes is called kubectl. All industry-
setting pod defaults, or injecting sidecar containers into pods, all
standard Kubernetes commands start with kubectl.
according to the configuration of the cluster.
https://kubernetes.io/docs/concepts/architecture/controller/
WEB UI (DASHBOARD)
ReplicaSet • A construct (ordinarily created by a
Kubernetes has an official GUI called Dashboard. That GUI is distinct Deployment object) that ensures the desired
from vendor GUIs that have been designed for specific Kubernetes number of copies (or replicas) of a pod that
share a particular container image(s) are
derivative products. Note that the Kubernetes Dashboard release
running.
version does not necessarily match the Kubernetes release version.
• Replicas may be used in the background
when performing rollouts on a new
CONSTRUCTS deployment.
Kubernetes has a number of constructs for defining and managing
objects on the cluster: Services • Enable a consistent mechanism to access
applications inside a cluster by providing
a logical layer that assigns IP/DNS/etc.
CONSTRUCT DESCRIPTION
persistence to apps.
Namespaces • Kubernetes includes a means to segment a
single physical cluster into separate logical Ingress and Load • Ingress exposes HTTP and HTTPS routes
clusters using namespacing. Balancing from outside the cluster to services within
the cluster.
• Can be used to isolate users, teams, or
applications and set quotas among other • Load balancers ensure traffic is routed to
functions. multiple instances of the service running on
the cluster to avoid a single point of failure of
Pods • Encapsulate one or more tightly bound the service.
containers, the resources required to run
these containers, and a network namespace. Roles • Sets of permissions that can be assigned to
users or service accounts of a cluster.
• Always scheduled on a single node,
regardless of the number of containers that • Contain rules that specify which API set,
are run as part of that pod. object, and verbs are permitted for an
account that's assigned a particular role.
Deployments • Construct that provides capabilities for
managing to the desired state of an app,
allowing higher availability and dynamic EXTENSIONS
scaling of workloads.
Kubernetes has a number of points to extend its core functionality:
• Include container deployment, placement,
scaling, image updates, rollout, and rollback CONSTRUCT DESCRIPTION
of a workload.
Custom Resource • Allows users to extend Kubernetes with
StatefulSets • A Kubernetes controller for managing Definition (CRD) custom APIs for different objects beyond the
workloads that require additional standard ones supported by Kubernetes.
management of state due to application
requirements. Container • A plugin API that enables Kubernetes to
• Pods managed by a StatefulSet have a Runtime Interface support other container runtimes beyond
consistent naming convention and manner (CRI) Docker and Containerd.
of connecting to persistent storage that
might be required for some applications, Container • Gives users a choice of network overlay
particularly legacy apps or databases. Network Interface that can be used with Kubernetes to add
(CNI) networking features.
DaemonSet • Enables users to run a pod on all nodes in the • A networking plugin is required to run
cluster. Kubernetes (e.g., Calico, Flannel, Canal, and
• Ordinarily used by Kubernetes plugins or other more niche/specific plugins).
administrative addons that require code to
be executed throughout the cluster (e.g., log Container Storage • Empowers users to support different storage
aggregation, networking features). Interface (CSI) systems through a driver model.
Setting a Bash prompt to mirror Kubernetes context: $ kubectl apply -f Perform a rolling update (where v2 is the
frontend-v2.json next version of the service, provided its
prompt_set() { object names are identical to the existing
if [ "$KUBECONFIG" != "" ]; then ones running in the cluster)
PROMPT_KUBECONTEXT="k8s:$(kubectl config current-
$ kubectl label Add label GPU; set value to true to the
context 2>/dev/null)\n"
pods foo GPU=true pods named foo
fi
PS1="${PROMPT_KUBECONTEXT}[\u@\h \W]\$ " If the label GPU already exists on the pod
foo, the command will fail unless you add
}
the flag --overwrite
k8s:admin@local
$ kubectl delete Delete foo pods from cluster
[kensey@sleeper-service ~]$
pod foo
COMMANDS $ kubectl delete Delete the service called foo from cluster
svc foo
CONSTRUCT DESCRIPTION $ kubectl create Create a clusterIP for a service named foo
service clusterip
$ kubectl version Print the client and server version infor- foo
mation
$ kubectl autoscale Autoscale pod foo with a minimum of 2
$ kubectl cluster- IP addresses of master and services deployment foo and maximum of 10 replicas when CPU
info --min=2 --max=10 utilization is equal to or greater than 70
--cpu-percent=70 percent
$ kubectl get List all the namespaces in the Kubernetes
namespaces cluster
MANAGE NODES
$ kubectl cordon Mark node as unschedulable; used for clus- Sometimes it's necessary to perform maintenance on underlying
NODE ter maintenance nodes. In those cases, it's important to use eviction and ensure the
application owners have set a pod disruption budget.
$ kubectl uncordon Mark node as available for scheduling; used
NODE after maintenance
To properly evict running pods from a node that requires maintenance,
$ kubectl drain Remove pods from node via graceful use:
NODE termination for maintenance 1. Cordon node: $ kubectl cordon $NODENAME
3. Uncordon node: $ kubectl uncordon $NODENAME The Kubernetes command line kubectl provides many of the resources
needed to debug clusters.
TEST PLAN
CHECK PERMISSIONS
It's important to devise a test plan and a run book to ensure any new
TROUBLESHOOTING COMMAND EXAMPLE
clusters meet operational guidelines. This enables standard operating
procedures (SOPs) that address needs such as consistency or compliance, Check permissions $ kubectl auth $ kubectl auth
facilitating better operational metrics for uptime and availability. can-i can-i create
deployments
--namespace dev
Below are samples from D2iQ's Kubernetes test plan, which is
used when validating new clusters, Kubernetes versions, platform Check permission- $ kubectl $ kubectl auth
applications, or workloads running on the cluster. After each step, specific user auth can-i can-i create
[Op-tions] deployments
validate that the cluster is working properly.
--namespace dev
--user=chris
TEST CLUSTERS
1. Provision a highly available Kubernetes cluster with 100 PENDING AND WAITING PODS
Kubernetes nodes
Pending —> Check Resources
2. Scale that cluster down to 30 nodes after it has finished
TROUBLESHOOTING COMMAND
provisioning
General issue checking $ kubectl describe pod
3. Provision three additional highly available Kubernetes clusters <name of pending pod>
with five nodes
Check if pod is using too many $ kubectl top pod
4. Scale all three clusters (in parallel) to 30 nodes simultaneously resources
(only if Kubernetes Metrics API is
5. Provision 16 more highly available Kubernetes clusters with 30
available)
nodes
Check node resources $ kubectl top node
6. Kill five Kubernetes nodes on a single cluster simultaneously
(only if Kubernetes Metrics API is
7. Kill three control-plane nodes on a single cluster (fewer if the available)
2. Run the e2e cluster loader with the higher end of pods per node Remove pods from the environment.
(35-50)
Waiting —> Incorrect Image Information
3. Run Kubernetes conformance testing to stress the cluster
TROUBLESHOOTING COMMAND
4. Provision Helm to the Kubernetes cluster
Check YAML URI Look at the appropriate manifest file;
5. Test specific Kubernetes workloads (using Helm charts)
check the image URI:
− Deploy NGINX spec:
containers:
− Deploy Redis
— name: example
− Deploy Postgres image: url:port/image:v
automation
Also check that the secret information is correct.
− Test different provider-specific load balancer features
Control output:
Launch a temporary pod with an interactive shell: $ kubectl get deploy bash-rand -o yaml
apiVersion: extensions/v1beta1
$ kubectl run busybox --rm -i --tty --restart=Never
kind: Deployment
--image busybox -- /bin/sh
metadata:
annotations:
Copy files into and out of containers (note that this requires a tar binary deployment.kubernetes.io/revision: "1"
in the container): creationTimestamp: 2018-12-11T05:20:32Z
generation: 1
$ kubectl cp default/bash-rand-77d55b86c7-bntxs:/
labels:
root/rand . run: bash-rand
tar: Removing leading `/' from member names [...]
$ cat rand
567bea045d8b80cd6d007ced02849ac4
TROUBLESHOOT WITH JQ
Kubectl provides an option to output results in JSON format, which
Increase the verbosity of kubectl output (99 is the most verbose — “get
allows for additional parsing and filtering. This is beneficial when
everything”):
writing scripts or monitoring the state of resources in a Kubernetes
Use the kubectl json format and pipe to the jq utility using a simple FEED RESULTS TO EXTERNAL SCRIPTS
dot filter to pretty-print the output: bash while read loop:
$ kubectl get nodes -o json | jq '.' $ while read -r serverevent; do echo "$serverevent"
\
Use the hierarchy to filter the input so only node labels are displayed: | jq '.["operation"] = .type | .["node"] = .object.
metadata.name | { "operation": .operation, "node":
$ kubectl get nodes -o json | jq '.items[].metadata. .node}' ; \
labels' done < <(curl -sN --cert client.cert --key client.
key --cacert cluster-ca.cert \
https://192.168.100.10:6443/api/v1/nodes?watch=true)
ADVANCED FUNCTIONS
{
Find pods with containers that have not passed a readiness probe:
"operation": "ADDED",
• select – cherry-pick a piece of the input by criteria and use a "node": "192.168.100.10"
boolean expression to match desired value }
[...]
• Pipe the output of one filter into another filter to clean up the
results
bash coproc:
.status.containerStatuses[].ready == false ) |
coproc curl -sN --cacert cluster-ca.cert --cert ./
.metadata.name'
client.cert --key ./client.key \
https://192.168.100.10:6443/api/v1/nodes?watch=true
TROUBLESHOOT WITH CURL
Adding headers to requests are often used for: exec 5<&${COPROC[0]}
DESCRIPTION COMMAND
https://192.168.100.10:6443/api/v1/namespaces/
default/pods Set an environment ETCDCTL="ETCDCTL_API=3
{ variable for the etcdctl --cert=server.crt
"kind": "PodList", etcdctl binary, --key=server.key --cacert=ca.crt
endpoints, and the --endpoints=https://127.0.0.1:2379"w
"apiVersion": "v1",
required certificates
"metadata": {
and key
"selfLink": "/api/v1/namespaces/default/pods",
"resourceVersion": "126540"
}, TABLE CONTINUES IN THE NEXT COLUMN
"items": [
Kubernetes patch releases — i.e., 1.x.y (ensure it has all CVE fixes)
Limit access of pod creation for users
A new version of Kubernetes is released every three months. Patches
One of the most widely used vectors for attacking container
come out at regular intervals for the latest three versions and have
management systems are the containers themselves. To ensure the
bug fixes.
containers are secure and protect the system from attacks:
Versions must be kept up to date due to the lack of widespread • Limit who can create pods.
support for older versions of Kubernetes and the bug fixes in each
• Limit the use of unknown or unmaintained libraries.
patch release. Note: Kubernetes constantly releases security fixes, and
• Use a private container registry and tagged container
unpatched clusters are vulnerable.
images, keeping tagged images immutable.
Transport Layer Security (TLS)
Secure Dashboard
Kubernetes components must use an encrypted connection. Make
The Kubernetes Dashboard is a functional utility for users, but it can
sure that Kubernetes clusters have end-to-end TLS enabled.
also be a vector for malicious attacks — limit its exposure as much
Kubernetes RBAC and authentication as possible.
ADDITIONAL RESOURCES
• Tracking Kubernetes Releases: https://github.com/kubernetes/ WRITTEN BY DEEPAK GOEL,
sig-release/tree/master/releases CHIEF TECHNOLOGY OFFICER, D2IQ
− Enhancements Tracking Sheet Deepak Goel serves as CTO at D2iQ. In this role,
Deepak leads the Technical Architecture Group
− Bug Triage Tracking Sheet that oversees architecture of all D2iQ products. He
joined D2iQ in 2016 to lead the effort to design, develop,
− Release Calendar and build products on its Kubernetes platform, enabling day two
operations in multi-cluster, multi-tenant Kubernetes environments.
• Tracking Kubernetes Enhancement Proposals: Deepak brings over 10 years of experience in the computer industry
https://github.com/kubernetes/enhancements/tree/master/ across networking, distributed systems, and security.
stedolan.github.io/jq/