Share with friends
Calling all Kubernetes masters! Think you've got what it takes? This section dives into the deep end with security, troubleshooting, and all the new and exciting stuff happening in the Kubernetes world. Answering these questions will prove you're a pro and someone everyone wants on their team.
More on the topic
Kubernetes Interview Questions - Beginner Level
Kubernetes Interview Questions - Medium Level Part 1
Kubernetes Interview Questions - Medium Level Part 2
Kubernetes Interview Questions - Advanced Level Part 1
Kubernetes Interview Questions - Advanced Level Part 2
Kubernetes Interview Questions - Advanced Level Part 3
Kubernetes Interview Questions - Advanced Level Part 4
Advanced-Level Kubernetes Interview Questions Part 2
Question 1: What are Kubernetes Namespaces and why are they used?
Answer: In Kubernetes, namespaces come in handy when you've got tons of users spread across different teams or projects. They're like dividers that keep cluster resources separate for each user. This way, the same name can be used in different namespaces without causing any confusion or conflicts..
Example: Consider you have two teams, "development" and "production," working on the same Kubernetes cluster. Using namespaces, you can create two separate environments without conflict:
kubectl create namespace development
kubectl create namespace production
Each team can then create services, deployments, and other resources within their respective namespaces without worrying about name collisions.
Question 2: Explain the concept of a Kubernetes Pod and its lifecycle.
Answer: A Pod is like the tiniest and most basic building block in Kubernetes. Picture it as a single running process in your cluster. Inside a Pod, you'll find one or more containers, storage resources, a unique IP address, and settings that control how the containers should behave.
Pod Lifecycle in a Nutshell:
- Pending: The Pod is hangin' around, waiting to be scheduled to a node.
- Running: The Pod is all settled in on a node, and its containers are up and running.
- Succeeded: Every container in the Pod finished its job without a hitch.
- Failed: All containers in the Pod are done, but at least one of them didn't make it.
- Unknown: We can't tell you what's up with this Pod. Sorry!
Example:
When you create a Pod using kubectl apply -f pod.yaml
, it starts in the Pending
state while the scheduler finds a node to run it. Once scheduled, it transitions to the Running
state. If the process in the container completes successfully, it moves to Succeeded
. If the process fails, it goes to Failed
.
Question 3: What are ConfigMaps and Secrets in Kubernetes?
Answer: ConfigMaps and Secrets are Kubernetes objects used to manage configuration data and sensitive information separately from the application code.
- ConfigMaps: Store non-confidential configuration data in key-value pairs. Example: A ConfigMap might store database connection strings, feature flags, or external API URLs.
apiVersion: v1
kind: ConfigMap
metadata:
name: example-config
data:
DATABASE_URL: postgres://user:password@hostname/dbname
FEATURE_FLAG: "true"
- Secrets: Store confidential data, such as passwords, OAuth tokens, and SSH keys, in a more secure manner (base64 encoded). Example: A Secret might store a database password.
apiVersion: v1
kind: Secret
metadata:
name: example-secret
type: Opaque
data:
DATABASE_PASSWORD: cGFzc3dvcmQ= # 'password' base64 encoded
Question 4: How does Kubernetes handle Service Discovery?
Answer: Kubernetes provides built-in service discovery to allow applications to find each other within the cluster. This is achieved using the DNS add-on and service objects.
- DNS: When a service is created, Kubernetes adds a DNS entry for it. The service can then be accessed using
<service-name>.<namespace>.svc.cluster.local
. - Environment Variables: Kubernetes also injects environment variables into the Pod for each service.
Example:
If you have a service named my-service
in the default
namespace, other applications can connect to it using my-service.default.svc.cluster.local
.
Question 5: Explain the difference between Deployments and StatefulSets.
Answer: Both Deployments and StatefulSets manage Pods, but they serve different purposes and have different characteristics.
-
Deployments: Best suited for stateless applications. They ensure that the desired number of identical Pod replicas are running at any given time and can handle rolling updates and rollbacks. Example: A web application where each instance is identical and does not need persistent storage.
-
StatefulSets: Designed for stateful applications. They provide guarantees about the ordering and uniqueness of Pods. Each Pod gets a stable, unique network identity, and persistent storage. Example: A database where each instance needs a stable identity and persistent storage.
Example:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: example-statefulset
spec:
serviceName: "example"
replicas: 3
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
containers:
- name: example
image: example/image
volumeMounts:
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
Question 6: What is a Kubernetes DaemonSet and when would you use it?
Answer: A DaemonSet is like a manager that makes sure all (or some) computers in a cluster are running the same program, or Pod. When new computers join the cluster, the manager adds copies of the Pod to them. And when computers leave the cluster, the manager gets rid of the Pods that were running on them.
Use Cases:
- Running a logging agent on every node to collect and ship logs.
- Running a monitoring agent on every node to gather node-specific metrics.
- Deploying a network plugin on every node.
Example:
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: example-daemonset
spec:
selector:
matchLabels:
name: example-daemonset
template:
metadata:
labels:
name: example-daemonset
spec:
containers:
- name: example
image: example/image
Question 7: How does Kubernetes manage resource limits for containers?
Answer: Kubernetes allows you to specify resource requests and limits for containers in terms of CPU and memory.
- Requests: How much computing power and memory is the container promised?
- Limits: How much CPU and memory can a container use at most?
Example:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: example-container
image: example/image
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
Question 8: What is a Kubernetes Ingress and how does it differ from a Service?
Answer: Within a cluster, an Ingress serves as an API object responsible for handling external access to services, primarily through HTTP. Its functions include load balancing, SSL termination, and facilitating virtual hosting based on domain names.
Key Differences:
- Service: Exposes your application internally (ClusterIP) or externally (NodePort, LoadBalancer). It can handle basic load balancing but does not support routing based on the request content.
- Ingress: Provides more advanced routing rules, such as path-based or host-based routing, SSL termination, and more. It requires an Ingress controller to function.
Example:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
spec:
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: example-service
port:
number: 80
Question 9: What are Kubernetes Labels and Selectors?
Answer: Labels are like little tags that you can stick on objects in Kubernetes, like Pods, Services, and Nodes. They help you keep things organized and make it easier to pick out specific objects when you need them.
- Selectors: Allow you to filter objects based on their labels. There are two types of selectors:
- Equality-based:
key=value
orkey!=value
- Set-based:
key in (value1, value2)
orkey notin (value1, value2)
Example:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
labels:
app: example
env: production
spec:
containers:
- name: example-container
image: example/image
To select Pods with the label app=example
:
apiVersion: v1
kind: Service
metadata:
name: example-service
spec:
selector:
app: example
ports:
- protocol: TCP
port: 80
targetPort: 9376
Question 10: Explain the concept of a Kubernetes Job and a CronJob.
Answer:
- Job: A Kubernetes Job whips up a bunch of Pods and makes sure at least a certain number of them finish the task successfully. These Jobs are perfect for tasks that will eventually wrap up, like batch processes.
Example: Running a database migration script.
apiVersion: batch/v1
kind: Job
metadata:
name: example-job
spec:
template:
spec:
containers:
- name: example
image: example/image
command: ["example-command"]
restart command: ["example-command"]
restartPolicy: OnFailure
- CronJob: A CronJob is like a task scheduler that lets you set up jobs to run on a regular basis. It's perfect for things like backing up data or generating reports, because you can tell it to run every day, week, or month, or whatever schedule you need.
Example: Running a backup script every day at midnight.
apiVersion: batch/v1
kind: CronJob
metadata:
name: example-cronjob
spec:
schedule: "0 0 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: example
image: example/image
command: ["example-command"]
restartPolicy: OnFailure
Question 11: How do you perform a rolling update in Kubernetes?
Answer: With a rolling update, you can change your app's version without any downtime. Kubernetes takes care of this using Deployments.
Steps for a Rolling Update:
- Update the Deployment with the new container image version.
- Kube gradually swaps out the old Pods with fresh ones, making sure there's always some Pods up and running.
Example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: example-deployment
spec:
replicas: 3
template:
metadata:
labels:
app: example
spec:
containers:
- name: example-container
image: example/image:v2 # Update the image version here
Apply the updated Deployment:
kubectl apply -f deployment.yaml
Question 12: What is the purpose of the Kubernetes kube-proxy?
Answer: In each node of your Kubernetes cluster, there's this network proxy called kube-proxy. It's like a traffic cop that makes sure your Pods can talk to each other and the outside world. kube-proxy uses iptables or IPVS to direct traffic within the cluster, so things run smoothly and your applications can communicate as they should.
Functions:
- Service Discovery: Enables Pods to communicate with services within the cluster.
- Load Balancing: Distributes traffic among the various Pods backing a service.
Question 13: Explain the concept of a Kubernetes ServiceAccount.
Answer: A ServiceAccount provides an identity for processes running in a Pod. By default, Pods are assigned a default ServiceAccount in their namespace, but you can create custom ServiceAccounts for more granular control over permissions.
Example: Create a ServiceAccount:
kubectl create serviceaccount example-serviceaccount
Use it in a Pod:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
serviceAccountName: example-serviceaccount
containers:
- name: example-container
image: example/image
Question 14: How does Kubernetes handle persistent storage?
Answer: In Kubernetes, you can store data permanently using Persistent Volumes (PVs) and Persistent Volume Claims (PVCs).
-
Persistent Volume (PV):In a cluster, storage is like a designated space that's been set up by an admin or created automatically using Storage Classes.
-
Persistent Volume Claim (PVC): Requested storage by the user.
Example: Define a Persistent Volume:
apiVersion: v1
kind: PersistentVolume
metadata:
name: example-pv
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data"
Claim the Persistent Volume:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: example-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
Use the PVC in a Pod:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: example-container
image: example/image
volumeMounts:
- mountPath: "/data"
name: example-volume
volumes:
- name: example-volume
persistentVolumeClaim:
claimName: example-pvc
Question 15: What are Kubernetes Network Policies?
Answer: Network Policies in Kubernetes are like traffic cops that direct the flow of information between Pods and other network destinations. They make sure that the right data gets to the right place at the right time. They define rules for allowing or denying traffic based on labels, namespaces, and IP blocks.
Example:
A Network Policy that allows traffic to a database Pod only from Pods with the label app=frontend
:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-db-access
spec:
podSelector:
matchLabels:
app: database
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
Question 16: How do you debug a failing Pod in Kubernetes?
Answer: Debugging a failing Pod involves several steps:
- Describe the Pod: Check for events and resource configurations.
kubectl describe pod <pod-name>
- Check Logs: View the container logs.
kubectl logs <pod-name>
- Exec into the Pod: Run commands inside the Pod.
kubectl exec -it <pod-name> -- /bin/sh
- Check the Events: Look for any recent events.
kubectl get events
Question 17: Explain the concept of Helm in Kubernetes.
Answer: Helm is like a toolbox for Kubernetes. It makes it easier to install, manage, and update Kubernetes applications. Helm uses a packaging format called charts, which are basically like bundles of files that describe a specific set of Kubernetes resources.
Key Features:
- Charts: Packages of pre-configured Kubernetes resources.
- Repositories: Collections of charts.
- Releases: Instances of charts running in a Kubernetes cluster.
Example: Install Helm and add a repository:
helm repo add stable https://charts.helm.sh/stable
helm repo update
Install a chart:
helm install my-release stable/nginx
Question 18: What is a Kubernetes Operator?
Answer: A Kubernetes Operator is like a recipe that shows you how to put together, launch, and take care of an application on Kubernetes. Operators extend Kubernetes functionalities by defining custom resources and controllers to manage the application lifecycle.
Example: An Operator for managing a database could automate tasks like backups, scaling, and updates.
Question 19: Explain the concept of Custom Resource Definitions (CRDs) in Kubernetes.
Answer:
With CRDs, you can create your own resources in Kubernetes. These resources can be managed like any other Kubernetes resource, using tools like kubectl
.
Example:
Define a custom resource MyResource
:
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: myresources.example.com
spec:
group: example.com
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
name:
type: string
scope: Namespaced
names:
plural: myresources
singular: myresource
kind: MyResource
Question 20: How does Kubernetes handle application updates and rollbacks?
Answer: Kubernetes handles application updates using Deployments, which support rolling updates and rollbacks.
- Rolling Update: Gradually updates Pods to the new version while keeping the application available.
- Rollback: Reverts to a previous version if the update fails.
Example of a rolling update: Update the Deployment with the new image:
kubectl set image deployment/example-deployment example-container=example/image:v2
Rollback to the previous version if needed:
kubectl rollout undo deployment/example-deployment
Question 21: What is the role of etcd in Kubernetes?
Answer: In Kubernetes, etcd serves as a distributed key-value store, acting as the backbone for storing all cluster data. It assumes responsibility for preserving configuration data, state information, and metadata pertaining to Kubernetes clusters.
Functions:
- State Management: Stores the state of all Kubernetes objects.
- Leader Election: Used by the Kubernetes control plane to perform leader election.
- Configuration Storage: Stores configuration data and metadata.
Question 22: How do you manage node scaling in Kubernetes?
Answer: Node scaling in Kubernetes can be managed manually or automatically using Cluster Autoscaler.
- Manual Scaling: Add or remove nodes using cloud provider interfaces or infrastructure tools.
- Cluster Autoscaler: Changes the number of nodes in a cluster as needed based on how much of the resources are being used.
Example of Cluster Autoscaler: Install Cluster Autoscaler on an AWS cluster:
apiVersion: autoscaling/v1
kind: ClusterAutoscaler
metadata:
name: cluster-autoscaler
spec:
scaleDown:
enabled: true
delayAfterAdd: 10m
delayAfterDelete: 10m
delayAfterFailure: 3m
nodeGroups:
- name: nodegroup
minSize: 1
maxSize: 10
targetSize: 5
Question 23: What is the purpose of Taints and Tolerations in Kubernetes?
Answer: Taints and Tolerations are like two best friends who make sure that Pods don't end up in the wrong place. They work together to prevent Pods from being scheduled on nodes that they're not supposed to be on. Taints are like little flags that nodes can put up to say, "Hey, I'm not a good fit for this type of Pod." Tolerations are like special passes that Pods can carry around that say, "It's okay, I can handle being scheduled on a tainted node." This way, Taints and Tolerations work together to make sure that Pods always end up in the right place.
-
Taints: Applied to nodes to repel certain Pods.
-
Tolerations: Applied to Pods to allow them to be scheduled onto nodes with matching taints.
Example: Taint a node:
kubectl taint nodes node1 key=value:NoSchedule
Add a toleration to a Pod:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
tolerations:
- key: "key"
operator: "Equal"
value: "value"
effect: "NoSchedule"
containers:
- name: example-container
image: example/image
Question 24: Explain the concept of Horizontal Pod Autoscaler (HPA).
Answer: HPA will automatically increase or decrease the number of containers running in a deployment, replica set, or stateful set based on how much CPU they're using or some other measurement..
Example:
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: example-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: example-deployment
minReplicas: 1
maxReplicas: 10
targetCPUUtilizationPercentage: 50
Question 25: What are Kubernetes Admission Controllers?
Answer: Admission Controllers are like bouncers at a party. They make sure that only the right people get in and that everyone follows the rules. They listen in on all the requests that come into the Kubernetes party (API server) before anything gets written down in the guest list (etcd). They can change or even reject requests if they don't like them.
Types:
- Mutating: Modify the requests (e.g., add default values).
- Validating: Validate the requests and potentially reject them.
Example:
The ResourceQuota
admission controller ensures that resource quotas are respected.
Question 26: How does Kubernetes manage secrets?
Answer:
Kubernetes manages secrets using the Secret
object, which stores sensitive data like passwords, OAuth tokens, and SSH keys. Secrets are base64-encoded but not encrypted by default.
Example: Create a Secret:
apiVersion: v1
kind: Secret
metadata:
name: example-secret
type: Opaque
data:
username: dXNlcm5hbWU= # 'username' base64 encoded
password: cGFzc3dvcmQ= # 'password' base64 encoded
Use the Secret in a Pod:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: example-container
image: example/image
env:
- name: USERNAME
valueFrom:
secretKeyRef:
name: example-secret
key: username
- name: PASSWORD
valueFrom:
secretKeyRef:
name: example-secret
key: password
Question 27: What is a Kubernetes Init Container?
Answer: Init Containers run before application containers in a Pod and are used to perform initialization tasks that must be completed before the main application containers start.
Example: An Init Container to set up a configuration file before the main application starts:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
initContainers:
- name: init-container
image: busybox
command: ['sh', '-c', 'echo "configuration data" > /config/config.txt']
volumeMounts:
- mountPath: /config
name: config-volume
containers:
- name: main-container
image: example/image
volumeMounts:
- mountPath: /config
name: config-volume
volumes:
- name: config-volume
emptyDir: {}
Question 28: What are Kubernetes StatefulSets used for?
Answer: StatefulSets are like the managers of stateful applications that need to keep their network identities and storage safe and sound. Each Pod in a StatefulSet has its own unique, rock-solid hostname and storage that won't budge even if the Pod gets deleted or moved around.
Example: Deploying a StatefulSet for a database application:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: example-statefulset
spec:
serviceName: "example"
replicas: 3
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
containers:
- name: example
image: example/image
volumeMounts:
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
Question 29: How does Kubernetes handle node failures?
Answer: Kubernetes handles node failures using node controllers, which detect node failures and take necessary actions to ensure application availability.
Steps Taken:
- Node Status Check: The node controller checks the status of nodes regularly.
- Node Unreachable: If a node becomes unreachable, it marks the node as
NotReady
. - Pod Eviction: Pods running on the failed node are evicted and rescheduled on other healthy nodes if possible.
Question 30: What are Kubernetes Volumes and how are they used?
Answer: Kubernetes Volumes provide a way to persist data beyond the lifetime of a Pod. Volumes can be used for sharing data between containers in a Pod or for persisting data across Pod restarts.
Types of Volumes:
- emptyDir: Ephemeral storage.
- hostPath: Storage on the node's filesystem.
- Persistent Volume: Durable storage managed by the cluster.
Example:
Using an emptyDir
volume to share data between containers:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: container1
image: example/image1
volumeMounts:
- mountPath: /shared
name: shared-volume
- name: container2
image: example/image2
volumeMounts:
- mountPath: /shared
name: shared-volume
volumes:
- name: shared-volume
emptyDir: {}
Next Steps
Kubernetes Interview Questions - Beginner Level
Kubernetes Interview Questions - Medium Level Part 1
Kubernetes Interview Questions - Medium Level Part 2
Kubernetes Interview Questions - Advanced Level Part 1
Kubernetes Interview Questions - Advanced Level Part 2
Kubernetes Interview Questions - Advanced Level Part 3
Kubernetes Interview Questions - Advanced Level Part 4
Share with friends