kubernetes 最全实操练习题 KCAD练习题
- 核心概念(13%)
- 题1:创建命名空间与pod
- 题2:利用yaml创建pod
- 题3:使用命令创建执行某一条命令的pod
- 题4:使用yaml创建执行某一条命令的pod
- 题5:获取创建命令空间的yaml,但不创建它
- 题6:获取ResourceQuota 的yaml,但不创建它
- 题7:获取所有命名空间上的 pod
- 题8:创建pod并开发端口
- 题9:修改pod的镜像,并观察pod
- 题10:获取nginx pod的ip
- 题11:创建临时pod访问nginx镜像
- 题12:获取pod的yaml
- 题13:获取有关 pod 的信息,包括有关潜在问题
- 题14:获取pod的日志
- 题15:如果 pod 崩溃并重新启动,则获取有关前一个实例的日志
- 题16:在pod中执行命令
- 题17:创建一个执行一条命令的pod
- 题18:同17,但创建的是临时pod
- 题19:创建一个pod,并设置env
- 多容器 Pod(10%)
- Pod design(20%)
- 配置(18%)
- Observability (18%)
- 服务与网络(13%)
- State Persistence(8%)
- Helm in K8s
- 重点
核心概念(13%)
题1:创建命名空间与pod
题目:Create a namespace called 'mynamespace' and a pod with image nginx called nginx on this namespace
题解:
# 创建命令空间
kubectl create namespace mynamespace
# 使用命令创建nginx pod
kubectl run nginx --image=nginx -n mynamespace
题2:利用yaml创建pod
题目:Create the pod that was just described using YAML
题解:
# nginx_pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx
namespace: mynamespace
spec:
containers:
- name: nginx
image: nginx
# 使用yaml文件创建pod,两者都可以
kubectl create -f nginx_pod.yaml
# 除了手敲yaml,官网复制,还可以命令生成
kubectl run nginx --image=nginx --dry-run=client -n mynamespace -o yaml > pod.yaml
题3:使用命令创建执行某一条命令的pod
题目:Create a busybox pod (using kubectl command) that runs the command "env". Run it and see the output
题解:
kubectl run busybox --image=busybox --command -- env
kubectl logs busybox
题4:使用yaml创建执行某一条命令的pod
题目:Create a busybox pod (using YAML) that runs the command "env". Run it and see the output
题解:
kubectl run busybox --image=busybox --command --dry-run=client -o yaml -- env > pod.yaml
# pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: busybox
name: busybox
spec:
containers:
- command:
- env
image: busybox
name: busybox
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Always
status: {}
kubectl create -f pod.yaml
题5:获取创建命令空间的yaml,但不创建它
题目:Get the YAML for a new namespace called 'myns' without creating it
题解:
kubectl create namespace myns -o yaml --dry-run=client
apiVersion: v1
kind: Namespace
metadata:
creationTimestamp: null
name: myns
spec: {}
status: {}
题6:获取ResourceQuota 的yaml,但不创建它
题目:Get the YAML for a new ResourceQuota called 'myrq' with hard limits of 1 CPU, 1G memory and 2 pods without creating it
题解:
kubectl create quota myrq --hard=cpu=1,memory=1G,pods=2 --dry-run=client -o yaml
apiVersion: v1
kind: ResourceQuota
metadata:
creationTimestamp: null
name: myrq
spec:
hard:
cpu: "1"
memory: 1G
pods: "2
status: {}
题7:获取所有命名空间上的 pod
题目:Get pods on all namespaces
题解:
kubectl get po -A
题8:创建pod并开发端口
题目:Create a pod with image nginx called nginx and expose traffic on port 80
题解:
kubectl run nginx --image=nginx --port=80
题9:修改pod的镜像,并观察pod
题目:Change pod's image to nginx:1.7.1. Observe that the container will be restarted as soon as the image gets pulled
题解:
kubectl set image pod/nginx nginx=nginx:1.7.1
kubectl describe po nginx
kubectl get po nginx -w
# 也可以使用kubectl edit 修改yaml中的images值
题10:获取nginx pod的ip
题目:Get nginx pod's ip created in previous step
题解:
kubectl get po -o wide | grep nginx
# 可以使用awk取ip,不过做题的时候没必要
题11:创建临时pod访问nginx镜像
题目:use a temp busybox image to wget its '/'
题解:
kubectl run busybox --image=busybox --rm -it -- wget -O- {nginx pod的ip}:80
题12:获取pod的yaml
题目:Get pod's YAML
题解:
kubectl get po nginx -o yaml
题13:获取有关 pod 的信息,包括有关潜在问题
题目:Get information about the pod, including details about potential issues (e.g. pod hasn't started)
题解:
kubectl describe po nginx
题14:获取pod的日志
题目:Get pod logs
题解:
kubectl logs nginx
题15:如果 pod 崩溃并重新启动,则获取有关前一个实例的日志
题目:If pod crashed and restarted, get logs about the previous instance
题解:
kubectl logs nginx -p
题16:在pod中执行命令
题目:Execute a simple shell on the nginx pod
题解:
kubectl exec -it nginx -- /bin/sh
题17:创建一个执行一条命令的pod
题目:Create a busybox pod that echoes 'hello world' and then exits
题解:
kubectl run busybox --image=busybox -it -- echo 'hello world'
题18:同17,但创建的是临时pod
题目:Do the same, but have the pod deleted automatically when it's completed
题解:
kubectl run busybox --image=busybox -it --rm -- /bin/sh -c 'echo hello world'
题19:创建一个pod,并设置env
题目:Create an nginx pod and set an env value as 'var1=val1'. Check the env value existence within the pod
题解:
# 创建
kubectl run nginx --image=nginx --restart=Never --env=var1=val1
# 检查
kubectl exec -it nginx -- env
多容器 Pod(10%)
题1:简单多容器
题目:Create a Pod with two containers, both with image busybox and command "echo hello; sleep 3600". Connect to the second container and run 'ls'
题解:
# pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: busybox
name: busybox
spec:
containers:
- args:
- /bin/sh
- -c
- ' echo hello;sleep 3600 '
image: busybox
name: busybox
resources: {}
- args:
- /bin/sh
- -c
- echo hello;sleep 3600
image: busybox
name: busybox2
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
# 创建pod
kubectl create -f pod.yaml
# 连接容器执行命令
kubectl exec -it busybox -c busybox2 -- ls
题2:初始化容器
题目:Create a pod with an nginx container exposed on port 80. Add a busybox init container which downloads a page using "wget -O /work-dir/index.html http://neverssl.com/online". Make a volume of type emptyDir and mount it in both containers. For the nginx container, mount it on "/usr/share/nginx/html" and for the initcontainer, mount it on "/work-dir". When done, get the IP of the created pod and create a busybox pod and run "wget -O- IP"
题解:
# pod.yaml
apiVersion: v1
kind: Pod
metadata:
labels:
run: box
name: box
spec:
initContainers:
- args:
- /bin/sh
- -c
- wget -O /work-dir/index.html http://neverssl.com/online
image: busybox
name: box
volumeMounts:
- name: vol
mountPath: /work-dir
containers:
- image: nginx
name: nginx
ports:
- containerPort: 80
volumeMounts:
- name: vol
mountPath: /usr/share/nginx/html
volumes:
- name: vol
emptyDir: {}
kubectl apply -f pod.yaml
kubectl get po -o wide
kubectl run box-test --image=busybox -it --rm -- /bin/sh -c "wget -O- IP"
Pod design(20%)
标签
题1:创建具有相关标签的pod
题目:Create 3 pods with names nginx1,nginx2,nginx3. All of them should have the label app=v1
题解:
kubectl run nginx1 --image=nginx --labels=app=v1
kubectl run nginx2 --image=nginx --labels=app=v1
kubectl run nginx3 --image=nginx --labels=app=v1
题2:显示pod的所有标签
题目:Show all labels of the pods
题解:
kubectl get po --show-labels
题3:更新pod标签
题目:Change the labels of pod 'nginx2' to be app=v2
题解:
kubectl label po nginx2 app=v2 --overwrite
题4:获取 pod 的某一个标签
题目:Get the label 'app' for the pods (show a column with APP labels)
题解:
kubectl get po -L app
题5:根据label值获取pod
题目:Get only the 'app=v2' pods
题解:
kubectl get po -l app=v2
题6:删除标签
题目:Remove the 'app' label from the pods we created before
题解:
kubectl label po nginx1 nginx2 nginx3 app-
题7:给node添加标签
题目:create a label for node
题解:
kubectl label nodes <your-node-name> accelerator=nvidia-tesla-p100
题8:pod的标签选择器
题目:Create a pod that will be deployed to a Node that has the label 'accelerator=nvidia-tesla-p100'
# pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: cuda-test
spec:
containers:
- name: cuda-test
image: "k8s.gcr.io/cuda-vector-add:v0.1"
nodeSelector:
accelerator: nvidia-tesla-p100
kubectl create -f pod.yaml
题9:为pod添加注解
题目:Annotate pods nginx1, nginx2, nginx3 with "description='my description'" value
题解:
kubectl annotate po nginx1 nginx2 nginx3 description='my description'
题10:检查pod的注解
题目:Check the annotations for pod nginx1
题解:
kubectl annotate pod nginx1 --list
题11:移除pod的注解
题目:Remove the annotations for these three pods
题解:
kubectl annotate po nginx{1..3} description-
题12: 删除pod
题目:Remove these pods to have a clean state in your cluster
题解:
kubectl delete po nginx{1..3}
deployment
题1:通过deployment部署容器
题目:Create a deployment with image nginx:1.18.0, called nginx, having 2 replicas, defining port 80 as the port that this container exposes (don't create a service for this deployment)
题解:
kubectl create deploy nginx --image=nginx:1.18.0 --replicas=2 --port=80
题2:获取deployment的yaml文件
题目:View the YAML of this deployment
题解:
kubectl get deploy nginx -o yaml
题3: 获取副本集的yaml
题目:View the YAML of the replica set that was created by this deployment
题解:
kubectl describe deploy nginx # you'll see the name of the replica set on the Events section and in the 'NewReplicaSet' property
# OR you can find rs directly by:
kubectl get rs -l run=nginx # if you created deployment by 'run' command
kubectl get rs -l app=nginx # if you created deployment by 'create' command
# you could also just do kubectl get rs
kubectl get rs nginx-7bf7478b77 -o yaml
题4:获取pod的yaml
题目:Get the YAML for one of the pods
题解:
kubectl get po nginx-7bf7478b77-gjzp8 -o yaml
题5:检查deployment部署进展情况
题目:Check how the deployment rollout is going
题解:
kubectl rollout status deploy nginx
题6: 更新镜像
题目:Update the nginx image to nginx:1.19.8
题解:
kubectl set image deploy nginx nginx=nginx:1.19.8
# 也可以kubectl edit
题7:查看历史确认副本正常
题目:Check the rollout history and confirm that the replicas are OK
题解:
kubectl rollout history deploy nginx
kubectl get deploy nginx
kubectl get rs | grep nginx
kubectl get po | grep nginx
题8:回退
题目:Undo the latest rollout and verify that new pods have the old image (nginx:1.18.0)
题解:
kubectl rollout undo deploy nginx
kubectl get po # select one 'Running' Pod
kubectl describe po nginx-5ff4457d65-nslcl | grep -i image
# kubectl rollout undo命令可以通过--to-revision参数指定回退到哪个版本
题9:查看第四次修订的详细信息
题目:Check the details of the fourth revision (number 4)
题解:
kubectl rollout history deploy nginx --revision=4
题10:更新副本数
题目:Scale the deployment to 5 replicas
题解:
kubectl scale deploy nginx --replicas=5
题11:副本自动伸缩
题目:Autoscale the deployment, pods between 5 and 10, targetting CPU utilization at 80%
题解:
kubectl autoscale deploy nginx --min=5 --max=10 --cpu-percent=80
# view the horizontalpodautoscalers.autoscaling for nginx
kubectl get hpa nginx
题12:暂停deploy
题目:Pause the rollout of the deployment
题解:
kubectl rollout pause deploy nginx
题13:更新镜像,确认暂停
题目:Update the image to nginx:1.19.9 and check that there's nothing going on, since we paused the rollout
题解:
kubectl set image deploy nginx nginx=nginx:1.19.9
# change the image to nginx:1.19.9
kubectl rollout history deploy nginx
# no new revision
题14:取消暂停
题目:Resume the rollout and check that the nginx:1.19.9 image has been applied
题解:
kubectl rollout resume deploy nginx
kubectl rollout history deploy nginx
题15:删除deploy与自动伸缩
题目:Delete the deployment and the horizontal pod autoscaler you created
题解:
kubectl delete deploy nginx
kubectl delete hpa nginx
Jobs
题1:创建jobs
题目:Create a job named pi with image perl that runs the command with arguments "perl -Mbignum=bpi -wle 'print bpi(2000)'"
题解:
kubectl create job pi --image=perl -- perl -Mbignum=bpi -wle 'print bpi(2000)'
题2:获取jobs输出
题目:Wait till it's done, get the output
题解:
kubectl get jobs -w # wait till 'SUCCESSFUL' is 1 (will take some time, perl image might be big)
kubectl get po # get the pod name
kubectl logs pi-**** # get the pi numbers
题3:删除jobs
题目:delete the jobs
题解:
kubectl delete job pi
题4:查看jobs状态
题目:See the status of the job, describe it and see the logs
题解:
kubectl get jobs
kubectl describe jobs busybox
kubectl logs job/busybox
题5:创建jobs,设置超时时间
题目:Create a job but ensure that it will be automatically terminated by kubernetes if it takes more than 30 seconds to execute
题解:
kubectl create job busybox --image=busybox --dry-run=client -o yaml -- /bin/sh -c 'while true; do echo hello; sleep 10;done' > job.yaml
vi job.yaml
# Add job.spec.activeDeadlineSeconds=30
apiVersion: batch/v1
kind: Job
metadata:
creationTimestamp: null
labels:
run: busybox
name: busybox
spec:
activeDeadlineSeconds: 30 # add this line
template:
metadata:
creationTimestamp: null
labels:
run: busybox
spec:
containers:
- args:
- /bin/sh
- -c
- while true; do echo hello; sleep 10;done
image: busybox
name: busybox
resources: {}
restartPolicy: OnFailure
status: {}
kubectl create -f job.yaml
题6:多次运行
题目:Create the same job, make it run 5 times, one after the other. Verify its status and delete it
题解:
kubectl create job busybox --image=busybox --dry-run=client -o yaml -- /bin/sh -c 'echo hello;sleep 30;echo world' > job.yaml
vi job.yaml
# Add job.spec.completions=5
apiVersion: batch/v1
kind: Job
metadata:
creationTimestamp: null
labels:
run: busybox
name: busybox
spec:
completions: 5 # add this line
template:
metadata:
creationTimestamp: null
labels:
run: busybox
spec:
containers:
- args:
- /bin/sh
- -c
- echo hello;sleep 30;echo world
image: busybox
name: busybox
resources: {}
restartPolicy: OnFailure
status: {}
kubectl create -f job.yaml
kubectl get job busybox -w # will take two and a half minutes
kubectl delete jobs busybox
Cron jobs
题1:创建定时任务
题目:Create a cron job with image busybox that runs on a schedule of "*/1 * * * *" and writes 'date; echo Hello from the Kubernetes cluster' to standard output
题解:
kubectl create cronjob busybox --image=busybox --schedule="*/1 * * * *" -- /bin/sh -c 'date; echo Hello from the Kubernetes cluster'
题2:查看日志
题目:See its logs
题解:
kubectl get cj
kubectl get jobs --watch
kubectl get po --show-labels # observe that the pods have a label that mentions their 'parent' job
kubectl logs busybox-1529745840-m867r
题3:删除定时任务
题目:delete cron job
题解:
kubectl delete cj busybox
题4:设置超时启动时间
题目:Create a cron job with image busybox that runs every minute and writes 'date; echo Hello from the Kubernetes cluster' to standard output. The cron job should be terminated if it takes more than 17 seconds to start execution after its scheduled time (i.e. the job missed its scheduled time).
题解:
kubectl create cronjob time-limited-job --image=busybox --restart=Never --dry-run=client --schedule="* * * * *" -o yaml -- /bin/sh -c 'date; echo Hello from the Kubernetes cluster' > time-limited-job.yaml
vi time-limited-job.yaml
# Add cronjob.spec.startingDeadlineSeconds=17
apiVersion: batch/v1beta1
kind: CronJob
metadata:
creationTimestamp: null
name: time-limited-job
spec:
startingDeadlineSeconds: 17 # add this line
jobTemplate:
metadata:
creationTimestamp: null
name: time-limited-job
spec:
template:
metadata:
creationTimestamp: null
spec:
containers:
- args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
image: busybox
name: time-limited-job
resources: {}
restartPolicy: Never
schedule: '* * * * *'
status: {}
题5:设置超时运行时间
题目:Create a cron job with image busybox that runs every minute and writes 'date; echo Hello from the Kubernetes cluster' to standard output. The cron job should be terminated if it successfully starts but takes more than 12 seconds to complete execution.
题解:
kubectl create cronjob time-limited-job --image=busybox --restart=Never --dry-run=client --schedule="* * * * *" -o yaml -- /bin/sh -c 'date; echo Hello from the Kubernetes cluster' > time-limited-job.yaml
vi time-limited-job.yaml
# Add cronjob.spec.jobTemplate.spec.activeDeadlineSeconds=12
apiVersion: batch/v1beta1
kind: CronJob
metadata:
creationTimestamp: null
name: time-limited-job
spec:
jobTemplate:
metadata:
creationTimestamp: null
name: time-limited-job
spec:
activeDeadlineSeconds: 12 # add this line
template:
metadata:
creationTimestamp: null
spec:
containers:
- args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
image: busybox
name: time-limited-job
resources: {}
restartPolicy: Never
schedule: '* * * * *'
status: {}
配置(18%)
ConfigMaps
题1:创建configmap
题目:Create a configmap named config with values foo=lala,foo2=lolo
题解:
kubectl create configmap config --from-literal=foo=lala --from-literal=foo2=lolo
题2:查看configmap
题目:Display its values
题解:
kubectl get cm config -o yaml
# or
kubectl describe cm config
题3:通过txt文件创建
题目:Create and display a configmap from a file
题解:
echo -e "foo3=lili\nfoo4=lele" > config.txt
kubectl create cm configmap2 --from-file=config.txt
kubectl get cm configmap2 -o yaml
题4: 通过env文件创建
题目:Create and display a configmap from a .env file
题解:
echo -e "var1=val1\n# this is a comment\n\nvar2=val2\n#anothercomment" > config.env
kubectl create cm configmap3 --from-env-file=config.env
kubectl get cm configmap3 -o yaml
题5:通过文件创建并赋值给指定key
题目:Create and display a configmap from a file, giving the key 'special'
题解:
echo -e "var3=val3\nvar4=val4" > config4.txt
kubectl create cm configmap4 --from-file=special=config4.txt
kubectl describe cm configmap4
kubectl get cm configmap4 -o yaml
题6:pod中引用config其中的值
题目:Create a configMap called 'options' with the value var5=val5. Create a new nginx pod that loads the value from variable 'var5' in an env variable called 'option'
题解:
kubectl create cm options --from-literal=var5=val5
kubectl run nginx --image=nginx --restart=Never --dry-run=client -o yaml > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
env:
- name: option # name of the env variable
valueFrom:
configMapKeyRef:
name: options # name of config map
key: var5 # name of the entity in config map
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl exec -it nginx -- env | grep option # will show 'option=val5'
题7:pod中应用整个config为env
题目:Create a configMap 'anotherone' with values 'var6=val6', 'var7=val7'. Load this configMap as env variables into a new nginx pod
题解:
kubectl create configmap anotherone --from-literal=var6=val6 --from-literal=var7=val7
kubectl run --restart=Never nginx --image=nginx -o yaml --dry-run=client > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
envFrom: # different than previous one, that was 'env'
- configMapRef: # different from the previous one, was 'configMapKeyRef'
name: anotherone # the name of the config map
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl exec -it nginx -- env
题8: pod中挂载config
题目:Create a configMap 'cmvolume' with values 'var8=val8', 'var9=val9'. Load this as a volume inside an nginx pod on path '/etc/lala'. Create the pod and 'ls' into the '/etc/lala' directory.
题解:
kubectl create configmap cmvolume --from-literal=var8=val8 --from-literal=var9=val9
kubectl run nginx --image=nginx --restart=Never -o yaml --dry-run=client > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
volumes: # add a volumes list
- name: myvolume # just a name, you'll reference this in the pods
configMap:
name: cmvolume # name of your configmap
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
volumeMounts: # your volume mounts are listed here
- name: myvolume # the name that you specified in pod.spec.volumes.name
mountPath: /etc/lala # the path inside your container
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl exec -it nginx -- /bin/sh
cd /etc/lala
ls # will show var8 var9
cat var8 # will show val8
SecurityContext
题1:指定运行pod的用户id
题目:Create the YAML for an nginx pod that runs with the user ID 101. No need to create the pod
题解:
kubectl run nginx --image=nginx --restart=Never --dry-run=client -o yaml > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
securityContext: # insert this line
runAsUser: 101 # UID for the user
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
题2: 添加Capabilities
题目:Create the YAML for an nginx pod that has the capabilities "NET_ADMIN", "SYS_TIME" added to its single container
题解:
kubectl run nginx --image=nginx --restart=Never --dry-run=client -o yaml > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
securityContext: # insert this line
capabilities: # and this
add: ["NET_ADMIN", "SYS_TIME"] # this as well
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
Requests and Limits
题1:设置pod资源限制
题目:Create an nginx pod with requests cpu=100m,memory=256Mi and limits cpu=200m,memory=512Mi
题解1:
kubectl run nginx --image=nginx --restart=Never --requests='cpu=100m,memory=256Mi' --limits='cpu=200m,memory=512Mi'
题解2:
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
name: nginx
resources:
requests:
memory: "256Mi"
cpu: 100m
limits:
memory: "512Mi"
cpu: 200m
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Always
status: {}
Secrets
题1:创建一个名为 mysecret 的密钥,其值为 password=mypass
题目:Create a secret called mysecret with the values password=mypass
题解:
kubectl create secret generic mysecret --from-literal=password=mypass
题2:创建一个名为mysecret2 的密钥,值从文件中获取
题目:Create a secret called mysecret2 that gets key/value from a file
题解:
echo -n admin > username
kubectl create secret generic mysecret2 --from-file=username
题3:获取密钥的值
题目:Get the value of mysecret2
题解1:
kubectl get secret mysecret2 -o yaml
echo -n YWRtaW4= | base64 -d
题解2:
kubectl get secret mysecret2 -o jsonpath='{.data.username}' | base64 -d
题解3:
kubectl get secret mysecret2 --template '{{.data.username}}' | base64 -d
题4:创建pod,挂载密钥成文件
题目:Create an nginx pod that mounts the secret mysecret2 in a volume on path /etc/foo
题解:
kubectl run nginx --image=nginx --restart=Never -o yaml --dry-run=client > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
volumes: # specify the volumes
- name: foo # this name will be used for reference inside the container
secret: # we want a secret
secretName: mysecret2 # name of the secret - this must already exist on pod creation
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
volumeMounts: # our volume mounts
- name: foo # name on pod.spec.volumes
mountPath: /etc/foo #our mount path
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl exec -it nginx /bin/bash
ls /etc/foo # shows username
cat /etc/foo/username # shows admin
题5:创建pod,将密钥设置为环境变量
题目:Created and mount the variable 'username' from secret mysecret2 onto a new nginx pod in env variable called 'USERNAME'
题解:
kubectl run nginx --image=nginx --restart=Never -o yaml --dry-run=client > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
env: # our env variables
- name: USERNAME # asked name
valueFrom:
secretKeyRef: # secret reference
name: mysecret2 # our secret's name
key: username # the key of the data in the secret
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl exec -it nginx -- env | grep USERNAME | cut -d '=' -f 2 # will show 'admin'
Service Accounts
题1:查看服务账号列表
题目:See all the service accounts of the cluster in all namespaces
题解:
kubectl get sa --all-namespaces
题2:创建新的账号
题目:Create a new serviceaccount called 'myuser'
题解:
kubectl create sa myuser
题3:创建pod,使用服务账号
题目:Create an nginx pod that uses 'myuser' as a service account
题解:
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
serviceAccountName: myuser # we use pod.spec.serviceAccountName
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl describe pod nginx
Observability (18%)
Liveness, readiness and startup probes
题1:创建pod,设置存活探针为运行命令
题目:Create an nginx pod with a liveness probe that just runs the command 'ls'. Save its YAML in pod.yaml. Run it, check its probe status
题解:
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
livenessProbe: # our probe
exec: # add this line
command: # command definition
- ls # ls command
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl describe pod nginx | grep -i liveness # run this to see that liveness probe works
题2:创建pod,设置存活探针为运行命令,并配置初始延迟与探测间隔
题目:Modify the pod.yaml file so that liveness probe starts kicking in after 5 seconds whereas the interval between probes would be 5 seconds. Run it, check the probe
题解:
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
livenessProbe:
initialDelaySeconds: 5 # add this line
periodSeconds: 5 # add this line as well
exec:
command:
- ls
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl describe po nginx | grep -i liveness
题3:创建pod,设置http请求就绪探针
题目:Create an nginx pod (that includes port 80) with an HTTP readinessProbe on path '/' on port 80. Again, run it, check the readinessProbe
题解:
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
resources: {}
ports:
- containerPort: 80 # Note: Readiness probes runs on the container during its whole lifecycle. Since nginx exposes 80, containerPort: 80 is not required for readiness to work.
readinessProbe: # declare the readiness probe
httpGet: # add this line
path: / #
port: 80 #
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
kubectl create -f pod.yaml
kubectl describe pod nginx | grep -i readiness # to see the pod readiness details
题4:查看指针失败的信息
题目:Lots of pods are running in qa
,alan
,test
,production
namespaces. All of these pods are configured with liveness probe. Please list all pods whose liveness probe are failed
题解:
kubectl get ns # check namespaces
kubectl -n qa get events | grep -i "Liveness probe failed"
kubectl -n alan get events | grep -i "Liveness probe failed"
kubectl -n test get events | grep -i "Liveness probe failed"
kubectl -n production get events | grep -i "Liveness probe failed"
Logging
题1:创建容器,循环打印,检查日志
题目:Create a busybox pod that runs 'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 1; done'. Check its logs
题解:
kubectl run busybox --image=busybox --restart=Never -- /bin/sh -c 'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 1; done'
kubectl logs busybox -f # follow the logs
Debugging
题1:创建pod,运行错误命令,查看日志与信息
题目:Create a busybox pod that runs 'ls /notexist'. Determine if there's an error (of course there is), see it. In the end, delete the pod
题解:
kubectl run busybox --restart=Never --image=busybox -- /bin/sh -c 'ls /notexist'
# show that there's an error
kubectl logs busybox
kubectl describe po busybox
kubectl delete po busybox
题2:创建pod,运行错误命令,查看信息,强制删除
题目:Create a busybox pod that runs 'notexist'. Determine if there's an error (of course there is), see it. In the end, delete the pod forcefully with a 0 grace period
题解:
kubectl run busybox --restart=Never --image=busybox -- notexist
kubectl logs busybox # will bring nothing! container never started
kubectl describe po busybox # in the events section, you'll see the error
# also...
kubectl get events | grep -i error # you'll see the error here as well
kubectl delete po busybox --force --grace-period=0
题3:获取节点cpu 内存占用信息
题目:Get CPU/memory utilization for nodes (metrics-server must be running)
题解:
kubectl top nodes
服务与网络(13%)
题1:创建pod,开发端口
题目:Create a pod with image nginx called nginx and expose its port 80
题解:
kubectl run nginx --image=nginx --restart=Never --port=80 --expose
题2:查看ClusterIP,检查端口
题目:Confirm that ClusterIP has been created. Also check endpoints
题解:
kubectl get svc nginx # services
kubectl get ep # endpoints
题3:创建临时pod,请求服务
题目:Get service's ClusterIP, create a temp busybox pod and 'hit' that IP with wget
题解1:
kubectl get svc nginx # get the IP (something like 10.108.93.130)
kubectl run busybox --rm --image=busybox -it --restart=Never -- sh
wget -O- IP:80
exit
题解2:
IP=$(kubectl get svc nginx --template={{.spec.clusterIP}}) # get the IP (something like 10.108.93.130)
kubectl run busybox --rm --image=busybox -it --restart=Never --env="IP=$IP" -- wget -O- $IP:80 --timeout 2
题4:修改端口开放类型,并请求
题目:Convert the ClusterIP to NodePort for the same service and find the NodePort port. Hit service using Node's IP.
题解:
kubectl patch svc nginx -p '{"spec":{"type":"NodePort"}}'
kubectl get svc
# result:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1d
nginx NodePort 10.107.253.138 <none> 80:31931/TCP 3m
wget -O- NODE_IP:31931
题5:指定映像创建3 副本DP并添加标记“app=foo”,声明容器接受端口 流量(但不要创建服务)
题目:Create a deployment called foo using image 'dgkanatsios/simpleapp' (a simple server that returns hostname) and 3 replicas. Label it as 'app=foo'. Declare that containers in this pod will accept traffic on port 8080 (do NOT create a service yet)
题解:
kubectl create deploy foo --image=dgkanatsios/simpleapp --port=8080 --replicas=3
kubectl label deployment foo --overwrite app=foo
题6:获取pod ip,创建临时容器尝试访问
题目:Get the pod IPs. Create a temp busybox pod and try hitting them on port 8080
题解1:
kubectl get pods -l app=foo -o wide # 'wide' will show pod IPs
kubectl run busybox --image=busybox --restart=Never -it --rm -- sh
wget -O- POD_IP:8080 # do not try with pod name, will not work
# try hitting all IPs to confirm that hostname is different
exit
题解2:
kubectl get po -o wide -l app=foo | awk '{print $6}' | grep -v IP | xargs -L1 -I '{}' kubectl run --rm -ti tmp --restart=Never --image=busybox -- wget -O- http://\{\}:8080
题解3:
kubectl get po -l app=foo -o jsonpath='{range .items[*]}{.status.podIP}{"\n"}{end}' | xargs -L1 -I '{}' kubectl run --rm -ti tmp --restart=Never --image=busybox -- wget -O- http://\{\}:8080
题7:创建服务,开发dp的端口
题目:Create a service that exposes the deployment on port 6262. Verify its existence, check the endpoints
题解:
kubectl expose deploy foo --port=6262 --target-port=8080
kubectl get service foo # you will see ClusterIP as well as port 6262
kubectl get endpoints foo # you will see the IPs of the three replica pods, listening on port 8080
题8:创建临时pod,访问服务
题目:Create a temp busybox pod and connect via wget to foo service, Verify that each time there's a different hostname returned.
kubectl get svc # get the foo service ClusterIP
kubectl run busybox --image=busybox -it --rm --restart=Never -- sh
wget -O- foo:6262 # DNS works! run it many times, you'll see different pods responding
wget -O- SERVICE_CLUSTER_IP:6262 # ClusterIP works as well
题9:创建2副本DP,开发端口,设置访问策略
题目:Create an nginx deployment of 2 replicas, expose it via a ClusterIP service on port 80. Create a NetworkPolicy so that only pods with labels 'access: granted' can access the deployment and apply it
题解:
kubectl create deployment nginx --image=nginx --replicas=2
kubectl expose deployment nginx --port=80
kubectl describe svc nginx # see the 'app=nginx' selector for the pods
# or
kubectl get svc nginx -o yaml
vi policy.yaml
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: access-nginx # pick a name
spec:
podSelector:
matchLabels:
app: nginx # selector for the pods
ingress: # allow ingress traffic
- from:
- podSelector: # from pods
matchLabels: # with this label
access: granted
kubectl create -f policy.yaml
# Check if the Network Policy has been created correctly
# make sure that your cluster's network provider supports Network Policy (https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/#before-you-begin)
kubectl run busybox --image=busybox --rm -it --restart=Never -- wget -O- http://nginx:80 --timeout 2 # This should not work. --timeout is optional here. But it helps to get answer more quickly (in seconds vs minutes)
kubectl run busybox --image=busybox --rm -it --restart=Never --labels=access=granted -- wget -O- http://nginx:80 --timeout 2 # This should be fine
State Persistence(8%)
题1:创建多容器pod,挂载卷,进行容器执行命令,删除pod
题目:Create busybox pod with two containers, each one will have the image busybox and will run the 'sleep 3600' command. Make both containers mount an emptyDir at '/etc/foo'. Connect to the second busybox, write the first column of '/etc/passwd' file to '/etc/foo/passwd'. Connect to the first busybox and write '/etc/foo/passwd' file to standard output. Delete pod.
题解:
kubectl run busybox --image=busybox --restart=Never -o yaml --dry-run=client -- /bin/sh -c 'sleep 3600' > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: busybox
name: busybox
spec:
dnsPolicy: ClusterFirst
restartPolicy: Never
containers:
- args:
- /bin/sh
- -c
- sleep 3600
image: busybox
imagePullPolicy: IfNotPresent
name: busybox
resources: {}
volumeMounts: #
- name: myvolume #
mountPath: /etc/foo #
- args:
- /bin/sh
- -c
- sleep 3600
image: busybox
name: busybox2 # don't forget to change the name during copy paste, must be different from the first container's name!
volumeMounts: #
- name: myvolume #
mountPath: /etc/foo #
volumes: #
- name: myvolume #
emptyDir: {} #
kubectl exec -it busybox -c busybox2 -- /bin/sh
cat /etc/passwd | cut -f 1 -d ':' > /etc/foo/passwd
cat /etc/foo/passwd # confirm that stuff has been written successfully
exit
kubectl exec -it busybox -c busybox -- /bin/sh
mount | grep foo # confirm the mounting
cat /etc/foo/passwd
exit
kubectl delete po busybox
题2:创建pv,设置容量、名称、策略。并查看它
题目:Create a PersistentVolume of 10Gi, called 'myvolume'. Make it have accessMode of 'ReadWriteOnce' and 'ReadWriteMany', storageClassName 'normal', mounted on hostPath '/etc/foo'. Save it on pv.yaml, add it to the cluster. Show the PersistentVolumes that exist on the cluster
题解:
# vi pv.yaml
kind: PersistentVolume
apiVersion: v1
metadata:
name: myvolume
spec:
storageClassName: normal
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
- ReadWriteMany
hostPath:
path: /etc/foo
kubectl create -f pv.yaml
# will have status 'Available'
kubectl get pv
题3:创建pvc,并获取pv,pvc列表
题目:Create a PersistentVolumeClaim for this storage class, called 'mypvc', a request of 4Gi and an accessMode of ReadWriteOnce, with the storageClassName of normal, and save it on pvc.yaml. Create it on the cluster. Show the PersistentVolumeClaims of the cluster. Show the PersistentVolumes of the cluster
题解:
vi pvc.yaml
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: mypvc
spec:
storageClassName: normal
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 4Gi
kubectl create -f pvc.yaml
kubectl get pvc # will show as 'Bound'
kubectl get pv # will show as 'Bound' as well
题4:创建pod,挂载pvc
题目:Create a busybox pod with command 'sleep 3600', save it on pod.yaml. Mount the PersistentVolumeClaim to '/etc/foo'. Connect to the 'busybox' pod, and copy the '/etc/passwd' file to '/etc/foo/passwd'
题解:
kubectl run busybox --image=busybox --restart=Never -o yaml --dry-run=client -- /bin/sh -c 'sleep 3600' > pod.yaml
vi pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: busybox
name: busybox
spec:
containers:
- args:
- /bin/sh
- -c
- sleep 3600
image: busybox
imagePullPolicy: IfNotPresent
name: busybox
resources: {}
volumeMounts: #
- name: myvolume #
mountPath: /etc/foo #
dnsPolicy: ClusterFirst
restartPolicy: Never
volumes: #
- name: myvolume #
persistentVolumeClaim: #
claimName: mypvc #
status: {}
kubectl create -f pod.yaml
kubectl exec busybox -it -- cp /etc/passwd /etc/foo/passwd
题5:利用已有文件,创建pod,执行命令之后删除并检测
题目:Create a second pod which is identical with the one you just created (you can easily do it by changing the 'name' property on pod.yaml). Connect to it and verify that '/etc/foo' contains the 'passwd' file. Delete pods to cleanup. Note: If you can't see the file from the second pod, can you figure out why? What would you do to fix that?
题解:
vim pod.yaml
# change 'metadata.name: busybox' to 'metadata.name: busybox2'
kubectl create -f pod.yaml
kubectl exec busybox2 -- ls /etc/foo # will show 'passwd'
# cleanup
kubectl delete po busybox busybox2
# check which nodes the pods are on
kubectl get po busybox -o wide
kubectl get po busybox2 -o wide
题6:创建pod,并复制pod中数据
题目:Create a busybox pod with 'sleep 3600' as arguments. Copy '/etc/passwd' from the pod to your local folder
题解:
kubectl run busybox --image=busybox --restart=Never -- sleep 3600
kubectl cp busybox:/etc/passwd ./passwd
cat passwd
Helm in K8s
题1:创建基本chart包
题目:Creating a basic Helm chart
题解:
helm create chart-test
题2:运行chart包
题目:Running a Helm chart
题解:
helm install -f myvalues.yaml my redis ./redis
题3:查找挂起列表
题目:Find pending Helm deployments
题解:
helm list --pending
题4:卸载
题目:Uninstall a Helm release
题解:
helm uninstall release_name
题5:更新chart包
题目:Upgrading a Helm chart
题解:
helm upgrade -f myvalues.yaml -f override.yaml redis ./redis
题6:使用repo命令
题目:Using Helm repo
题解:
helm repo add [NAME] [URL] [flags]
helm repo list / helm repo ls
helm repo remove [REPO1] [flags]
helm repo update / helm repo up
helm repo update [REPO1] [flags]
helm repo index [DIR] [flags]
题7:下载拉取chart包
题目:Download a Helm chart from a repository
题解:
helm pull [chart URL | repo/chartname] [...] [flags] ## this would download a helm, not install
helm pull --untar [rep/chartname] # untar the chart after downloading it
重点
# 练习环境
https://www.katacoda.com/courses/kubernetes/playground
# 命令自动补全
source <(kubectl completion bash)
# 查看k8s对象下的元素
kubectl explain
# 保存k8s官网 关键书签
出处:https://www.cnblogs.com/52why
微信公众号: 红雨python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通