Kubernetes Snippets - Essential Configuration Examples

Discover essential Kubernetes snippets for Pod Anti-Affinity and Docker socket mounting. Optimize your deployments with these practical configuration examples.

Kubernetes Snippets

Kubernetes Pod Anti-Affinity Configuration

This section provides essential Kubernetes snippets for configuring Pod Anti-Affinity. Pod Anti-Affinity ensures that pods are scheduled on different nodes, enhancing resilience and availability of your applications.

Hard Pod Anti-Affinity

Ensures pods do not run on the same node. This is critical for high availability scenarios.

affinity:
  podAntiAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
            - key: app
              operator: In
              values:
                - bitcoin
        topologyKey: "kubernetes.io/hostname"

An alternative way to specify hard anti-affinity using matchLabels.

affinity:
  podAntiAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchLabels:
            app: bitcoind
        topologyKey: "kubernetes.io/hostname"

Soft Pod Anti-Affinity

This configuration suggests that pods should not run on the same node but does not enforce it strictly. It's useful for balancing resource utilization.

  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchLabels:
              app: bitcoind
          topologyKey: "kubernetes.io/hostname"

Mounting a Docker Socket in Kubernetes

This snippet demonstrates how to mount a Docker socket within a Kubernetes pod. This is often required for containers that need to interact with the Docker daemon, such as CI/CD agents or Docker-in-Docker setups.

      - image: docker:stable-dind
        name: docker-in-docker
        volumeMounts:
          - name: dockersock
            mountPath: "/var/run"
            #mountPath: "/var/run/docker.sock"
        securityContext:
          privileged: true
          allowPrivilegeEscalation: true
      volumes:
      - name: dockersock
        hostPath:
          path: /var/run/docker.sock
          #type: File

Note: Mounting the Docker socket grants significant privileges to the pod. Ensure you understand the security implications before using this configuration.

For more advanced Kubernetes configurations and best practices, refer to the official Kubernetes documentation on node assignment and Docker API documentation.