CKAD試験無料問題集「Linux Foundation Certified Kubernetes Application Developer 認定」


Task
A Deployment named backend-deployment in namespace staging runs a web application on port 8081.
正解:
See the solution below.
Explanation:
Solution:


You are building a Kubernetes application tnat requires persistent storage for its dat a. The application needs to be able to access the data even if the pod is restarted or deleted. You have a PersistentVolumeClaim (PVC) defined for this purpose.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. Create a PersistentVolume (PV):
- Define a PV with a suitable storage class, access modes (ReadWriteOnce), and a capacity that meets your application's storage requirements.
- Example:

2. Create a PersistentVolumeClaim (PVC): - Define a PVC with the desired storage class and access modes. - Specify the desired storage capacity. - Example:

3. Create a Deployment With the PVC: - In the Deployment YAML, define a volume mount that uses the PVC you created_ - Specify the volume mount path within the container. - Example:

4. Create the Deployment: - Apply the Deployment YAML using 'kubectl apply -f my-app-deployment.yamr 5. Verify the Deployment - Check the status of the Deployment using 'kubectl get deployments my-app' - Verify that the Pod is running and using the PersistentVolumeClaim. - You can also check the pod's logs for confirmation that the data is stored in the mounted volume.
You have a Deployment named 'my-app-deployment running a Flask application. You want to add a liveness probe that checks if the Flask application is responding on port '5000' and a readiness probe that checks if the application is ready to receive requests. Implement these probes using Kustomize.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. Create a base Deployment configuration:

2. Create a 'kustomization.yamr file:

3. Create 'patcnes/liveness-probe.yaml':

4. Create 'patches/readiness-probe-yaml':

5. Apply the Kustomize configuration: bash kustomize . I kubectl apply -t- - Liveness probe: This probe checks if the application is still alive and running. It uses a TCP socket to connect to port ' 5000' and waits for 15 seconds before making the first cneck. It checks every 20 seconds, and if it fails 3 times in a row, the pod is restarted. - Readiness probe: This probe checks if the application is ready to receive requests. It also uses a TCP socket to connect to port '5000'. It checks every 10 seconds and waits for 5 seconds before the first check. If it fails 2 times in a row, the pod is marked as unhealthy and excluded trom receiving traffic. Note: Make sure your Flask application is actually listening on port '5000' and responding to requests. ,
You have a Kubernetes cluster running a microservices application. The application nas a set of microservices deployed as Deployments, each with their own set of resource requests and limits- You want to implement a monitoring system to track the resource utilization of these microservices.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. Install Prometheus: Prometheus is an open-source monitoring system that collects and stores metrics. You can install Prometheus in your Kubernetes cluster using a Deployment:

2 Create a ConfigMap for Prometheus: Define a ConfigMap to configure Prometheus with the desired scrape targets and other settings:

3. Create a Service for Prometheus: Create a Service to expose Prometheus outside the cluster:

4. Install Grafana: Grafana is a popular open-source dashboard and visualization tool. You can install Grafana in your Kubernetes cluster using a Deployment:

5. Create a ConfigMap for Grafana: Create a ConfigMap to configure Grafana with Prometheus as the data source:

6. Create a Service for Grafana: Create a Service to expose Grafana outside the cluster:

