不想錯過任何事?

通過認證考試的技巧

最新考試新聞和折扣資訊

由我們的專家策劃和更新

是的,請向我發送時事通訊

查看其他面試題

1
參考答案
Well, to solve the problem, they can shift their monolithic code base to a microservice design and then each and every microservices can be considered as a container. So, all these containers can be deployed and orchestrated with the help of Kubernetes.
2
參考答案
K8s or Kubernetes is an open-source platform that is used to automate the deployment and scaling of containerized applications. This platform makes it easy to manage applications in application deployment with various features. We also know this process as orchestration.
職涯加速

考取認證,讓履歷脫穎而出。

數據分析顯示,持有 IT 認證的從業者年薪平均比求職者高出 26%。在 SPOTO,您可以同時備考認證與準備面試,加速職涯成長。

1 100% 通過率
2 2 週題庫練習
3 通過認證考試
3
參考答案
Steps to approach the above problem: 1. Verify that the Nginx Pod is running and healthy. kubectl get pods -o wide kubectl describe pod nginx-web 2. Check the Service and port mapping. Ensure the correct port is exposed and matches the Pod's container port. Check that the Service finds the correct Pods. kubectl describe service nginx-service 3. Check network policies. If a network policy blocks ingress traffic, the Service won't be accessible. kubectl get networkpolicies kubectl describe networkpolicy 4. Verify Ingress and external DNS configuration. kubectl describe ingress nginx-ingress
4
參考答案
The primary parts of Kubernetes Architecture consist of: - The API server is the cluster's central management point, which manages all read and write requests and exposes the Kubernetes API, is the cluster's central management point. - etc is a decentralized key-value store that houses the cluster's configuration information, including the status of individual pods and services. - The daemon known as the controller manager is in charge of executing controllers, which are in charge of keeping the cluster in the desired state. - The scheduler is a daemon that distributes pods among nodes according to resource needs and other limitations. - The kubelet is a daemon that operates on every node and is in charge of notifying the API server of the node's condition and initiating and halting pods. - A daemon called the Kube proxy operates on each node to oversee network connection with pods and services. - The pod is the fundamental Kubernetes deployment unit, and it can hold one or more containers. - The service is a logical metaphor for pods that offer a reliable external destination for pod access. - A cluster's namespace is a method of resource division and organization. - The volume: a means of storing data for pods that can be supported by a range of storage options.
5
參考答案
A Kubetcl is a command-line tool or platform through which you can pass commands to a cluster. Kubectl is the Kubernetes-specific command line tool that lets you communicate and control Kubernetes clusters. With Kubectl, you can deploy applications, inspect and manage cluster resources, view logs, and debug your applications running on Kubernetes. Kubectl can also be used to manage remote and cloud clusters such as GKE.
6
參考答案
The sensitive information stored in a cluster can be safeguarded via using several encryption and access restrictions techniques. Usually this data is stored in a rest or transit mode to secure it from unauthorized access.
7
參考答案
Workload disruptions can be prevented by configuring correct Pod Disruption Budgets (PDBs). PDBs specify how many Pod replicas can become unavailable while Pods are updating due to a new Deployment rollout. Pod disruptions may also occur due to maintenance operations such as upgrading Kubernetes or replacing a Node. You can mitigate the impacts of these events by ensuring you manually drain affected Nodes first. This enables Kubernetes to reschedule Pods onto other available Nodes gracefully.
8
參考答案
The Kubernetes control plane is the brain of the cluster. It runs as a group of control plane components, including the API server, scheduler, and controller manager. In production clusters, these components run across multiple nodes to improve reliability and avoid a single point of failure. Everything flows through the control plane, which is why understanding Kubernetes architecture starts here. Imagine you deploy an online store. You package the application into a container and push it to the cluster. The control plane schedules the pods onto worker nodes. If traffic increases, the deployment scales. If a node fails, it reschedules the workload to another node.
9
參考答案
Pronounced as "ett-see-dee," it is written in Go programming language and used to coordinate distributed work and key-value pairs. It is an open-source distributed key-value store that holds and manages the critical information distributed systems need to keep running. It is built on the Raft consensus algorithm, which ensures datastore consistency across all the nodes.
10
參考答案
Kubernetes simplifies container deployment by automating the distribution and scheduling of containers across a cluster of machines, ensuring efficient use of resources and maintaining the desired state of applications.
11
參考答案
Add tls and secretName entries. spec: tls: - hosts: - some_app.com secretName: someapp-secret-tls
12
參考答案
A Pod is the smallest deployable unit in Kubernetes, representing a single instance of a running process within a cluster. It can contain one or more containers that share network and storage resources.
13
參考答案
Zero-downtime deployments are achievable in Kubernetes using strategies like rolling updates, which gradually replace old pods with new ones, ensuring service availability. Properly configured readiness and liveness probes help manage the application state during deployment, avoiding downtime. Blue/green deployment and canary releases also contribute to maintaining availability by allowing testing of new versions alongside stable production versions before full rollout, minimizing the impact of potential errors.
14
參考答案
Use Persistent Volumes (PV) and Persistent Volume Claims (PVC) to manage storage independently of pod lifecycle. Proper storage management ensures data persistence across pod restarts and failures, simplifying troubleshooting related to stateful applications.
15
參考答案
StatefulSets provide three critical guarantees that regular Deployments don't: StatefulSet Controller ↓ Ordered Pod Creation (pod-0, pod-1, pod-2) ↓ Stable Network Identity (predictable DNS names) ↓ Persistent Storage Binding (each pod gets its own PVC) Why StatefulSet Pods Fail to Recreate 1. PVC Binding Issues StatefulSets create a unique PVC for each pod replica. When a pod is deleted, the PVC remains (by design) to preserve data. However, several issues can prevent the new pod from binding to its existing PVC: - Storage Class problems: The storage class used by the PVC might not be available - Volume affinity conflicts: The PV might be bound to a specific zone/node that's unavailable - PVC stuck in terminating state: Finalizers preventing cleanup 2. Ordinal Dependencies StatefulSets maintain strict ordering. If pod-0 is unhealthy, pod-1 won't be created or updated. This dependency chain can cause cascading failures. 3. Network Identity Conflicts Each StatefulSet pod gets a predictable DNS name (pod-0.service-name.namespace.svc.cluster.local). If the underlying service or DNS configuration has issues, pod recreation fails. Diagnostic Approach Understanding the Problem Scope First, determine whether this is: - A single pod issue - A StatefulSet controller problem - A cluster-wide storage issue - A network/DNS problem Key Investigation Points - PVC Status Analysis - Is the PVC bound to a PV? - Is the PV available and in the correct zone? - Are there finalizer issues preventing cleanup? - Pod Scheduling Constraints - Node affinity requirements - Resource availability on target nodes - Taints and tolerations - StatefulSet Controller Health - Controller manager logs - StatefulSet status and conditions - Event timeline analysis Recovery Strategy Without Data Loss Phase 1: Assess Data Safety Before any recovery actions, ensure data safety: - Verify PV still contains data - Check storage backend health - Confirm backup availability Phase 2: Identify Blocking Issues - Node availability and readiness - Storage class and provisioner status - Network policies affecting pod communication Phase 3: Systematic Recovery Force delete stuck pod → Clear finalizers if needed → Allow StatefulSet controller to recreate → Verify PVC rebinding → Validate data integrity The key principle is working with Kubernetes' natural healing mechanisms rather than forcing manual interventions that might cause data loss. Storage Architecture Considerations Modern StatefulSet deployments should consider: Regional Storage: Using storage classes that replicate across zones Backup Integration: Automated snapshots before major operations Monitoring: PV/PVC health monitoring and alerting Disaster Recovery: Cross-region backup and restore procedures
16
參考答案
Docker is a tool for building, distributing, and running individual containers. Kubernetes is a system for managing and orchestrating clusters of containers, regardless of which runtime is used (though Docker is common).
17
參考答案
A ReplicaSet ensures that a specified number of pod replicas are running at any given time. However, Deployments manage ReplicaSets and provide declarative updates to applications along with features like rolling updates and rollbacks.
18
參考答案
A senior engineer should demonstrate awareness of Kubernetes' evolving landscape, mentioning resources like the official Kubernetes blog, SIG meetings, KEPs (Kubernetes Enhancement Proposals), and community forums. They might also discuss significant changes in recent releases or upcoming features that could impact how clusters are managed. These questions are designed to uncover a candidate's depth of knowledge and experience with Kubernetes, going beyond basic concepts to explore their ability to architect, optimize, and troubleshoot complex Kubernetes environments.
19
參考答案
A Persistent Volume (PV) in Kubernetes is a storage resource provisioned by an administrator or dynamically created through a StorageClass, used to persist data beyond the lifecycle of a Pod.
20
參考答案
Top features of Kubernetes include:
21
參考答案
Kubernetes cluster management involves configuring and maintaining the Kubernetes control plane, worker nodes, and network settings.
22
參考答案
Replication controllers are great for pods that live longer. We rely on replication controller to launch pods whenever a host restarts However, if there are multiple hosts, a replication controller can be rescheduled to the other host. To deal with this issue of unreliability from replication controller, we use ReplicaSet.
23
參考答案
The Gateway API is the modern evolution of Kubernetes networking that aims to replace standard Ingress. While Ingress was designed for simple HTTP routing, it became limited and fragmented as clusters grew more complex. The Gateway API improves this by: - Role-oriented design: It separates the definition of the Gateway (managed by infrastructure engineers) from the Routes (managed by application developers). - Better support: It has native support for advanced traffic features like traffic splitting (A/B testing), header matching, and multi-cluster networking without needing complex custom annotations.
24
參考答案
Bonus question for practice. Debug by checking pod logs, describe the pod for events, verify container configuration, and check for resource constraints or application errors.
25
參考答案
Kubernetes secrets are a secure way to store sensitive information, such as passwords, API keys, and other authentication tokens, used by applications running in a Kubernetes cluster.
26
參考答案
Kubernetes adds significant operational overhead. If you're running a small team with a few simple services, Docker Compose or a managed service like AWS ECS or Google Cloud Run might be a better fit. Kubernetes shines when you need to manage many services at scale, automate complex deployments, or provide self-service infrastructure for multiple teams. Not every workload needs Kubernetes, and interviewers ask this to see whether you understand trade-offs. Our Introduction to Kubernetes tutorial covers this exact decision point with a practical comparison.
27
參考答案
Kubelet provides data and this data runs on each node. But these data needs are needed to be aggregators. This is where the Heapster comes into play and aggregates all data that are supplied by the Kubelet. Now this container is generally supported by the cluster of Kubernetes and it runs like a pod. Then it finds all other clusters and examines the information used from the nodes of Kubernetes. This is done with the help of a non-machine agent.
28
參考答案
A Persistent Volume (PV) is a piece of storage in the cluster. A Persistent Volume Claim (PVC) is a request for storage by a user. Kubernetes binds a PVC to an available PV that meets the criteria.
29
參考答案
Dynamic volume provisioning is a concept primarily associated with cloud computing and storage management. It refers to the automated and on-demand allocation of storage resources as needed by applications or services. In dynamic volume provisioning, storage volumes are created or expanded dynamically, without requiring manual intervention or pre-allocated storage space. This approach ensures that applications have access to the right amount of storage capacity precisely when they need it, optimising resource utilisation and minimising the risk of running out of storage. Dynamic volume provisioning is especially valuable in cloud environments where workloads can fluctuate in size and demand, allowing for greater flexibility, scalability, and cost-effectiveness in managing storage resources.
30
參考答案
Kubernetes ConfigMaps are used to store non-sensitive configuration data as key-value pairs. They allow you to decouple configuration artifacts from image content, making applications easier to manage and portable. - Creating ConfigMaps: You can create them from literal values, files, or directories. - Using ConfigMaps: Inject configuration data into Pods as environment variables, command-line arguments, or configuration files. Example of creating a ConfigMap: kubectl create configmap myconfig --from-literal=key1=value1 --from-literal=key2=value2 Example ConfigMap YAML definition: apiVersion: v1 kind: ConfigMap metadata: name: myconfig data: key1: value1 key2: value2 Using a ConfigMap in a Pod: ```yaml apiVersion: v1 kind: Pod metadata: name: configmap-pod spec: containers: - name: mycontainer image: nginx env: - name: KEY1 valueFrom: configMapKeyRef: name: myconfig key: key1 - name: KEY2 valueFrom: configMapKeyRef: name: myconfig key: key2 Applying the Pod configuration: ```bash kubectl apply -f configmap-pod.yaml
31
參考答案
There are a number of recommended security measures for Kubernetes, including implementing third-party authentication and authorization tools, using network segmentation to restrict access to sensitive data, and maintaining regular monitoring and auditing of the cluster. Another key recommendation is to use role-based access control (RBAC) to limit access to the Kubernetes API. This ensures that only authorized users can make changes to the system and introduces an additional layer of protection against potential vulnerabilities or attacks. Node isolation is also worth mentioning. It is a process of isolating individual nodes in a Kubernetes cluster so that each node only has access to its own resources. This process is used to improve the security and performance of Kubernetes clusters by preventing malicious activity on one node from affecting other nodes. Node isolation can be achieved through a variety of means, such as using a firewall to block network traffic between nodes, or using software-defined networking to segment node traffic. By isolating nodes, Kubernetes administrators can ensure that each node in a cluster is used only for its intended purpose and that unauthorized access to resources is prevented. Other best practices for securing Kubernetes include: – Restricting access to the Kubernetes API to authorized users only – Using network firewalls to restrict access to the Kubernetes nodes from unauthorized users – Using intrusion detection/prevention systems to detect and prevent unauthorized access to the Kubernetes nodes – Using encryption for communications between the nodes and pods in the cluster – Limiting which IP addresses have access to cluster resources – Implementing regular vulnerability assessments. Ultimately, incorporating these types of security measures into your Kubernetes deployment will help ensure the safety and integrity of your system.
32
參考答案
It is one of the features in Kubernetes that allows users to express the rule about pod replacement based on labels allocated to nodes in the Kubernetes cluster.
33
參考答案
The API Server acts as the central communication point in Kubernetes. It processes requests from users and internal components, validates them, and updates etcd.
34
參考答案
aws eks update-kubeconfig --name --region - Uses IAM credentials to get the cluster endpoint and authentication details.
35
參考答案
No, they don't. The Kubernetes components, like kubelet, will take up resources on your nodes, and you'll still need more capacity for the node to do any work. In a larger cluster, it often makes sense to create a mix of different instance sizes. That way, pods that require a lot of memory with intensive compute workloads can be scheduled by Kubernetes on large nodes, and smaller nodes can handle smaller pods.
36
參考答案
- Microservices architectures (e.g., REST APIs, GraphQL services) - Event-driven applications (Kafka consumers, message queues) - Machine learning workloads (TensorFlow Serving, Jupyter notebooks) - CI/CD pipelines (GitHub Actions runners, Jenkins agents) - Data processing workloads (Spark, Flink, Airflow) - Multi-cloud/hybrid workloads needing portability
37
參考答案
A Namespace is a way to logically partition resources within a single cluster. You'd use them to separate teams, environments (dev vs. staging), or to apply different resource quotas and access controls. # Create a namespace kubectl create namespace dev # Deploy a pod into that namespace kubectl run nginx --image=nginx --namespace=dev # List pods in that namespace kubectl get pods --namespace=dev By default, Kubernetes provides the default , kube-node-lease , kube-system , and kube-public Namespaces. Most production clusters create additional ones to organize workloads. Our tutorial on Kubernetes Services, Rolling Updates, and Namespaces walks through Namespace setup with a realistic data pipeline example.
38
參考答案
Follow the 4C security model to secure a Kubernetes cluster: - Cloud provider security: Use IAM roles and firewall rules. - Cluster security: Enable RBAC, audit logs, and API server security. - Container security: Scan images and use non-root users. - Code security: Implement secrets management and use network policies.
39
參考答案
Kubernetes Configuration Management is the automated management of configuration files and settings across a Kubernetes cluster.
40
參考答案
Main pod types in Kubernetes include regular pods, init pods, and mirror pods based on their lifecycle and creation.
41
參考答案
A node the smallest unit of hardware. It defines a single machine in a cluster that can be a virtual machine from a cloud provider or physical machine in the data center. Every machine available in the Kubernetes cluster can substitute other machines.
42
參考答案
Kubernetes architecture comprises several key components. The Control Plane consists of the API Server, Controller Manager, and Scheduler, while the Node components include Kubelet, Container Runtime, and Kube Proxy. Understanding the interaction and role of each component is crucial for effective Kubernetes management.
43
參考答案
The Kube proxy is a component of worker nodes. The Kube proxy goes through each node and runs in them. It helps in TCP/UDP packet forwarding transversely back-end network services. Eventually, the proxy of the network or network proxy is configured in the Kubernetes API in every single node. Finally, the cluster IPs and ports are supplied by the compatible environment variables of docker. These clusters are opened by the proxy.
44
參考答案
Kubernetes supports rolling updates, allowing for seamless deployment of new versions without downtime. During a rolling update, Pods are gradually replaced with new ones, ensuring a smooth transition. In case of issues, Kubernetes provides automated rollbacks, reverting to the previous version and maintaining application stability.
45
參考答案
Best practices for Kubernetes cluster security include: Implementing Role-Based Access Control (RBAC) Using network policies to control traffic within the cluster Restricting external access to cluster components and API servers Implementing secured node access and communication between nodes in the cluster
46
參考答案
The cloud controller manager lets you link the cluster to the cloud provider's API. Cloud-controller manager allows cloud vendors to evolve independently from the core Kubernetes code by abstracting the provider-specific code. It abstracts provider-specific code and functionality, which allows cloud vendors to develop and maintain their code independently from the core Kubernetes code. Using the CCM, cloud-specific operations such as creating and managing load balancers, block storage volumes, and cloud-specific networking resources can be performed seamlessly within a Kubernetes cluster. This allows users to take advantage of the benefits of both Kubernetes and the cloud provider while minimizing the potential for compatibility issues.
47
參考答案
In Kubernetes, services are an abstract way to expose an application running on a set of pods as a network service. They enable network access to a set of pods in Kubernetes, and they provide a consistent way to access the application, regardless of the individual pods' IP addresses or their scheduling. Services can be exposed internally or externally, and they can also be used for load balancing and service discovery within the Kubernetes cluster.
48
參考答案
Pods and containers are two components of a Kubernetes architecture. Pods are composed of one or more containers that share an IP address and port space. This means that containers within a pod can communicate with each other without going through a network. Pods also provide a way to deploy applications on a cluster in a replicable and scalable way. Containers, on the other hand, are isolated from each other and do not share an IP address. This isolation provides a higher level of security as each container can only be accessed by its own process. In addition, containers have their own file system, which means that they can be used to package up an application so that it can be run in different environments.
49
參考答案
We can upgrade the Kubernetes version in a cluster by following the official upgrade guides provided by the Kubernetes documentation, which typically involve upgrading the control plane components first followed by the worker nodes, and ensuring compatibility with the applications and add-ons.
50
參考答案
Sidecar containers extend the functionality of the main container, such as logging, monitoring, or handling network traffic in a service mesh.
51
參考答案
Both are container orchestration tools, but they cater to different scales and complexities. Docker Swarm is native to Docker, making it easy to set up but limited for enterprise use. Kubernetes offers robust auto-healing and scaling for massive microservice architectures. | Feature | Kubernetes (K8s) | Docker Swarm | |---| | Setup & Complexity | High learning curve, complex setup. | Fast setup, easy to learn. | | Scalability | Extremely high (ideal for massive clusters). | Good, but struggles at high scale. | | Auto-scaling | Built-in horizontal pod scaling (HPA). | Not natively supported. | | Load Balancing | Requires manual Service/Ingress configuration. | Built-in automatic load balancing. |
52
參考答案
- Enable encryption at rest with AWS KMS via EKS configuration. - Use TLS for in-transit encryption. - Apply fine-grained access control via RBAC. - Use External Secrets Operator to sync from AWS Secrets Manager or Parameter Store.
53
參考答案
A Pod Disruption Budget (PDB) is a Kubernetes resource that allows you to set policies on how many Pods of a particular ReplicaSet or Deployment can be simultaneously unavailable during voluntary disruptions. Voluntary disruptions can occur during planned maintenance, scaling events, or other administrative actions. The main purpose of a Pod Disruption Budget is to ensure high availability and reliability of applications running in a Kubernetes cluster while allowing for necessary maintenance and updates. By setting a PDB, you define the maximum tolerable disruption to a group of Pods, ensuring that a minimum number of replicas remain available and operational at all times. A typical use case for PDB is during rolling updates or scaling events. When you update a deployment or scale it up or down, Kubernetes will try to ensure that the disruption does not exceed the defined PDB. This prevents scenarios where all instances of an application are taken down simultaneously, leading to service outages or degraded performance. Here's how a Pod Disruption Budget is defined in a Kubernetes manifest: ```yaml apiVersion: policy/v1beta1 kind: PodDisruptionBudget metadata: name: example-pdb spec: selector: matchLabels: app: example-app maxUnavailable: 1 ``` In this example, we create a Pod Disruption Budget named "example-pdb" for Pods labeled with `app: example-app`. The `maxUnavailable` parameter is set to 1, meaning that only one Pod can be unavailable at any time due to voluntary disruptions. It's important to note that a PDB does not prevent involuntary disruptions caused by node failures or other unforeseen issues. Instead, it focuses on controlling voluntary disruptions to maintain application availability during planned events. PDBs are particularly useful for applications that require a certain level of redundancy or have strict availability requirements.
54
參考答案
The Horizontal Pod Autoscaler (HPA) automatically scales the number of Pod replicas in a Deployment, ReplicaSet, or StatefulSet based on observed metrics, such as CPU utilization or custom metrics. It increases the number of Pods to handle increased load and decreases them when the load subsides, optimizing resource usage. apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: webserver-mem-hpa spec: maxReplicas: 5 minReplicas: 1 scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: webserver metrics: - type: Resource resource: name: memory target: type: Utilization averageValue: 2Mi
55
參考答案
The agent on each worker node that ensures containers described in Pod specs are running.
56
參考答案
A node is a worker machine in Kubernetes that runs containerized applications.
57
參考答案
Master node in Kubernetes manages the state of the cluster, scheduling applications, and maintaining deployments as defined. It includes components like the kube-apiserver, kube-scheduler, etcd.
58
參考答案
Role-Based Access Control (RBAC) in Kubernetes lets you define who can do what within your cluster. It's essential for securing resources and delegating responsibilities. Step-by-Step Setup - Define User Groups and Access Levels - Choose an Authentication Method - Create Roles or ClusterRoles - Bind Roles to Users or Groups
59
參考答案
An init container is a type of container in Kubernetes that runs before the main application containers in a pod. The purpose of an init container is to perform initialization tasks or setup procedures that are not present in the application container images. Examples of tasks that an init container might perform include downloading configuration files, setting up a network connection, or initializing a database schema.
60
參考答案
We can get more details regarding the pod using the below command: kubectl describe pod -n This command can provide details such as the IP of the node where the pod has been assigned, the IP of the pod, service endpoints, the status of the pod, the image used for running the pod, volumes mounted to the pod, and resource specifications of the pod, etc.
61
參考答案
Kubernetes continuously checks the health of nodes using the Node Controller. If a node fails, the Replication Controller notices that pods are down and creates new ones on other available nodes, ensuring the application's availability.
62
參考答案
The Container Storage Interface (CSI) is the standard to establish device-independent relationships across block and file storage systems and containerized workloads. In essence, CSI allows storage interfaces to be declared to be implemented by containers. Key Components in Kubernetes Storage - PersistentVolume (PV): Represents a piece of storage in the cluster, provisioned manually or dynamically. - PersistentVolumeClaim (PVC): A request for storage by a user or application. - StorageClass: Defines the type of storage (e.g., SSD, HDD, encrypted) and links to a CSI driver for dynamic provisioning.
63
參考答案
The company can do well with something that offers scale-out capability, agility, and the DevOps practice to the cloud-based applications. Kubernetes, in this situation, can enable the customization of the scheduling architecture and support multiple container formats. This results in greater efficiency as well as provides support for various container networking solutions and container storage.
64
參考答案
The kube-scheduler is a control plane component that watches for newly created Pods with no assigned Node. It selects a Node for the Pod to run on based on factors like resource requirements, affinity/anti-affinity, and taints/tolerations.
65
參考答案
A Kubernetes Operator is a method of packaging, deploying, and managing a Kubernetes application. Operators extend the Kubernetes API with custom resources and controllers. They automate routine tasks such as backups, scaling, upgrades, and configuration management. Operators are particularly useful for managing complex stateful applications like databases.
66
參考答案
Following are the security measure of this platform - - Role-Based Access Control (RBAC) - Network Policies - Pod Security Policies - Secrets management
67
參考答案
Core Concepts: Resource Quotas and Limit Ranges help define the upper limits of resources that each object can consume.
68
參考答案
A Kubernetes cluster consists of a set of node machines for running containerized applications. It includes at least one master node and multiple worker nodes that host the pods.
69
參考答案
We can scale a Deployment by updating its replica count using the kubectl scale command or by modifying the replicas field in the Deployment manifest.
70
參考答案
An init container is a container that Kubernetes runs before any other containers in the pod are created. You can use an init container to implement initialization behavior that other pods will use. The example below shows how to create an init container that waits for a database service to come online before it creates the container that will use the database. apiVersion: v1 kind: Pod metadata: name: myapp-pod labels: app: myapp spec: containers: - name: myapp-container image: busybox:1.31 command: ['sh', '-c', 'echo The app is running! && sleep 3600'] initContainers: - name: init-myservice image: busybox:1.31 command: ['sh', '-c', 'until nslookup redis-master; do echo waiting for redis-master; sleep 2; done;'] |
71
參考答案
Kubernetes is a platform for managing containers at scale, while Docker itself is a container technology that can be used by Kubernetes. A container infrastructure, such as Docker, allows apps to be packaged into lightweight, portable, and self-sufficient units. Kubernetes is a platform for managing and orchestrating containers at scale. Along with Kubernetes, Docker gives you the ability to deploy and manage applications at large scales.
72
參考答案
Kubernetes follows a master-worker node architecture: 1. Control Plane (Master Node): - API Server: The front end of Kubernetes, handling all requests. - Controller Manager: Ensures desired state by managing controllers (e.g., replication, node health). - Scheduler: Assigns pods to nodes based on resource availability and constraints. - etcd: A distributed key-value store that holds cluster state and configurations. 2. Worker Nodes: - Kubelet: Communicates with the API server, ensuring pods run as expected. - Container Runtime: Runs containers (e.g., Docker, containerd). - Kube Proxy: Manages networking and routes traffic to pods. This architecture ensures scalability, self-healing, and automation, making Kubernetes a resilient platform.
73
參考答案
Pod Affinity is a feature that influences the scheduling of Pods to ensure they are co-located or spread apart based on node labels or other conditions.
74
參考答案
Following are the common features K8s provides - - Self-healing - Rolling updates - Ingress controllers - Health checks - Replicated - Daemonsets - Statefulsets
75
參考答案
Central to Kubernetes resource management are requests and limits. The interviewer is checking that you understand how Kubernetes decides where to place pods and what happens when a container tries to use more resources than it should.
76
參考答案
Etcd is a distributed key-value store that stores the configuration data of a Kubernetes cluster. It is primarily used to store the state of the cluster and provides a reliable source of truth for cluster consistency. In a production environment, it is recommended to have an etcd cluster with a minimum of three nodes for high availability.
77
參考答案
The controller manager is a daemon used for garbage collection, core control loops, and namespace creation. It enables the running of more than one process on the master node.
78
參考答案
A ConfigMap is a Kubernetes resource used to store non-confidential configuration data in key-value pairs. ConfigMaps allow you to decouple configuration artifacts from image content, making applications more portable. ConfigMaps can be injected into Pods as environment variables, command-line arguments, or configuration files.
79
參考答案
Docker is a container runtime, which is a software that runs containerized applications. When Kubernetes schedules a pod to a node, the kubelet running on that node instructs Docker to launch the containers.
80
參考答案
Bonus question for practice. The role of etcd in Kubernetes is as a distributed key-value store that holds cluster state and configurations. It ensures data consistency through consensus algorithms like Raft.
81
參考答案
A Kubernetes secret is an object used to store sensitive information, such as a password or API key. A configuration map, on the other hand, is used to store configuration data that a pod or container can consume.
82
參考答案
Container orchestration is the process of automating container lifecycle management—deploying, scaling, networking, and ensuring high availability.
83
參考答案
This requires a declarative Deployment YAML that utilizes a multi-container pod pattern. apiVersion: apps/v1 kind: Deployment metadata: name: php-nginx-app spec: replicas: 3 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: nginx image: nginx:latest ports: - containerPort: 80 - name: php-fpm image: php:8.1-fpm This file specifies replicas: 3 for high availability. The containers block deploys both an Nginx web server and a PHP-FPM processor within the exact same Pod, allowing them to communicate seamlessly over localhost.
84
參考答案
Different types of controller managers in Kubernetes are:
85
參考答案
A controller is a loop that watches the current state of a resource and works to bring it in line with the desired state. This is the core pattern behind how Kubernetes operates. Kubernetes ships with many built-in controllers. For example: - The Deployment controller watches Deployment resources and ensures the correct number of ReplicaSets and pods exist, handling rollouts and rollbacks. - The ReplicaSet controller ensures the right number of pod replicas are running at any given time. - The Job controller manages pods that are expected to run to completion and tracks whether they succeeded or failed. Each of these follows the same pattern: observe the desired state, compare it to what is actually running, and take action to reconcile any differences.
86
參考答案
Horizontal Pod Autoscaler (HPA) automatically adjusts the number of Pods in a deployment, replica set, or stateful set based on observed CPU utilization or other custom metrics. The HPA periodically checks the metrics and, based on the configured thresholds, increases or decreases the number of Pods to match the desired performance. HPA can be configured using YAML or kubectl commands.
87
參考答案
Kubernetes provides built-in mechanisms for rolling updates and rollbacks to ensure zero-downtime deployments: - Rolling updates: Gradually replaces old Pods with new ones. This ensures that the application remains available during the update process. Deployments and StatefulSets support rolling updates. - Rollbacks: Revert to previous versions if the new deployment is problematic. Kubernetes retains the history of previous ReplicaSets for deployments, making it possible to rollback. Commands for rolling updates and rollbacks: kubectl set image deployment/my-deployment my-container=my-image:2.0 kubectl rollout status deployment/my-deployment kubectl rollout undo deployment/my-deployment Configuring rolling update strategies in a Deployment: strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1
88
參考答案
This question often comes in the form of "how would you run a service on every node in the cluster without using a Deployment?" If you hear that phrasing, the answer is a DaemonSet. A DaemonSet ensures that a copy of a specific pod runs on every node in the cluster (or a defined subset of nodes). When a new node is added to the cluster, the DaemonSet automatically schedules a pod on it. When a node is removed, that pod is cleaned up. This makes DaemonSets the right choice for workloads that need to be present everywhere, such as: - Log collectors like Fluentd or Filebeat that need to gather logs from every node. - Monitoring agents, such as a Prometheus node exporter, need to report metrics from each machine. - Network plugins such as the CNI components which must be running on every node for pod networking to function. The key difference from a Deployment is intent. A Deployment lets you say "run N replicas somewhere in the cluster," and the scheduler decides where. A DaemonSet says, "run exactly one replica on every eligible node."
89
參考答案
In Kubernetes, a job object is used to run a specific task to completion or a certain number of times. It's ideal for tasks that are rather short and encapsulate work that isn't part of the ongoing application processes. - Pod Management: Jobs create one or more Pods and manage their lifecycle, ensuring successful completion. - Completions: You can specify the number of successful completions, especially useful for batch tasks. - Parallelism: Control how many Pods run concurrently. This feature allows for efficient management of resources. - Pod Cleanup: After the task has been completed, Jobs ensure that related Pods are terminated. They might also garbage collect completed Jobs, depending on your settings. - Auto-Restart: Jobs do not restart by default if successful. They can be configured to restart on failure. - Serial Jobs: Ensure tasks are completed exactly once. - Parallel Jobs: Suitable for tasks where some level of parallel processing can be beneficial for performance. - Work Queues: Suitable for tasks where a specific number of parallel tasks is defined and managed. - Data Processing: For processing a batch of records or data sets. For example, a tech company might use it in a data pipeline to process thousands of records in chunks. - Clean-up Tasks: For periodic clean-up, such as an e-commerce site cleaning up expired user data. - Software Compilation: Useful in CI/CD pipelines to parallelize software builds. - Cron Jobs: For scheduling recurring batch processes, such as taking database backups nightly. - Metering or Accounting: Useful for counting or tallying records, possibly in near-real-time. - Health Checks: Occasionally, when more sophisticated health checks are needed, for tasks perhaps beyond the remit of a Liveness and Readiness check. - Resource Acquisition: For occasional resource acquisition tasks – imagine a scenario where a system occasionally scales on demand and requires a specific number of resources at run-time.
90
參考答案
The programming skills are important for Kubernetes developers for writing scripts, developing applications,and integrating systems effectively in a Kubernetes environment. Programming also helps in customizing Kubernetes components and developing operators that automate complex operations.
91
參考答案
To remove a specific Pod from your cluster, you use the kubectl delete command followed by the resource type and name. kubectl delete pod my-pod-name Important Note: If this Pod is managed by a higher-level controller (like a Deployment or ReplicaSet), Kubernetes will immediately notice the desired state has drifted. It will automatically spin up a brand-new Pod to replace the deleted one. If your goal is to permanently eliminate the application, you must delete the parent Deployment itself (kubectl delete deployment my-deployment), which subsequently terminates all associated Pods.
92
參考答案
A Network Policy defines how Pods communicate with each other and with external endpoints, acting as a firewall at Layer 3/4 (IP and port level). By default, all Pods can talk to each other freely, but applying Network Policies enables a zero-trust model, restricting traffic based on defined rules. Role in the Kubernetes Networking Stack - Services handle Layer 4 connectivity and internal load balancing. - Ingress manages Layer 7 routing for external HTTP/S traffic. - Network Policies enforce security filtering at the IP/port level, independent of Services and Ingress. This layered architecture allows for clear separation of concerns: - Developers manage Service definitions. - Platform teams configure Ingress routing. - Security teams enforce communication boundaries with Network Policies.
93
參考答案
A number of micro-services are installed in the container of an application. Without the micro-services, the application can't perform specific functions. The containers that contain the micro-services can only work when they communicate with each other. Here inter container communication is necessary to perform certain activities in the application. In such conditions, the container orchestration tool comes into play. The container orchestration basically synchronizes all the containers containing micro-services.
94
參考答案
The Kubelet is an agent that runs on each node in the Kubernetes cluster. It ensures that containers are running in Pods by interacting with the container runtime (e.g., Docker, containerd) and the Kubernetes API server. The Kubelet monitors the state of Pods and, if necessary, ensures that they are started, stopped, or restarted based on the desired state provided by the cluster's control plane.
95
參考答案
Resource Quotas in Kubernetes allow administrators to manage resource consumption across namespaces. They ensure that namespaces do not exceed a specified amount of CPU, memory, and other resources. Resource Quotas can limit: - Pod count: Maximum number of Pods. - CPU and memory: Maximum aggregate CPU and memory. - PersistentVolumeClaims: Number and size of persistent volumes. - Custom resources: Defined in CustomResourceDefinitions. Example configuration for a ResourceQuota: ```yaml apiVersion: v1 kind: ResourceQuota metadata: name: quota
96
參考答案
This would often come phrased as "if you wanted to ensure that a certain number of pods are always available during maintenance or voluntary disruptions, how would you do it?" A Pod Disruption Budget (PDB) lets you tell Kubernetes the minimum number of pods in a group that must remain available at any given time during voluntary disruptions. Voluntary disruptions include things like node drains, cluster upgrades, or autoscaler scale-downs. They do not cover involuntary disruptions like hardware failures or kernel crashes. You define a PDB by specifying either a minAvailable or maxUnavailable value alongside a label selector that matches the pods you want to protect. For example, if you have 5 replicas of a service and set minAvailable: 3, Kubernetes will block any voluntary disruption that would bring the available count below 3. This is particularly important in production environments where you are running rolling cluster upgrades or need to drain nodes for maintenance.
97
參考答案
A Service Mesh is a dedicated infrastructure layer designed to manage service-to-service communication within a Kubernetes cluster. Service Meshes provide authentication, authorization, and observability features for distributed systems.
98
參考答案
Custom controllers that extend Kubernetes to manage complex applications.
99
參考答案
Blue/green deployment in Kubernetes involves running two identical environments (blue and green), only one of which serves live traffic at a time. This strategy enables testing in the green environment while the blue handles live traffic, switching traffic to green once it's verified stable, reducing deployment risk and downtime.
100
參考答案
- EKS with Fargate + EC2 node groups (for flexibility). - Multi-AZ worker node groups. - IAM Roles for Service Accounts (IRSA) for fine-grained IAM. - Istio/Linkerd for service mesh and mTLS. - External Secrets Operator with AWS Secrets Manager. - Calico for NetworkPolicies. - ArgoCD for GitOps, Terraform for infrastructure as code. - CIS benchmarks, Pod Security Standards, and OPA/Gatekeeper for policy enforcement. - Prometheus, Loki, and Grafana, with CloudWatch integration for observability.
101
參考答案
A Kubernetes deployment manages a set of identical replicas of a defined application instance. It ensures that the desired number of replicas are running and monitors their health. Deployments manage the creation, update, and scaling of pods, which are the basic units in Kubernetes. On the other hand, a Kubernetes Daemonset ensures that all the nodes in a cluster run a copy of a specific pod. A Daemonset controller creates pods on each node in the cluster and then monitors them to ensure they are healthy. Daemonsets are helpful for deploying cluster-level applications such as log collectors and monitoring agents. In summary, a Kubernetes deployment is used to manage multiple identical replica pods while a Kubernetes Daemonset is used to ensure that a specific pod runs on all nodes in a cluster.
102
參考答案
Kubernetes provides four Service types, each designed for different networking scenarios: | Type | Scope | Use Case | |---|---|---| | ClusterIP | Internal only | Service-to-service within the cluster | | NodePort | External via node IP | Development, testing | | LoadBalancer | External via cloud LB | Production internet traffic | | ExternalName | DNS redirect | Mapping to external service by DNS |
103
參考答案
The most common approach involves using Prometheus for collecting metrics and Grafana for visualization. Prometheus scrapes metrics from Kubernetes components like kubelet, API server, and containerized applications via exporters (e.g., node-exporter, kube-state-metrics). Grafana connects to Prometheus to display dashboards for cluster health, resource usage, and workload performance. For logging, Fluent Bit or Fluentd collects logs from nodes and pods, forwarding them to a backend like Elasticsearch or Loki. These logs are then visualized in tools such as Kibana or Grafana Loki dashboards. Alerting is typically handled by Alertmanager, integrated with Prometheus, enabling notifications based on metric thresholds or failures.
104
參考答案
A Kubernetes Operator is a method for packaging, deploying, and managing Kubernetes-native applications. An Operator defines a set of custom resources and controllers to automate the management of complex applications.
105
參考答案
Kubernetes supports both horizontal and vertical scaling: - Horizontal Pod Autoscaler (HPA): Automatically adjusts the number of Pod replicas based on observed CPU utilization or other custom metrics. It ensures applications can handle varying loads without manual intervention. - Vertical Pod Autoscaler (VPA): Adjusts the CPU and memory requests and limits for containers in Pods. It ensures Pods have adequate resources to run efficiently. - Cluster Autoscaler: Automatically adjusts the number of nodes in a cluster based on the resource needs of the workloads. It adds nodes when resources are insufficient and removes them when they are underutilized. Commands to configure HPA: kubectl autoscale deployment --cpu-percent=50 --min=1 --max=10 Configuration for VPA and Cluster Autoscaler typically involves setting up policies and resource definitions in YAML files.
106
參考答案
A Kubernetes Operator is a method of packaging, deploying, and managing a Kubernetes application. Operators extend the Kubernetes API to manage custom resources and automate tasks related to the application lifecycle. They are built using the Operator Framework and typically include: - CustomResourceDefinitions (CRDs): Define custom resources. - Controller logic: Implements the desired state for the custom resources. Operators can handle tasks such as installing applications, managing upgrades, backups, failovers, and scaling. They leverage the Kubernetes control loop to continuously monitor and reconcile the state of the custom resource.
107
參考答案
Etcd stores the entire cluster's state, so protecting it comes first. You do that by taking regular snapshots and storing them outside the cluster. Beyond etcd, spread your control plane and worker nodes across multiple availability zones so one failure does not bring everything down. Back up resource definitions and persistent volume data on schedule for a broader recovery.
108
參考答案
Control Plane (Cluster Management) Responsible for managing the overall state and behavior of the cluster. - API Server: Entry point for all REST commands; validates and updates cluster state in etcd . - etcd: Distributed key-value store; the single source of truth for cluster data. - Scheduler: Assigns Pods to nodes based on resource needs and policies. - Controller Manager: Runs controllers that reconcile desired vs. actual state (e.g., Node, Deployment controllers). Data Plane (Workload Execution) Runs actual application workloads on worker nodes. - Kubelet: Ensures containers are running as specified; reports node status to the control plane. - Kube-proxy: Manages network rules for Pod communication. - Container Runtime: Executes containers (e.g., containerd, CRI-O).
109
參考答案
Kubernetes containerd is a lightweight, non-intrusive container runtime for Kubernetes.
110
參考答案
Network Policies act as internal firewalls for your Pods. By default, Kubernetes operates on a “flat network” where all Pods can communicate with all other Pods (Default Allow). A Network Policy uses Pod labels and namespaces to restrict East-West traffic. For security, you should implement a “Default Deny” policy to block all incoming and outgoing traffic, and then explicitly whitelist connections (e.g., allowing the Frontend Pods to only talk to the Backend Pods on port 3306). They require a supporting CNI plugin (like Calico or Cilium) to enforce the rules. RBAC regulates who can access the Kubernetes API and what actions they can perform. You configure it using four primary objects: - Role: Defines permissions (e.g., get, create, delete pods) within a specific namespace. - RoleBinding: Connects a Role to a User, Group, or ServiceAccount within that namespace. - ClusterRole: Similar to a Role, but applies globally across the entire cluster (e.g., permission to view Nodes). - ClusterRoleBinding: Connects a ClusterRole to a subject across the entire cluster.
111
參考答案
ResourceQuota in Kubernetes is like setting rules to make sure different parts of the system don't use too much CPU, memory, or other resources, keeping everything running smoothly and fairly for everyone. apiVersion: v1 kind: ResourceQuota metadata: name: example-resource-quota spec: hard: #OBJECT BASED QUOTA pods: "10" # Maximum number of pods allowed in the namespace #COMPUTE BASED QUOTA requests.cpu: "2" # Maximum total CPU requests allowed (in millicores) requests.memory: 4Gi # Maximum total memory requests allowed limits.cpu: "4" # Maximum total CPU limits allowed (in millicores) limits.memory: 8Gi # Maximum total memory limits allowed persistentvolumeclaims: "5" # Maximum number of persistent volume claims allowed
112
參考答案
A ReplicaSet is a Kubernetes resource that ensures a specified number of replicas of a Pod are running at any given time. It is often used indirectly through Deployments. A ReplicaSet monitors the number of running Pods and creates or deletes Pods as necessary to maintain the desired state.
113
參考答案
Secrets can be created using YAML or JSON configuration files or by using the kubectl create secret command.
114
參考答案
- Define the CRD YAML and apply: kubectl apply -f crd.yaml - Deploy a controller to reconcile and manage those resources.
115
參考答案
Kubernetes provides four main types of Services, each serving a different networking purpose: - ClusterIP (default): Allows for internal communication of Pods. Only accessible from within the cluster. - NodePort: This exposes the Service on a static port of each Node, making It accessible from outside the cluster. - LoadBalancer: Uses a cloud provider's external load balancer. The Service is then accessible via a public IP. - ExternalName: Maps a Kubernetes Service to an external hostname.
116
參考答案
There is not much of a difference between the Replica set and the Replication controller. They have nearly the same types of functions. The basic difference is observed when it comes to the utilization of selectors for pod replication. In the case of the Replica set, set-based selectors for replication of pods. Whereas the replication controllers make use of equity-based selectors.
117
參考答案
If a pod's PV goes inaccessible, instant data recovery becomes necessary. To recover that data, connect the pods to a new node, if possible, or use restore or backup techniques.
118
參考答案
Management Hierarchy - Deployment: Defines the desired state of an application (e.g., number of replicas, container image) and manages updates. - ReplicaSet: Ensures the specified number of Pods are running; created and managed by the Deployment. - Pod: The smallest deployable unit; runs one or more containers. Update Strategy - Updating a Deployment (e.g., new image) triggers creation of a new ReplicaSet. - Kubernetes performs a rolling update: scales up the new ReplicaSet while scaling down the old one. - The old ReplicaSet is retained (scaled to zero) for rollback if needed.
119
參考答案
Kubernetes doesn't natively support canary or blue-green deployments, so extra tooling is required. Argo Rollouts is one option: it provides a Kubernetes controller and a custom Rollout object that lets you easily configure canary and blue-green releases for a set of Pods. Flux's Flagger component is an alternative solution. Both tools also support progressive delivery strategies, allowing new deployments to be automatically promoted between rollout stages.
120
參考答案
When using Kubernetes, most of the time you don't care how your pods are scheduled, but sometimes you care that pods are deployed in order, that they have a persistent storage volume, or that they have a unique, stable network identifier across restarts and reschedules. In those cases, StatefulSets can help you accomplish your objective. It manages the deployment and scaling of a set of Pods, and provides guarantees about the ordering and uniqueness of these Pods. StatefulSets are valuable for applications that require one or more of the following. - Stable, unique network identifiers. - Stable, persistent storage. - Ordered, graceful deployment and scaling. - Ordered, automated rolling updates.
121
參考答案
Kubernetes can automate the scaling of Pods based on CPU or memory usage, ensuring optimal resource allocation and performance.
122
參考答案
GKE is Google Kubernetes Engine which is used for managing and orchestrating systems for Docker containers. GKE also lets us orchestrate container clusters within the Google Public Cloud.
123
參考答案
A DaemonSet ensures that a copy of a Pod runs on all or some specific nodes in the cluster. They are used for deploying cluster-wide services such as log collectors, monitoring agents, or network storage systems. When a node is added to the cluster, the DaemonSet automatically adds a Pod to the new node, and similarly, when a node is removed, the DaemonSet cleans up the Pods running on that node.
124
參考答案
Kubernetes Federation allows you to manage multiple Kubernetes clusters as a single entity. It provides mechanisms for synchronizing resources across clusters and enables high availability and disaster recovery. - Multi-cluster management: Deploy and manage applications across multiple clusters. - Global configuration: Apply policies and configurations uniformly across all clusters. - Cross-cluster discovery: Services can discover each other across clusters. Federation API server and controllers manage the federation of clusters. Example of creating a federated deployment: ```yaml apiVersion: types.kubefed.io/v1beta1 kind: FederatedDeployment metadata: name: myapp namespace: mynamespace spec: template: metadata: labels: app: myapp spec: replicas: 3 template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp-image placement: clusters: - name: cluster1 - name: cluster2 ```
125
參考答案
Kubernetes clusters are a set of node machines that run containerized applications.
126
參考答案
Kubernetes and Docker relate as Kubernetes manages Docker containers. While Docker creates and runs containers, Kubernetes orchestrates and scales them on a cluster, handling deployment, scaling, and networking.
127
參考答案
A Kubernetes stateful set manages the deployment, scaling, and ongoing state of a set of stateful pods, such as databases or other stateful applications.
128
參考答案
Best practices for Kubernetes performance optimization include: Setting resource limits and requests to ensure adequate resources for the application Using horizontal and vertical pod autoscaling Optimizing container images for size and performance Monitoring and tuning system and application performance
129
參考答案
The Kubernetes Scheduler determines which nodes are viable for pod placement based on resource availability and scheduling policies, making the final decision on where a pod should run.
130
參考答案
Kubernetes cluster autoscaling automatically scales the number of nodes in a cluster based on the current demand for resources.
131
參考答案
Applications can be updated in Kubernetes using rolling updates, which ensure zero downtime by incrementally updating pod instances with new ones. This is managed through the Deployment resource.
132
參考答案
This would usually come in the form of "why would you pick Ingress over the Gateway API (or vice versa)?" The answer here is less technical and more organizational. The Gateway API is a newer Kubernetes standard for managing traffic routing into and within a cluster. It was designed to address the limitations of Ingress by providing a more expressive, extensible, and role-oriented model. Where Ingress uses a single resource for everything, the Gateway API splits responsibilities across multiple resources: The Gateway API also natively supports features like traffic splitting, header matching, and cross-namespace routing without relying on annotations.
133
參考答案
Rolling updates can fail to achieve zero downtime due to several factors: Rolling Update Process: Old Pods Running → New Pods Starting → Health Checks → Traffic Switch → Old Pods Termination ↑ (Failure points that cause downtime) Common Rolling Update Failure Modes 1. Inadequate Health Checks - Readiness probes not properly configured - Application not ready when probe succeeds - Health check endpoints not reflecting actual readiness 2. Resource Constraints - Insufficient cluster capacity for new pods - Resource limits preventing pod startup - Node pressure causing evictions 3. Application-Level Issues - Database migration conflicts - Incompatible configuration changes - Dependency service unavailability 4. Infrastructure Problems - Load balancer configuration delays - DNS propagation issues - Network policy conflicts Advanced Deployment Strategies 1. Blue-Green Deployment Pattern Blue Environment (Current) ← Active Traffic Green Environment (New) ← Deployment + Testing Switch Traffic: Blue → Green (Instant cutover) Architecture Benefits: - Instant traffic switching with zero downtime - Full rollback capability - Complete environment testing before traffic switch - Resource overhead of running dual environments Implementation Approach: # Blue deployment (current) apiVersion: apps/v1 kind: Deployment metadata: name: app-blue labels: version: blue spec: replicas: 3 selector: matchLabels: app: myapp version: blue # Green deployment (new) apiVersion: apps/v1 kind: Deployment metadata: name: app-green labels: version: green spec: replicas: 3 selector: matchLabels: app: myapp version: green # Service (traffic switching) apiVersion: v1 kind: Service metadata: name: app-service spec: selector: app: myapp version: blue # Switch to 'green' for deployment Traffic Switching Process: - Deploy green environment alongside blue - Run comprehensive testing on green - Update service selector from version: blue to version: green - Monitor for issues and rollback if needed - Terminate blue environment after validation 2. Canary Deployment Pattern Production Traffic: 90% → Stable Version 10% → New Version (Canary) Gradual Shift: 90/10 → 70/30 → 50/50 → 0/100 Risk Mitigation Benefits: - Gradual exposure to real user traffic - Early issue detection with limited blast radius - Data-driven rollout decisions - Automated rollback based on metrics Canary Implementation with Istio: apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: app-canary spec: hosts: - app-service http: - match: - headers: canary: exact: "true" # Header-based canary route: - destination: host: app-service subset: v2 - route: - destination: host: app-service subset: v1 weight: 90 # 90% to stable version - destination: host: app-service subset: v2 weight: 10 # 10% to canary version Enhanced Rolling Update Configuration Optimized Rolling Update Parameters: apiVersion: apps/v1 kind: Deployment metadata: name: zero-downtime-app spec: replicas: 5 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 # Never reduce available pods maxSurge: 2 # Can create 2 extra pods (40% surge) template: spec: containers: - name: app image: myapp:v2 readinessProbe: httpGet: path: /health/ready port: 8080 initialDelaySeconds: 30 # Wait for app initialization periodSeconds: 5 # Check every 5 seconds timeoutSeconds: 3 # 3-second timeout successThreshold: 1 # 1 success = ready failureThreshold: 3 # 3 failures = not ready livenessProbe: httpGet: path: /health/live port: 8080 initialDelaySeconds: 60 # Longer delay for liveness periodSeconds: 10 # Less frequent checks Key configuration elements: maxUnavailable: 0: Ensures no reduction in available capacity maxSurge: 2: Allows temporary over-provisioning for smooth transition Separate readiness and liveness probes with appropriate timing Conservative probe timing to avoid premature pod termination Graceful Shutdown Implementation PreStop Hook Configuration: spec: containers: - name: app lifecycle: preStop: exec: command: ["/bin/sh", "-c", "sleep 15"] # Grace period terminationGracePeriodSeconds: 30 # Total shutdown time Application Shutdown Sequence: - TERM signal sent to application - PreStop hook executed (connection draining) - Application performs graceful shutdown - KILL signal sent if still running after grace period Database Migration Strategies 1. Forward-Compatible Migrations - New application version compatible with old database schema - Database changes applied separately from application deployment - Backward compatibility maintained during transition 2. Expansion/Contraction Pattern - Expand: Add new database elements (columns, tables) - Deploy: Application version supporting both old and new schema - Contract: Remove old database elements after full deployment Monitoring and Validation Deployment Health Metrics: - Pod readiness and availability during rollout - Application error rates and response times - Database connection and transaction metrics - User experience and business metrics Automated Rollback Triggers: - Error rate thresholds exceeded - Response time degradation - Health check failure rates - Business metric anomalies Progressive Deployment Validation: - Automated testing in canary environment - Synthetic transaction monitoring - Real user monitoring and feedback - Business impact assessment Infrastructure Prerequisites 1. Cluster Capacity Planning - Ensure sufficient resources for surge capacity - Node autoscaling configuration for demand spikes - Multi-zone deployment for availability 2. Load Balancer Configuration - Proper health check configuration - Connection draining support - Session affinity considerations 3. Monitoring and Alerting - Real-time deployment progress monitoring - Automated alerting for deployment issues - Integration with incident response procedures
134
參考答案
Horizontal pod Autoscaler works as a part of the control loop. HPA can automatically reshape workflows in order to maintain required states by frequently contrasting its own metrics.
135
參考答案
Kube-apiserver acts as the front-end to the cluster, processing REST requests, validating them, and updating the corresponding objects in etcd, providing the primary interface for cluster management.
136
參考答案
Pod affinity and anti-affinity in Kubernetes influence pod placement decisions, enhancing co-location or separation for workload optimization. Affinity rules attract pods to specific nodes, while anti-affinity repels them, enabling high availability, performance efficiency, and strategic distribution across the cluster.
137
參考答案
A sidecar container is an auxiliary container that runs alongside the main application container within the same Pod. It enhances or supports the primary container without being part of the core application logic. Common Use Cases - Log forwarding - Metrics collection - Service mesh proxies (e.g., Envoy) - TLS termination - Data synchronization
138
參考答案
These are the three primary Service types used to expose applications in Kubernetes: | Service Type | Accessibility | Primary Use Case | |---| | ClusterIP (Default) | Internal only. | East-West traffic (e.g., Frontend Pods communicating with Backend Database Pods). | | NodePort | External (via Node IP + static port). | Quick debugging or exposing services in bare-metal environments without a cloud provider. | | LoadBalancer | External (via Cloud Provider IP). | Production web apps. Automatically provisions an external Load Balancer (AWS ELB, Azure ALB) to route North-South traffic. |
139
參考答案
Readiness probe ensures that a pod is ready to handle requests. Kubernetes only sends traffic to pods passing their readiness checks, thus helping maintain service reliability.
140
參考答案
To debug a Kubernetes cluster issue: - Check cluster components: Ensure the API server, etcd, controller manager, and scheduler are healthy. - Inspect node status: Use kubectl get nodes andkubectl describe node to check node health and resource usage. - Examine Pod status: Use kubectl get pods --all-namespaces andkubectl describe pod to gather detailed information. - Review logs: Check logs for the control plane components and application Pods using kubectl logs . - Investigate network issues: Use network debugging tools like kubectl exec -it -- /bin/sh to diagnose connectivity problems. - Analyze events: Use kubectl get events --sort-by='.metadata.creationTimestamp' to review recent cluster events. - Resource utilization: Monitor CPU, memory, and storage using tools like Prometheus and Grafana.
141
參考答案
Kubernetes handles stateful applications using StatefulSets. StatefulSets manage the deployment and scaling of a set of Pods with persistent identities and stable network identities. This is particularly useful for applications that require persistent storage and ordered deployment, such as databases and distributed systems. - Persistent Storage: Each Pod in a StatefulSet gets its own PersistentVolumeClaim. - Ordered Deployment and Scaling: Pods are created, deleted, and scaled in a specific order. - Stable Network Identities: Each Pod gets a unique, stable network identity. Example of a StatefulSet configuration: ```yaml apiVersion: apps/v1 kind: StatefulSet metadata: name: web spec: serviceName: "nginx" replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx volumeMounts: - name: www mountPath: /usr/share/nginx/html volumeClaimTemplates: - metadata: name: www spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 1Gi ```
142
參考答案
Kubernetes cloud-native development is a software development methodology that maximizes the use of Kubernetes to build, deploy, and manage cloud-native applications.
143
參考答案
StorageClasses define the provisioning requirements for dynamically provisioned Persistent Volumes, allowing administrators to offer different classes of storage to users.
144
參考答案
A ConfigMap is an API object used to store non-confidential data in key-value pairs. Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume.
145
參考答案
Kubernetes offers various abstractions to manage containerized applications according to specific operational needs. Deployments, StatefulSets, and DaemonSets are all essential controllers in this regard. - Deployments are suitable for stateless, replicated applications, and mainly focus on the management of pods. - State: Stateless - These are ideal for microservices that do not store data and can be horizontally scaled. - Pod Management: Managing a replica set of pods. - Inter-Pod Communication: Achieved through services. - Storage: Volatile. Data does not persist beyond the pod's lifecycle. - StatefulSets are designed for stateful applications requiring stable, unique network identities and persistent storage. - State: Stateful - Suitable for applications that store persistent data, control startup order, and require unique network identities. - Pod Management: Provides sticky identity, persistence, and orderly deployment and scaling. - Inter-Pod Communication: Managed through stable network identities. - Storage: Provides mechanisms for persistent storage. - DaemonSets are for running agents on each node for system-level tasks. - State: Node-Focused - Ideal for workloads with demon-like functionalities that are needed on each node (e.g. log collection, monitoring). - Pod Management: Ensures one pod per node. - Inter-Pod Communication: Not a primary concern. - Storage: Depends on the specific use case.
146
參考答案
Kubernetes Secrets is a secure way to store sensitive information within Kubernetes clusters, such as passwords, OAuth tokens, SSH keys, and other confidential data. - Storage: Kubernetes Secrets stores sensitive data securely within the cluster's ETCD database. - Base64 Encoding: Secrets are encoded in Base64 format to prevent plain-text exposure. - Usage: Secrets can be mounted into pods as files or environment variables for secure access by applications. - Access Control: Role-Based Access Control (RBAC) ensures only authorized entities can manage Secrets. - Updates and Rotations: Secrets should be periodically rotated for enhanced security by generating new values. - Secret Types: Kubernetes supports various Secret types tailored for different sensitive information. - Immutable: Once created, Secrets cannot be updated directly; they must be recreated with new data. #Create a Secret: kubectl create secret --from-literal== #View Secrets: kubectl get secrets #View Secret Details: kubectl describe secret #Decode a Secret: kubectl get secret -o jsonpath="{.data.}" | base64 --decode #Delete a Secret: kubectl create secret generic --from-file= #Create a Secret from a File: kubectl create secret generic --from-file= #Create a TLS Secret: kubectl create secret tls --cert= --key= #Create a Docker Registry Secret: kubectl create secret docker-registry --docker-server= --docker-username= --docker-password= --docker-email= #Mount a Secret as a Volume (in a Pod's YAML): volumes: - name: secret: secretName: #Use a Secret as an Environment Variable (in a Pod's YAML): env: - name: valueFrom: secretKeyRef: name: key:
147
參考答案
Kubernetes provides several built-in security features, such as role-based access control (RBAC), pod security policies, and network policies. Best practices for securing a Kubernetes cluster include applying security updates regularly, using strong authentication and access controls, and using network segmentation to separate resources.
148
參考答案
First priority is to restore service: # Roll back immediately kubectl rollout undo deployment/ # Verify the rollback kubectl rollout status deployment/ Then investigate: # Check rollout history kubectl rollout history deployment/ # Check logs from failing Pods kubectl logs --previous # Verify image pull details kubectl describe pod | grep -A3 "Image" Common causes include a bad image tag, missing environment variables in the new version, or failing health checks with updated endpoints.
149
參考答案
Picture this: six out of ten respondents in our State of Cloud Cost survey reported that their cloud costs are higher than they should be. And if you think K8s has something to do with it, you are right! Rising Kubernetes costs are becoming a major headache for many teams, making it challenging to keep spending in check without sacrificing scalability or innovation. It doesn't help that Kubernetes lacks a robust, built-in cost management solution. On top of that, many cost management tools fail to deliver the accuracy, detail, and control you need to keep costs in check — without slowing down engineering velocity or hindering scalability. Not CloudZero.
150
參考答案
Kubernetes can be monitored using various tools like Prometheus, Grafana, and Kubernetes' native monitoring capabilities, which provide insights into cluster performance and resource usage.
151
參考答案
Kubernetes RBAC is a method of controlling access to Kubernetes resources based on user roles and permissions.
152
參考答案
Kubernetes ensures high availability through Pod Disruption Budgets (PDBs), anti-affinity rules, and self-healing mechanisms. Here's how these mechanisms work: - Pod Disruption Budget (PDB): Ensures a minimum number of Pods remain available during voluntary disruptions (e.g., cluster updates where nodes need to be scaled down). - Pod affinity and anti-affinity: Controls for which Pods can be scheduled together or separately. - Node selectors and Taints/Tolerations: Control how workloads are distributed across Nodes. Here's an example PDB YAML definition that ensures that at least two Pods remain running during disruptions: apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: my-app-pdb spec: minAvailable: 2 selector: matchLabels: app: my-app
153
參考答案
- Liveness probes: Check if the application is running. If it fails, Kubernetes restarts the pod. - Readiness probes: Determine if the application is ready to handle traffic. Ensures traffic is only sent to ready pods.
154
參考答案
Centralized logging is required for debugging and auditing. Two different logging stack options: - Loki + Fluentd + Grafana (Lightweight and fast). - ELK Stack (Elastic, Logstash, Kibana) (Scalable and enterprise-grade).
155
參考答案
Namespaces in Kubernetes provide a mechanism for isolating groups of resources within a single cluster. They allow multiple users or teams to share a cluster without interfering with each other. Benefits and use cases for namespaces include: - Resource isolation: Different teams or projects can operate within their own namespace. - Resource quotas: Set limits on the amount of resources a namespace can use. - Name collision: Avoid name collisions by using namespaces to segregate resources. - Security policies: Apply network policies and RBAC rules at the namespace level. Example of creating a namespace: kubectl create namespace my-namespace Applying a resource quota to a namespace: apiVersion: v1 kind: ResourceQuota metadata: name: compute-resources namespace: my-namespace spec: hard: requests.cpu: "1" requests.memory: 1Gi limits.cpu: "2" limits.memory: 2Gi
156
參考答案
- Sidecar container pattern - Init container pattern - Ambassador pattern - Adapter pattern - Work Queue pattern - Leader Election pattern - Scatter/Gather pattern - Single container pattern
157
參考答案
CRDs empower you to define custom Kubernetes objects, extending Kubernetes beyond built-in resources like Pods and Services. CRDs enable custom controllers and Operators, automating complex application management.
158
參考答案
Kubernetes network plugins provide networking capabilities to Pods and manage network policies within a cluster. The Container Network Interface (CNI) is the standard used by Kubernetes for networking. Popular network plugins include: - Calico: Provides networking and network policy enforcement. - Flannel: Simple overlay network that satisfies the Kubernetes requirements. - Weave: Implements a full mesh network topology. - Cilium: Provides network security and visibility using BPF. - Kube-router: A lean network fabric for Kubernetes. Network plugins manage tasks like IP address management, routing, network isolation, and security policies. Example of deploying Calico as a network plugin: kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml
159
參考答案
Kubernetes is a container management system developed in the Google platform. The purpose of Kubernetes is to manage a containerized application in various types of physical, virtual, and cloud environments. Google Kubernetes is a highly flexible container tool to deliver even complex applications, consistently. Applications run on clusters of hundreds to thousands of individual servers.
160
參考答案
Docker builds containers, which then communicate with each other via Kubernetes. Kubernetes supports multiple container runtimes, including Docker, CRI-O, and others. In simple terms, Kubernetes is analogous to an operating system, and Docker containers are comparable to applications installed on that operating system. Docker is a containerization platform that allows developers to package and distribute their applications as self-contained units, known as containers. Kubernetes, on the other hand, is a container orchestration platform that automates the deployment, scaling, and management of containerized applications. The two technologies, Kubernetes and Docker, work together to enable the deployment and management of applications in a distributed environment.
161
參考答案
A ReplicaSet is a Kubernetes controller that keeps a stable number of identical pod replicas running in the cluster. You declare the desired count. From that point, it watches the actual state. If one pod crashes or a node fails, a new one is created on a healthy node. If there are more pods than specified, the extras are terminated. The example below demonstrates a ReplicaSet designed to maintain three identical pods:
162
參考答案
Kubernetes probes are mechanisms to check the health and status of containers. They help determine if a container is ready to accept traffic (readiness probe) and if it is still running properly (liveness probe). Types of probes: - Liveness Probe: Checks if the container is running. If the probe fails, Kubernetes will restart the container. - Readiness Probe: Checks if the container is ready to serve traffic. If the probe fails, the container will be removed from service endpoints. - Startup Probe: Used to check if an application has started successfully. It is useful for applications with long initialization times. Probes can use different methods: - HTTP: Perform an HTTP GET request. - TCP: Perform a TCP check. - Exec: Execute a command inside the container. Example of a Pod with probes: livenessProbe: httpGet: path: /healthz port: 8080 initialDelaySeconds: 3 periodSeconds: 3 readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 3 periodSeconds: 3
163
參考答案
Kubernetes provides persistent storage through Persistent Volumes (PVs) and Persistent Volume Claims (PVCs): - Persistent Volume (PV): A PV is a cluster-wide resource that represents a piece of networked storage in the cluster, such as a physical disk or a network-attached storage (NAS). Administrators provision and manage PVs. - Persistent Volume Claim (PVC): A PVC is a request for a specific amount of storage resources by a user or application. It binds to a suitable PV with matching capacity and access modes. PVCs are used by developers to request and consume storage resources in a more abstracted manner.
164
參考答案
With the use of limit and request resource usage of a POD can be controlled. Request: The number of resources being requested for a container. If a container exceeds its request for resources, it can be throttled back down to its request. Limit: An upper cap on the resources a single container can use. If it tries to exceed this predefined limit it can be terminated if K8's decides that another container needs these resources. If you are sensitive towards pod restarts, it makes sense to have the sum of all container resource limits equal to or less than the total resource capacity for your cluster. Example: apiVersion: v1 kind: Pod metadata: name: demo spec: containers: - name: example1 image:example/example1 resources: requests: memory: "_Mi" cpu: "_m" limits: memory: "_Mi" cpu: "_m"
165
參考答案
A sidecar container is a utility container that is used to extend support for a main container in a Pod. Sidecar containers can be paired with one or more main containers, and they enhance the functionality of those main containers. An example would be using a sidecar container specifically to process system logs or for monitoring.
166
參考答案
Single control plane multi-region deployments introduce several architectural challenges: Single Control Plane (Region A) → Worker Nodes (Region A, B, C) ↓ Cross-region latency for all cluster operations Single point of failure for entire infrastructure Key challenges: - Latency: API calls from distant regions experience high latency - Reliability: Control plane failure affects all regions - Network partitions: Cross-region connectivity issues impact operations - Data locality: Workload placement and data gravity considerations Architectural Design Patterns 1. Regional Node Pools with Intelligent Scheduling Node Topology Awareness: # Label nodes by region and zone apiVersion: v1 kind: Node metadata: name: worker-node-us-west-1a labels: topology.kubernetes.io/region: "us-west-1" topology.kubernetes.io/zone: "us-west-1a" node.kubernetes.io/instance-type: "m5.large" Application Deployment with Region Affinity: apiVersion: apps/v1 kind: Deployment metadata: name: app-us-west spec: replicas: 3 selector: matchLabels: app: myapp region: us-west template: metadata: labels: app: myapp region: us-west spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: topology.kubernetes.io/region operator: In values: ["us-west-1", "us-west-2"] # Multi-AZ within region podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: ["myapp"] topologyKey: topology.kubernetes.io/zone Key scheduling considerations: nodeAffinity: Ensures pods run in specific regions podAntiAffinity: Distributes pods across availability zones Regional replica distribution for high availability 2. Topology-Aware Service Routing apiVersion: v1 kind: Service metadata: name: app-service annotations: service.kubernetes.io/topology-aware-hints: auto spec: selector: app: myapp ports: - port: 80 targetPort: 8080 type: ClusterIP Topology-aware routing benefits: - Reduces cross-region traffic - Improves response latency - Minimizes data transfer costs - Enhances overall performance Storage and Data Considerations 1. Regional Storage Classes apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: regional-ssd-us-west provisioner: kubernetes.io/aws-ebs parameters: type: gp3 replication-type: regional zones: us-west-1a,us-west-1b,us-west-1c allowedTopologies: - matchLabelExpressions: - key: topology.kubernetes.io/zone values: - us-west-1a - us-west-1b - us-west-1c volumeBindingMode: WaitForFirstConsumer Storage design principles: - Regional storage for data locality - Cross-zone replication for availability - Backup and disaster recovery across regions - Data sovereignty and compliance considerations 2. Database Deployment Strategies Regional Database Replicas: # Primary database in primary region apiVersion: apps/v1 kind: StatefulSet metadata: name: database-primary namespace: us-east spec: serviceName: database-primary replicas: 1 template: spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: topology.kubernetes.io/region operator: In values: ["us-east-1"] --- # Read replica in secondary region apiVersion: apps/v1 kind: StatefulSet metadata: name: database-replica namespace: us-west spec: serviceName: database-replica replicas: 1 template: spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: topology.kubernetes.io/region operator: In values: ["us-west-1"] Better Architectural Approach: Multi-Cluster Why Single Control Plane Doesn't Scale: - Control plane becomes bottleneck for geographically distributed workloads - Network latency affects all cluster operations - Blast radius of control plane failures too large - Limited failure isolation between regions Multi-Cluster Architecture: Regional Clusters: ├── US-East Cluster (Primary) ├── US-West Cluster (Secondary) ├── EU-West Cluster (Compliance) └── AP-Southeast Cluster (Local Market) Cross-Cluster Coordination: ├── Service Mesh Federation ├── GitOps Deployment Sync ├── Multi-Cluster DNS └── Global Load Balancing 1. Cluster API for Multi-Cluster Management # Cluster definition for US-East apiVersion: cluster.x-k8s.io/v1beta1 kind: Cluster metadata: name: us-east-production namespace: cluster-management spec: clusterNetwork: services: cidrBlocks: ["10.128.0.0/12"] pods: cidrBlocks: ["192.168.0.0/16"] infrastructureRef: apiVersion: infrastructure.cluster.x-k8s.io/v1beta1 kind: AWSCluster name: us-east-production controlPlaneRef: apiVersion: controlplane.cluster.x-k8s.io/v1beta1 kind: KubeadmControlPlane name: us-east-production-control-plane --- # Cluster definition for US-West apiVersion: cluster.x-k8s.io/v1beta1 kind: Cluster metadata: name: us-west-production namespace: cluster-management spec: clusterNetwork: services: cidrBlocks: ["10.144.0.0/12"] pods: cidrBlocks: ["192.169.0.0/16"] infrastructureRef: apiVersion: infrastructure.cluster.x-k8s.io/v1beta1 kind: AWSCluster name: us-west-production 2. Multi-Cluster Service Discovery # Multi-cluster service registration apiVersion: networking.istio.io/v1alpha3 kind: ServiceEntry metadata: name: us-west-api-service namespace: istio-system spec: hosts: - api-service.us-west.local location: MESH_EXTERNAL ports: - number: 443 name: https protocol: HTTPS resolution: DNS addresses: - 10.144.1.100 # US-West cluster service IP Global Traffic Management 1. Global Load Balancing Strategy Internet Traffic → Global Load Balancer → Regional Clusters ↓ Health-based routing to healthy regions Latency-based routing for performance Geographic routing for compliance 2. DNS-Based Traffic Distribution # External DNS configuration for multi-cluster apiVersion: v1 kind: Service metadata: name: api-service-us-east annotations: external-dns.alpha.kubernetes.io/hostname: api-us-east.company.com external-dns.alpha.kubernetes.io/ttl: "60" spec: type: LoadBalancer selector: app: api-service --- apiVersion: v1 kind: Service metadata: name: api-service-us-west annotations: external-dns.alpha.kubernetes.io/hostname: api-us-west.company.com external-dns.alpha.kubernetes.io/ttl: "60" spec: type: LoadBalancer selector: app: api-service Disaster Recovery and Failover 1. Cross-Region Backup Strategy # Automated cross-region backup apiVersion: batch/v1 kind: CronJob metadata: name: cross-region-backup spec: schedule: "0 2 * * *" jobTemplate: spec: template: spec: containers: - name: backup image: backup-tool:latest env: - name: SOURCE_REGION value: "us-east-1" - name: BACKUP_REGION value: "us-west-1" command: - /bin/sh - -c - | # Backup persistent volumes kubectl get pv --no-headers | while read pv; do create_cross_region_snapshot $pv done # Backup cluster state kubectl get all --all-namespaces -o yaml > cluster-state.yaml upload_to_backup_region cluster-state.yaml 2. Automated Failover Procedures Health Check Failure → Update DNS Records → Route Traffic to Healthy Region ↓ Notify Operations Team ↓ Begin Recovery Procedures Monitoring Multi-Region Infrastructure 1. Cross-Region Monitoring Strategy Key metrics for multi-region deployments: - Cross-region network latency and connectivity - Regional cluster health and availability - Application performance per region - Data replication lag and consistency - Cost optimization across regions 2. Alerting and Incident Response # Multi-region monitoring alerts groups: - name: multi-region.rules rules: - alert: CrossRegionLatencyHigh expr: histogram_quantile(0.95, increase(http_request_duration_seconds_bucket{job="cross-region-probe"}[5m])) > 0.5 for: 2m labels: severity: warning region: "{{ $labels.source_region }}" annotations: summary: "High latency detected between regions" - alert: RegionalClusterDown expr: up{job="kubernetes-apiservers"} == 0 for: 1m labels: severity: critical cluster: "{{ $labels.cluster }}" annotations: summary: "Regional cluster {{ $labels.cluster }} is unreachable" Cost Optimization Strategies 1. Regional Resource Optimization - Instance type selection based on regional pricing - Spot instances for non-critical workloads - Reserved instances for predictable workloads - Data transfer cost minimization through intelligent routing 2. Workload Placement Optimization # Cost-aware scheduling preferences apiVersion: v1 kind: Pod metadata: name: batch-job spec: nodeSelector: node.kubernetes.io/instance-type: "spot" topology.kubernetes.io/region: "us-west-1" # Lower cost region tolerations: - key: "spot-instance" operator: "Equal" value: "true" effect: "NoSchedule" Best Practices for Multi-Region Deployments 1. Network Design - Dedicated network connections between regions - VPN or private connectivity for cluster communication - Network security and traffic encryption - Bandwidth planning for cross-region traffic 2. Security Considerations - Identity and access management across regions - Certificate management and rotation - Compliance with regional regulations - Data sovereignty and residency requirements 3. Operational Excellence - Standardized deployment procedures across regions - Consistent monitoring and alerting strategies - Disaster recovery testing and validation - Change management for multi-region updates
167
參考答案
Kubernetes is used because: - Kubernetes can run on-premises bare metal, OpenStack, public clouds Google, Azure, AWS, etc. - It helps you to avoid vendor lock issues as it can use any vendor-specific APIs or services except where Kubernetes provides an abstraction, e.g., load balancer and storage. - It will enable applications that need to be released and updated without any downtime. - Kubernetes allows you to assure those containerized apps run where and when you want and help you to find resources and tools which you want to work.
168
參考答案
Etcd stores the complete cluster state, meaning critical information is stored there. By default, Kubernetes stores secrets unencrypted in etcd, making them vulnerable to compromise. Therefore, it can be crucial to enable secret encryption at REST so that secrets are stored and encrypted. As a first step, you need to create an encryption configuration file and store an encryption/decryption key in that file: apiVersion: apiserver.config.k8s.io/v1 kind: EncryptionConfiguration resources: - resources: - secrets providers: - aescbc: keys: - name: key1 secret: - identity: {} The configuration above specifies that Kubernetes will use the aescbc provider to encrypt Secret resources, with a fallback to identity for unencrypted data. Next, you need to adapt the kube-apiserver configuration file, typically found at /etc/kubernetes/manifests/kube-apiserver.yaml on a control plane node, and include the -- encryption-provider-config flag pointing to the encryption configuration file that you've created: command: - kube-apiserver ... - --encryption-provider-config=/path/to/encryption-config.yaml Save the changes and restart the kube-apiserver to apply the new configuration.
169
參考答案
Kubernetes supports four types of services such as ClusterIP, NodePort, LoadBalancer, and Ingress. Each service has some requirements to enable them for the application and thus you need to understand everything before the deployment process.
170
參考答案
Pods that are stuck restarting will appear in the kubectl get pods command's output with a RESTARTS count that keeps increasing. You can troubleshoot the issue by using kubectl describe pod to view the events associated with the Pod. Accessing the Pod's logs using kubectl logs pod/ may also reveal useful information if the Pod's restarting due to a problem with the containerized app. Common causes of Pod restart loops include incorrect container image paths, failing liveness probes, and out-of-memory scenarios, so it's often helpful to begin by checking for these issues.
171
參考答案
The Kubernetes API server is the central management entity that exposes the Kubernetes API. It serves as the entry point for all the administrative tasks in the cluster. It handles RESTful API requests and processes them by interacting with the etcd database and other control plane components. The API server: - Validates requests. - Processes resource configurations. - Maintains cluster state in etcd. - Provides a point of extension for custom resources and controllers.
172
參考答案
- Kubernetes dashboard is not as helpful as it should be - Security is not very effective. - It is very complex and can reduce productivity - Kubernetes is more costly than its alternatives.
173
參考答案
While Taints repel Pods, Affinity attracts or intelligently distributes them based on specific architectural rules and labels. | Feature | Target Rule | Primary Goal | Real-World Example | |---| | Node Affinity | Node Labels | Attracts a Pod to a specific set of underlying Worker Nodes. | Forcing a heavy data-processing Pod to only schedule on Nodes labeled disktype=ssd. | | Pod Anti-Affinity | Pod Labels | Repels Pods from other Pods to spread out workloads across the cluster. | Ensuring three replicas of a database are scheduled on three completely different Nodes to prevent a single point of failure (High Availability). |
174
參考答案
To imperatively create a new deployment in Kubernetes, you use the kubectl create deployment command. This is the fastest way to get an application running without writing a full YAML manifest from scratch. kubectl create deployment my-deployment --image=nginx:1.16 --replicas=3 In this command, –image specifies the exact container image to pull from your container registry, and –replicas tells the Control Plane how many identical Pods to spin up. For production, however, it is highly recommended to use the declarative approach (kubectl apply -f deployment.yaml) for better version control.
175
參考答案
A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes. It is a resource in the cluster just like a node. A PersistentVolumeClaim (PVC) is a request for storage by a user. Pods can request specific sizes and access modes (e.g., ReadWriteOnce, ReadOnlyMany) using PVCs. The cluster then maps the PVC to a suitable PV.
176
參考答案
An Operator is a method of packaging, deploying, and managing a Kubernetes-native application. It uses custom resources to automate operational tasks for complex applications, extending the Kubernetes API.
177
參考答案
The master node (control plane) manages the cluster's desired state, scheduling, and coordination. It consists of the API server, controller manager, scheduler, and etcd. If a single master node fails in a non-HA setup, the cluster becomes unmanageable, but running workloads continue until nodes or pods require updates. To recover, you would: - Check etcd health and restore from a backup if necessary. - Recreate the master node with the same configurations. - Rejoin worker nodes to the cluster if disconnected. For high availability (HA) clusters, multiple master nodes are used, and failure is mitigated via leader election mechanisms and redundant etcd instances.
178
參考答案
A DaemonSet ensures that all (or some) Kubernetes nodes run a copy of a specific pod. It is commonly used for deploying system daemons like log collectors, monitoring agents, or other tools that need to run on all or certain nodes.
179
參考答案
A Kubernetes deployment is suitable for stateless applications, while a Statefulset is ideal for stateful applications like databases. A deployment is designed to handle simple scaling and zero downtime rolling updates. In contrast, a Statefulset offers more guarantees on the ordering and uniqueness of pods and persistent storage.
180
參考答案
When a request reaches the Kubernetes API, it does not go straight to etcd. It passes through admission controllers first. These plugins check the request before anything is saved and can approve or block it depending on your configuration. Two of them stand out: MutatingAdmissionWebhook can modify a request before it is saved, and ValidatingAdmissionWebhook can accept or reject it based on your rules. This is where policy tools like Kyverno or OPA Gatekeeper come in. You write a policy, connect it through the webhook, and every request runs through it automatically. For example, if you want to stop containers from running as root, you write a policy that rejects any pod that does not set runAsNonRoot to true. Any pod that violates this gets rejected at the API level.
181
參考答案
Liveness probes in Kubernetes check if an application inside a pod is running, restarting it if the check fails. Readiness probes determine if the application is ready to process requests, ensuring Kubernetes directs traffic only to pods ready for it. These probes help maintain application reliability and availability.
182
參考答案
The company can implement the DevOps methodology, by building a CI/CD pipeline, but one problem that may occur here is the configurations may take time to go up and running. So, after implementing the CI/CD pipeline the company's next step should be to work in the cloud environment. Once they start working on the cloud environment, they can schedule containers on a cluster and can orchestrate with the help of Kubernetes. This kind of approach will help the company reduce their deployment time, and also get faster across various environments.
183
參考答案
A PersistentVolume is a storage resource provisioned in the cluster that lives independently of any pod. This means the data survives even when the pod is deleted or rescheduled. A PersistentVolumeClaim is how a pod requests persistent volumes by specifying size and access mode, and Kubernetes matches it to an available volume.
184
參考答案
The API server is the front-end interface for the Kubernetes control plane that exposes the Kubernetes API.
185
參考答案
To supply their customers with a digital experience, they will hope that the company lacks a scalable platform. This is necessary to obtain data from the website of a client. In order to do so, they will have to migrate from private data centers to any cloud platform. But before going to work on the cloud platform they need to prepare and produce various micro-services for their applications. After landing on the cloud platform, they can make use of any available open-source orchestration platform like Kubernetes. This in return will promote building different types of apps and delivering the same as soon as possible.
186
參考答案
Kubernetes assigns each Pod an IP address and exposes the containers within the Pod using a local network namespace, allowing them to communicate with each other over the localhost interface.
187
參考答案
Use kubectl describe pod to check events and conditions. kubectl logs retrieves logs for debugging. Tools like Prometheus or K9s can provide deeper insights.
188
參考答案
Both manage Pod replicas, but they serve entirely different architectures. Deployments manage stateless applications (like web servers), whereas StatefulSets are designed for stateful applications (like MySQL or MongoDB databases). | Feature | Deployment | StatefulSet | |---| | Pod Identity | Random hashes (e.g., web-8a9b). | Sticky, sequential network IDs (e.g., db-0, db-1). | | Storage | Pods typically share the same volume. | Each Pod gets its own dedicated persistent volume (PVC). | | Scaling Order | Simultaneous creation/deletion. | Strict, ordered creation and graceful deletion. |
189
參考答案
Kubernetes allows you to update ConfigMaps, Secrets, and environment variables, triggering rolling updates of Pods to apply the configuration changes.
190
參考答案
There are various possible reasons by which a cluster can go in 'Pending state'. For instance, node affinity, resource constraints, insufficient resources or anti-affinity rules. We can detect them by troubleshooting resource limits/requests, event logs or node availability. Then it can be resolved by modifying node assignments and resources.
191
參考答案
Network Policies allow you to define rules for communication between Pods and control traffic flow within the cluster.
192
參考答案
Headless Services are used when you don't need or want load-balancing and a single service IP. Instead, they allow you to directly access the pods behind the service.
193
參考答案
To troubleshoot a failing Pod, you can: - Check Pod status: Use kubectl get pod to see the Pod's status. - Describe Pod: Use kubectl describe pod to get detailed information about the Pod, including events that might indicate why it's failing. - View logs: Use kubectl logs to check the logs of the main container in the Pod. If the Pod has multiple containers, specify the container name:kubectl logs -c . - Exec into Pod: Use kubectl exec -it -- /bin/bash to get a shell inside the running container and manually inspect files or run commands. - Check Events: Use kubectl get events to look for any recent events that might provide clues about failures.
194
參考答案
If a Pod's memory consumption exceeds its assigned memory limit, Kubernetes immediately kills the container with an out of memory (OOM) error. The container restarts if a restart policy is defined. Unlike memory, if a Pod exceeds its assigned CPU limit, it is not killed. Instead, Kubernetes throttles CPU usage, causing the application to slow down.
195
參考答案
The Operator pattern was pioneered by CoreOS (later acquired by Red Hat) as a way to encode operational knowledge into software. The idea was that managing complex stateful applications like databases, message queues, or monitoring systems requires domain expertise that goes beyond what basic Kubernetes controllers handle. An Operator captures that expertise in code. In practical terms, an Operator is a controller paired with one or more CRDs. The CRD defines the application-level resource (for example, a PostgresCluster), and the controller contains the logic for managing the full lifecycle of that application: provisioning, scaling, backups, upgrades, and failure recovery. So the difference is one of scope. Every Operator is a controller, but not every controller is an Operator. A controller reconciles the state for a given resource. An Operator does the same thing but embeds application-specific operational logic that would otherwise require a human administrator to perform manually.
196
參考答案
Kubernetes network policies are rules that control the flow of network traffic between pods and services within a Kubernetes cluster.
197
參考答案
DaemonSets are specialist objects that replicate a set of identical Pods across every Node in your Kubernetes cluster. They ensure all your Nodes are running a particular workload. This is useful for services such as monitoring agents and log collectors, where data must be gathered from each Node to make your cluster fully observable.
198
參考答案
A container cluster lets us place and manage containers in a dynamic setup. It can be considered as a set of nodes or Compute Engine instances. The API server of Kubernetes does not run on cluster nodes, instead the Container Engine hosts the API server.
199
參考答案
Both readiness and liveness probes are used to check for the overall heal of the application.
200
參考答案
A DaemonSet ensures one copy of a pod runs on every node in the cluster. Add a new node, and the pod lands on it automatically. Remove a node, and the pod goes with it. This makes it useful for node-level tasks like log collection, monitoring agents, or network plugins, where every node needs the same workload running.