Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Kubernetes - Best Practices with Code Examples

Introduction

Implementing best practices in Kubernetes ensures that your applications are reliable, scalable, and maintainable. This guide provides an intermediate-level overview of Kubernetes best practices, along with code examples to illustrate these practices.

Key Points:

  • Following best practices helps optimize Kubernetes deployments and operations.
  • Code examples demonstrate how to implement these practices effectively.
  • This guide covers various aspects of Kubernetes best practices, including resource management, security, and observability.

Best Practices for Resource Management

Resource Requests and Limits

Set resource requests and limits to ensure that pods have sufficient resources and to prevent resource contention:

# Example pod specification with resource requests and limits
apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: example-container
    image: nginx
    resources:
      requests:
        memory: "64Mi"
        cpu: "250m"
      limits:
        memory: "128Mi"
        cpu: "500m"
                

Horizontal Pod Autoscaling (HPA)

Use HPA to automatically scale the number of pod replicas based on CPU or memory usage:

# Example HPA configuration
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: example-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: example-deployment
  minReplicas: 1
  maxReplicas: 10
  targetCPUUtilizationPercentage: 80
                
# Apply the HPA configuration kubectl apply -f hpa.yaml

Best Practices for Security

RBAC (Role-Based Access Control)

Implement RBAC to control access to Kubernetes resources:

# Example RBAC configuration
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: default
subjects:
- kind: User
  name: jane
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
                
# Apply the RBAC configuration kubectl apply -f rbac.yaml

Network Policies

Use Network Policies to control the communication between pods:

# Example Network Policy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: example-network-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      role: db
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: frontend
  egress:
  - to:
    - podSelector:
        matchLabels:
          role: frontend
                
# Apply the Network Policy kubectl apply -f network-policy.yaml

Best Practices for Observability

Logging

Implement centralized logging to aggregate logs from all containers and nodes:

# Example Fluentd configuration for log aggregation
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluentd-config
  namespace: kube-system
data:
  fluent.conf: |
    
      @type tail
      path /var/log/containers/*.log
      pos_file /var/log/es-containers.log.pos
      tag kubernetes.*
      format json
      time_key time
      time_format %iso8601
    

    
      @type elasticsearch
      host elasticsearch-logging
      port 9200
      logstash_format true
      include_tag_key true
      type_name access_log
    
                
# Apply the Fluentd configuration kubectl apply -f fluentd-config.yaml

Monitoring

Use Prometheus and Grafana for monitoring and visualizing metrics:

# Example Prometheus configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: prometheus-config
  namespace: monitoring
data:
  prometheus.yml: |
    global:
      scrape_interval: 15s
    scrape_configs:
      - job_name: 'kubernetes'
        kubernetes_sd_configs:
        - role: pod
          namespaces:
            names:
            - default
                
# Apply the Prometheus configuration kubectl apply -f prometheus-config.yaml

Best Practices for Deployment

Rolling Updates

Use rolling updates to update applications without downtime:

# Example Deployment with rolling update strategy
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
                
# Apply the Deployment kubectl apply -f deployment.yaml

Blue-Green Deployment

Implement blue-green deployments to minimize downtime and reduce risk during updates:

# Example Service configuration for blue-green deployment
apiVersion: v1
kind: Service
metadata:
  name: example-service
spec:
  selector:
    app: nginx
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

# Example Deployment for blue environment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-blue
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
      version: blue
  template:
    metadata:
      labels:
        app: nginx
        version: blue
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2

# Example Deployment for green environment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-green
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
      version: green
  template:
    metadata:
      labels:
        app: nginx
        version: green
    spec:
      containers:
      - name: nginx
        image: nginx:1.16.0
                
# Apply the Service and Deployments kubectl apply -f service.yaml kubectl apply -f deployment-blue.yaml kubectl apply -f deployment-green.yaml

Best Practices for Configuration Management

Using ConfigMaps

Use ConfigMaps to manage configuration data for your applications:

# Example ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: example-config
data:
  config.properties: |
    key1=value1
    key2=value2

# Example pod using ConfigMap
apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: example-container
    image: nginx
    volumeMounts:
    - name: config-volume
      mountPath: /etc/config
  volumes:
  - name: config-volume
    configMap:
      name: example-config
                
# Apply the ConfigMap and Pod kubectl apply -f configmap.yaml kubectl apply -f pod.yaml

Best Practices for Secret Management

Using Secrets

Use Secrets to manage sensitive data, such as passwords and API keys:

# Example Secret
apiVersion: v1
kind: Secret
metadata:
  name: example-secret
type: Opaque
data:
  username: YWRtaW4=  # base64 encoded value of 'admin'
  password: MWYyZDFlMmU2N2Rm  # base64 encoded value of '1f2d1e2e67df'

# Example pod using Secret
apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: example-container
    image: nginx
    env:
    - name: USERNAME
      valueFrom:
        secretKeyRef:
          name: example-secret
          key: username
    - name: PASSWORD
      valueFrom:
        secretKeyRef:
          name: example-secret
          key: password
                
# Apply the Secret and Pod kubectl apply -f secret.yaml kubectl apply -f pod.yaml

Conclusion

Implementing Kubernetes best practices ensures that your applications are reliable, secure, and efficient. By following the examples and guidelines provided in this guide, you can optimize your Kubernetes deployments and operations for better performance and maintainability.