T Configure Gratana: Access the Grafana web interface (using the LoadBalancer IP address) and configure a new data source for Prometheus. Specify the Prometheus Service address. 8. Create Dashboards: Create dashboards in Gratana to visualize the metrics collected by Prometheus. You can create dashboards for individual microservices, showing metrics like CPU usage, memory usage, network traffic, and response times. 9. Monitor Your Microservices: Once you have dashboards set up, you can monitor your microservices' resource utilization and performance in real time. use Grafana's alerting features to be notified of any issues or potential problems. ,
Context
You are asked to allow a Pod to communicate with two other Pods but nothing else.
You must connect to the correct host . Failure to do so may result
in a zero score.
!
[candidate@base] $ ssh ckad000
18
charming-macaw namespace to use a NetworkPolicy allowing the Pod to send and receive traffic only to and from the Pods front and db.
All required NetworkPolicies have already been created.
You must not create, modify or delete any NetworkPolicy while working on this task. You may only use existing NetworkPolicies .
正解:
See the Explanation below for complete solution.
Explanation:
ssh ckad00018
You cannot create/modify/delete any NetworkPolicy.
So the only way to make the existing policies "take effect" is to ensure the right Pods have the labels
/selectors those policies expect.
The task: in namespace charming-macaw, configure things so the target Pod can send + receive traffic ONLY to/from Pods front and db.
1) Inspect what NetworkPolicies already exist (don't change them)
kubectl -n charming-macaw get netpol
kubectl -n charming-macaw get netpol -o wide
Dump them to see the selectors they use:
kubectl -n charming-macaw get netpol -o yaml
You are looking for policies that:
* select the restricted pod via spec.podSelector
* and allow ingress/egress only with selectors that match front and db
* often there's also a "default deny" policy.
2) Identify the Pods and their current labels
kubectl -n charming-macaw get pods -o wide
kubectl -n charming-macaw get pods --show-labels
Specifically inspect labels for front and db:
kubectl -n charming-macaw get pod front --show-labels
kubectl -n charming-macaw get pod db --show-labels
(If they're Deployments instead of single Pods, do:)
kubectl -n charming-macaw get deploy --show-labels
kubectl -n charming-macaw get pods -l app=front --show-labels
kubectl -n charming-macaw get pods -l app=db --show-labels
3) Figure out which pod is "the Pod" to restrict
Usually there's a third pod (e.g., backend, api, app) besides front and db.
List pods again and identify the "other" one:
kubectl -n charming-macaw get pods
Let's assume the pod to restrict is called app (replace as needed):
TARGET=<pod-to-restrict>
4) Match the existing NetworkPolicy selectors by labeling pods (allowed) Because you can't edit NetworkPolicies, you must make labels on Pods (or their controllers) match the policies' selectors.
4.1 Determine the label required on the TARGET pod
From the YAML, find the policy that selects the restricted pod, e.g.:
spec:
podSelector:
matchLabels:
role: restricted
Extract podSelector from each policy quickly:
kubectl -n charming-macaw get netpol -o jsonpath='{range .items[*]}{.metadata.name}{" => "}{.spec.
podSelector}{"\n"}{end}'
Pick the selector that is meant for the restricted pod, then apply it to the TARGET pod (example:
role=restricted):
kubectl -n charming-macaw label pod $TARGET role=restricted --overwrite Best practice (if the pod is managed by a Deployment): label the Deployment template instead, so it persists.
Find the owner:
kubectl -n charming-macaw get pod $TARGET -o jsonpath='{.metadata.ownerReferences[0].kind}{" "}{.
metadata.ownerReferences[0].name}{"\n"}'
If it's a ReplicaSet, find its Deployment:
RS=$(kubectl -n charming-macaw get pod $TARGET -o jsonpath='{.metadata.ownerReferences[0].name}') kubectl -n charming-macaw get rs $RS -o jsonpath='{.metadata.ownerReferences[0].kind}{" "}{.metadata.
ownerReferences[0].name}{"\n"}'
Then label the Deployment (example):
kubectl -n charming-macaw label deploy <DEPLOYMENT_NAME> role=restricted --overwrite
4.2 Ensure front and db match what the allow-rules reference
Look inside the allow policy ingress.from / egress.to. You might see something like:
from:
- podSelector:
matchLabels:
name: front
- podSelector:
matchLabels:
name: db
So you must ensure:
* front pod has name=front
* db pod has name=db
Apply labels (examples-use what the policy expects):
kubectl -n charming-macaw label pod front name=front --overwrite
kubectl -n charming-macaw label pod db name=db --overwrite
Again, if they're Deployments, label the Deployment instead:
kubectl -n charming-macaw label deploy front name=front --overwrite
kubectl -n charming-macaw label deploy db name=db --overwrite
5) Verify the NetworkPolicies now "select" the right pods
Check which labels each pod has now:
kubectl -n charming-macaw get pods --show-labels
Confirm the restricted pod matches the NetPol podSelector:
kubectl -n charming-macaw get netpol <POLICY_NAME> -o jsonpath='{.spec.podSelector}{"\n"}' kubectl -n charming-macaw get pod $TARGET --show-labels
6) Functional verification (quick network tests)
Exec into the restricted pod and try to reach:
* front # allowed
* db # allowed
* anything else # blocked
If busybox has wget:
kubectl -n charming-macaw exec -it $TARGET -- sh -c 'wget
-qO- http://front 2
>/dev/null || true'
kubectl -n charming-macaw exec -it $TARGET -- sh -c 'wget
-qO- http://db 2
>/dev/null || true'
Test something that should be blocked (example: kubernetes service DNS name):
kubectl -n charming-macaw exec -it $TARGET -- sh -c 'wget -qO- https://kubernetes.default.svc 2>/dev/null
|| echo "blocked"'
Also test inbound (from front to target, and from db to target) if the target listens on a port; otherwise inbound testing may be limited.
What you're doing conceptually
* Existing NetPols are already correct.
* Your job is to make pod labels match the NetPol selectors so:
* default deny applies to the target
* allow rules apply only between target # front and target # db
You have a Deployment named 'wordpress-deployment' that runs 3 replicas of a Wordpress container with the image 'wordpress:latest You need to ensure that wnen a new image is pusned to the Docker Hub repository 'my-wordpress-repo/wordpressaatest' , tne Deployment automatically updates to use the new image. Additionally, you need to set up a rolling update strategy where only one pod is updated at a time- The maximum number of unavailable pods at any given time should be 1.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. Update the Deployment YAML.
- Add 'imagePuIIPoIicy: Always' to the container definition to ensure the deployment pulls the latest image from the Docker Hub repository even if a local copy exists.
- Set 'strategy-type: Rollingupdate' to enable a rolling update strategy.
- Configure 'strategy.rollingupdate.maxonavailable: I ' to allow only one pod to be unavailable during the update process.
- Set 'strategy-rollingUpdate.maxSurge: O' to restrict the number of pods added during the update to zero.
You are tasked with designing a multi-container Pod that runs a web application, a database, and a cache server. The application needs to initialize the database before the web server starts. How would you implement this using Kubernetes init containers? Provide a comprehensive YAML configuration for the Pod.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. Define Init Container:
- Create an init container named 'db-initializer' with the following:
- Image: Specify the image containing the script to initialize the database (e.g., 'mydatabase/initializer.latest
- Command: Define the command to execute the initialization script.
- VolumeMounts: Mount any necessary volumes from the main container to the init container.
2. Main Container:
- Create a main container named 'webserver' with the following:
- Image: Specify the web server image (e_g_, 'nginx:latest)_
- Pons: Define any ports exposed by the web server.
- VolumeMounts: Mount any necessary volumes (e.g., data volumes).
3. Define Volumes:
- Define any volumes used by the containers (e.g., 'persistentVolumeClaim' for persistent storage).
4. Pod Specification:
- Create a Pod specification with the following:
- Containers: Include both the 'db-initializer' and 'webserver' containers.
- RestartPolicy: Set to 'Always' to ensure that the Pod restarts if a container fails.
- ImagePullSecrets: Add any necessary image pull secrets.

- The initContainers' section specifies the initialization steps to be executed before the main container starts. - The 'db-initializer' container runs the 'database-initializer-sm script to initialize the database. - The 'volumeMounts' ensure that both the 'db-initializer' and 'webserver containers have access to the same database volume. - The ' persistentVolumeClaim' provides a persistent storage for the database data. Remember: - Replace 'mydatabase/initializer:latest and 'nginx:latest' with your actual container images. - Modify the 'database-initializer.sh' script based on your specific database initialization requirements. - Customize the volumes and volume mounts according to your application's needs.]
You are running a web application within a Kubernetes cluster. The application consists of two pods, each with a resource request of 1CPU core and I GiB of memory. However, you've noticed that the application experiences performance issues during peak traffic hours. To mitigate these issues, you decide to implement resource quotas tor the namespace where the application runs. You want to ensure that the application pods receive adequate resources while preventing other applications from consuming excessive resources. Design and implement a resource quota for the namespace that sets limits for CPU and memory resources.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. Define the Resource Quota:
- Create a YAML file (e.g., resource-quota.yaml') containing the following resource quota configuration:

2. Apply the Resource Quota: - Apply the resource quota to the 'web-app' namespace using the following command: bash kubectl apply -f resource-quota-yaml 3. Verify the Resource Quota: - Check the status of the resource quota using the following command: bash kubectl get resourcequotas -n web-app You should see the 'web-app-quota' listed with its defined limits and requests. 4. Monitor Resource Usage: - Use the 'kubectl describe resourcequota web-app-quota -n web-apps command to monitor the current resource usage within the 'web-apps namespace- This will show you the consumed resources against the defined limits. 5. Adjust the Resource Quota: - If the resource quota is too restrictive or not restrictive enough, you can adjust the values in the 'requests' and 'limits' fields in the 'resource. quota.yaml file and reapply the resource quota using 'kubectl apply'. - The resource quota limits the total amount of resources (CPU and memory) that can be consumed by all pods in the 'web-app' namespace. - The requests' field specifies the total amount of resources that pods in the namespace can request. - The 'limits' field sets a hard limit on the total amount of resources that pods can use, preventing them from exceeding these limits. - This ensures that the web application has access to the required resources while preventing other applications in the namespace from consuming all available resources. ,
You are running a microservices application on Kubernetes, and you need to restrict the communication between your services to specific ports. For example, your 'frontend' service should only be allowed to communicate with the 'backend' service on port 8080. How would you configure this using NetworkPolicy in Kubernetes?
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. Define the NetworkPolicy:
- Create a new YAML file (e.g., 'frontend-network-policy.yaml') to define the network policy.
- Specify the name of the NetworkPolicy and the namespace where it will be applied.
- Include the following elements within the 'spec' section:
- 'podSelector' to target the 'frontend' pods.
- 'ingress' section to define inbound traffic rules.
- 'egress' section to define outbound traffic rules.

2. Apply the NetworkPolicy: - Apply the NetworkPolicy to your cluster using the following command: bash kubectl apply -f frontend-network-policy.yaml 3. Verify the NetworkPolicy: - Use the 'kubectl get networkpolicy' command to list the applied NetworkPolicies and confirm the status. 4. Test the Restrictions: - From a 'frontend' pod, attempt to connect to the 'backend' service on port 8080. - Attempt to connect to other services or ports on the backend or external networks. - Verify that the communication restrictions defined in the NetworkPolicy are working as expected.
You have a Deployment named that runs 3 replicas of a Wordpress container. You need to implement a rolling update strategy that allows for a maximum or two pods to be unavailable at any given time during the update process. Additionally, you want to ensure that the update process is triggered automatically whenever a new image is pushed to the Docker Hub repository 'wordpress/wordpress:latest'.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. IJPdate the Deployment YAMLI
- Update the 'replicas to 2.
- Define 'maxunavailable: 2 and 'maxSurge: O' in the 'strategy.rollingupdate' section to control the rolling update process.
- Configure a 'strategy-type' to 'RollinglJpdate' to trigger a rolling update when the deployment is updated.
- Add a 'spec-template-spec-imagePullPolicy: Always" to ensure that the new image is pulled even if it exists in the pod's local cache.

2. Create the Deployment - Apply the updated YAML file using 'kubectl apply -f wordpress-deploymentyamr 3. Verify the Deployment: - Check the status of the deployment using 'kubectl get deployments wordpress-deployment to confirm the rollout and updated replica count. 4. Trigger the Automatic Update: - Push a new image to the 'wordpress/wordpress:latest' Docker Hub repository. 5. Monitor the Deployment: - Use 'kubectl get pods -l app=wordpress' to monitor the pod updates during the rolling update process. You will observe that two pods are terminated at a time, while two new pods with the updated image are created. 6. Check for Successful Update: - Once the deployment is complete, use 'kubectl describe deployment wordpress-deployment' to see that the 'updatedReplicas' field matches the 'replicas' field, indicating a successful update.
You are building a container image for a Python application that requires several external libraries. You want to ensure that the image is as small as possible while still containing all necessary dependencies. What strategy should you use to optimize the image size? Explain your approach and provide a code example.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
I). Use a multi-stage Dockerfile: This allows you to have separate build and runtime stages. The build stage can include all necessary tools and dependencies for building the application, while the runtime stage only includes the essential components needed to run the application.

2. Minimize the base image: Choose a base image With only the necessary operating system components, tools, and libraries. I-Ising a slim image variant like 'python:3.9-slim' reduces the image Size significantly. 3. Use a lightweight package manager: Employ a lightweight package manager like 'pip' for installing Python dependencies. This helps keep the image lean 4. Optimize dependencies: Analyze your 'requirements.txt' file and remove any unnecessary dependencies or packages. This is crucial for reducing the overall size of the image. 5. Use caching wisely: In the 'Dockerfile', leverage caching by placing 'COPY commands for your application code before 'RUN' commands. This prevents unnecessary rebuilds of the image when only the application code changes. 6. Consider dependency bundling: If your application relies on specific library versions, consider using a tool like 'pip-tools' to lock down dependencies. This avoids issues where updates to external libraries introduce compatibility problems. 7. Remove unnecessary files: After building your image, inspect the image layers and identify any unneeded files. Remove these files using 'docker image prune' to further reduce image size.
You must connect to the correct host . Failure to do so may result in a zero score.
[candidate@base] $ ssh ckad00044
Task:
Update the existing Deployment busybox running in the namespace rapid-goat .
First, change the container name to musl.
Next, change the container image to busybox:musl .
Finally, ensure that the changes to the busybox Deployment, running in the namespace rapid-goat, are rolled out.
正解:
See the Explanation below for complete solution.
Explanation:
0) SSH to the correct host
ssh ckad00044
(Optional sanity)
kubectl config current-context
kubectl get ns | grep rapid-goat
1) Inspect the Deployment and current container name
kubectl -n rapid-goat get deploy busybox
kubectl -n rapid-goat get deploy busybox -o jsonpath='{.spec.template.spec.containers[*].name}{"\n"}' kubectl -n rapid-goat get deploy busybox -o jsonpath='{.spec.template.spec.containers[*].image}{"\n"}' Note the current container name (likely something like busybox). We need to rename it to musl.
2) Edit the Deployment (best for renaming container)
Renaming a container is easiest with edit:
kubectl -n rapid-goat edit deploy busybox
In the editor, find:
spec:
template:
spec:
containers:
- name: <old-name>
image: <old-image>
Change it to:
- name: musl
image: busybox:musl
Save and exit.
3) Ensure the rollout happens and completes
kubectl -n rapid-goat rollout status deploy busybox
4) Verify the new Pod template is correct
Check the Deployment template:
kubectl -n rapid-goat get deploy busybox -o jsonpath='{.spec.template.spec.containers[0].name}{"\n"}{.spec.
template.spec.containers[0].image}{"\n"}'
Check running Pods and the image actually used:
kubectl -n rapid-goat get pods -o wide
POD=$(kubectl -n rapid-goat get pods -l app=busybox -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true) If you don't have that label selector, just pick a pod name from kubectl get pods and:
kubectl -n rapid-goat describe pod <pod-name> | sed -n '/Containers:/,/Conditions:/p'
You have a Kubernetes cluster with a Deployment that runs a critical web application. The application's codebase is in a Git repository, and you want to automatically deploy a new version of the application whenever a new commit is pushed to the 'master branch ot the repository. You need to ensure that the deployment process iS seamless and doesn't result in downtime for the web application.
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
I). Set up a Git repository:
- Create a Git repository on a platform like GitHub, GitLab, or Bitbucket.
- Store your web application's code in this repository
2. Configure a webhook:
- Go to the settings of your Git repository and configure a webhook.
- The webhook URL should point to your Kubernetes clusters API server.
- Set the webhook event to 'push' and the branch to 'master
3. Create a Deployment
- Create a Deployment YAML file with the following configuration:

4. Create a Kubernetes Secret: - Store your Git repository's credentials in a Kubemetes secret - This secret will be used to authenticate the webhook request from your Git repository. 5. Create a Job: - Create a Job YAML file with the following configuration:

6. Apply the resources: - Apply the Deployment, Secret, and Job YAML files to your Kubernetes cluster 7. Test the deployment: - Push a new commit to the 'master' branch of your Git repository. - Observe that the Job runs and updates the Deployment with the new image. - VeriSi that the web application is still accessible during the update process.
You have a web application tnat requires a dedicated sidecar container to manage logging and monitoring. The sidecar container should be deployed alongside every pod of the application. You need to ensure that the sidecar container is always available alongside the application pods, even if the main application container ex;mences failures. Which Kubernetes resource is most suitable for this scenario and wny?
正解:
See the solution below with Step by Step Explanation.
Explanation:
Solution (Step by Step) :
1. Choose DaemonSet The most suitable Kubernetes resource for this scenario is a DaemonSet.
2. Daemonset Functionality: Daemonsets ensure that a pod is running on every node in your cluster. This is ideal tor sidecar containers because they need to be present alongside tne main application pod on each node.
3. Daemonset Benefits:
- Guaranteed Availability: Daemonsets guarantee that the sidecar container is always available on the same node as the main application pod, even if the application pod is restarted or fails.
- Pod Management: DaemonSets manage the lifecycle of the sidecar container, ensuring its availability and resource allocation.
- Node-Level Deployment: Daemonsets deploy pods on all nodes, ensuring consistent functionality across the cluster
4. Implementation Example:

This DaemonSet definition specifies a pod with two containers: the 'logging-sidecar' and 'your-application'. The Slogging-sidecar' is your sidecar container, and 'your-application' represents your main application. - Important: The Daemonset will ensure that a pod with these containers is deployed on every node of your Kubernetes cluster 5. Deployment and Monitoring: - Deployment: Use 'kubectl apply -f logging-sidecar.yamr to deploy the DaemonSet. - Monitoring: Observe the pods created by the Daemonset using 'kubectl get pods'. You should see a pod with the 'logging-sidecar and 'your- application' containers running on each node- 6. Conclusion: - Using a DaemonSet to manage your sidecar container ensures its consistent availability alongside the main application pods, guaranteeing logging and monitoring capabilities even in case of pod failures-,