What are Useful Kubernetes YAML File Examples?

Kubernetes YAML files are important. We use these files to set up different resources in a Kubernetes cluster. They help us describe how we want our applications to run. We write these files in a way that is easy to read. This makes it simple to manage things like deployments, services, and config maps. These files are very important for working with containerized apps in Kubernetes.

In this article, we will look at some useful examples of Kubernetes YAML files. We will show how to set up deployments, services, config maps, secrets, persistent volumes, and ingress resources. We will also show some Helm chart YAML examples. We will talk about real-life situations where we use these configurations. By learning these examples, we will get better at using Kubernetes YAML files for our apps.

  • What are Good Examples of Kubernetes YAML Files?
  • How to Set Up a Kubernetes Deployment in YAML?
  • What is a Kubernetes Service YAML Example?
  • How to Set Up Kubernetes ConfigMaps with YAML?
  • What Does a Kubernetes Secret YAML File Look Like?
  • How to Make Persistent Volumes and Claims in YAML?
  • What are Real-Life Examples for Kubernetes YAML Files?
  • How to Use YAML for Kubernetes Ingress Resources?
  • What are Helm Chart YAML Examples?
  • Common Questions We Ask

How to Define a Kubernetes Deployment in YAML?

To define a Kubernetes Deployment with YAML, we need to say what we want for our application. This includes how many copies we want, which container image to use, and any settings we need. Here is a simple example of a Kubernetes Deployment YAML file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  labels:
    app: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app-container
        image: my-app-image:latest
        ports:
        - containerPort: 8080
        env:
        - name: ENV_VAR_NAME
          value: "value"

Key Parts of the Deployment YAML:

  • apiVersion: This tells the API version for the Kubernetes object.
  • kind: This shows that this YAML is for a Deployment.
  • metadata: This has information about the Deployment, like the name and labels.
  • spec: This explains what we want, including:
    • replicas: This is how many pod copies we want.
    • selector: This helps us find the pods that this Deployment controls.
    • template: This is the pod template we use to make the pods. It includes the pod’s information and details.
      • containers: This is a list of containers that run in the pod. It shows their image, ports, and environment variables.

We can use this YAML structure to define and manage our Kubernetes Deployments well. For more information on Kubernetes deployments, check out what are Kubernetes deployments and how do I use them.

What is a Kubernetes Service YAML Example?

A Kubernetes Service YAML example shows us how to make an application visible. This application runs on a group of Pods. Services help different parts of a Kubernetes app talk to each other. Below is a simple example of a Kubernetes Service YAML for a web application.

apiVersion: v1
kind: Service
metadata:
  name: my-service
  labels:
    app: my-app
spec:
  type: ClusterIP
  selector:
    app: my-app
  ports:
    - port: 80
      targetPort: 8080
      protocol: TCP

Explanation of Key Fields:

  • apiVersion: This tells us the API version for the Service.
  • kind: This shows what type of object it is, which is Service.
  • metadata: This has the name and labels to identify the Service.
  • spec: This explains the wanted state of the Service.
    • type: This tells the type of Service (like ClusterIP, NodePort, LoadBalancer, etc.).
    • selector: This is a label query for the Pods that should be selected for this Service.
    • ports: This lists the ports that the Service listens to and sends to the target Pods.

This example makes a ClusterIP service named my-service. It sends traffic from port 80 to port 8080 of the Pods that have the label app: my-app. To learn more about Kubernetes services, we can check what are Kubernetes services and how do they expose applications.

How to Configure Kubernetes ConfigMaps Using YAML?

ConfigMaps in Kubernetes help us separate configuration settings from image content. This makes our containerized applications easier to move around. ConfigMaps can store configuration data in key-value pairs. Our applications can then use this data.

Creating a ConfigMap

To create a ConfigMap with a YAML file, we can write it like this:

apiVersion: v1
kind: ConfigMap
metadata:
  name: example-config
  namespace: default
data:
  DATABASE_URL: "postgres://user:password@hostname:port/dbname"
  APP_MODE: "production"

Applying the ConfigMap

After we define our ConfigMap in a YAML file (like configmap.yaml), we can create it in our Kubernetes cluster with this command:

kubectl apply -f configmap.yaml

Using ConfigMap in Pods

We can use the ConfigMap in our Pods by adding it to our Pod specification. Here is an example of a Pod that uses the ConfigMap:

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: example-container
    image: example-image
    env:
      - name: DATABASE_URL
        valueFrom:
          configMapKeyRef:
            name: example-config
            key: DATABASE_URL
      - name: APP_MODE
        valueFrom:
          configMapKeyRef:
            name: example-config
            key: APP_MODE

Mounting ConfigMap as a Volume

We can also mount a ConfigMap as a volume inside our Pods. This allows our application to read the configuration data as files. Here is how to do it:

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: example-container
    image: example-image
    volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: example-config

This setup mounts the whole ConfigMap as files in the /etc/config directory of the container.

Updating a ConfigMap

To update a ConfigMap, we can change the YAML file and apply it again:

kubectl apply -f configmap.yaml

If we want to edit it directly, we can use:

kubectl edit configmap example-config

This lets us update the key-value pairs without stopping our application.

For more information on ConfigMaps, we can read the article on Kubernetes ConfigMaps.

What Does a Kubernetes Secret YAML File Look Like?

Kubernetes Secrets help us store sensitive information. This includes passwords, OAuth tokens, and SSH keys. We store this data in a base64 encoded format. This way, it does not show in plaintext. Here is an example of a Kubernetes Secret in a YAML file.

apiVersion: v1
kind: Secret
metadata:
  name: my-secret
  namespace: default
type: Opaque
data:
  username: bXlVc2VybmFtZQ==  # base64 encoded value of 'myUsername'
  password: cGFzc3dvcmQ=      # base64 encoded value of 'password'

In this example:

  • apiVersion shows the version of the Kubernetes API.
  • kind tells us that this is a Secret.
  • metadata has the name and namespace of the Secret.
  • type shows the type of Secret. Opaque is the most common type.
  • data keeps key-value pairs. The values are base64 encoded.

To create a Secret from a file, we can use this command:

kubectl create secret generic my-secret --from-file=path/to/your/file

This command reads the file we specify. It creates a Secret with the file’s name as the key and the file’s contents as the value.

For more details about managing secrets in Kubernetes, we can check how to manage secrets in Kubernetes securely.

How to Create Persistent Volumes and Claims in YAML?

To make persistent storage in Kubernetes, we define PersistentVolumes (PV) and PersistentVolumeClaims (PVC) using YAML format. Below are some simple examples to help us set up both.

Persistent Volume (PV) Example

This example shows how to create a PersistentVolume that uses hostPath for storage.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: my-pv
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: /mnt/data

Persistent Volume Claim (PVC) Example

In this example, we create a PersistentVolumeClaim. This request storage from the PersistentVolume we defined above.

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi

Dynamic Provisioning Example

If we use a storage class for dynamic provisioning, we can specify the storage class in our PVC. Here is a simple example:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-dynamic-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
  storageClassName: standard

To view the PersistentVolumes and Claims we created, we run:

kubectl get pv
kubectl get pvc

For more details about Kubernetes volumes, we can check out Kubernetes Volumes.

What are Real-Life Use Cases for Kubernetes YAML Files?

Kubernetes YAML files are very important for defining and managing resources in a Kubernetes cluster. Here are some common use cases we can see in real life:

  1. Microservices Deployment: We use Kubernetes YAML files to deploy microservices. Each service can be configured separately. For example, deploying a simple microservice stack may need many YAML files. Each file will define a different service.

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: user-service
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: user
      template:
        metadata:
          labels:
            app: user
        spec:
          containers:
          - name: user-service
            image: myregistry/user-service:v1
            ports:
            - containerPort: 8080
  2. Configuring Networking with Ingress: We can use YAML files to define Ingress resources. This helps us manage external access to services. It is helpful for routing, SSL termination, and host-based routing.

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      name: my-ingress
    spec:
      rules:
      - host: myapp.example.com
        http:
          paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: user-service
                port:
                  number: 8080
  3. Managing Configuration with ConfigMaps: ConfigMaps help us store configuration data. Applications can use this data. It makes it easier to update and manage settings.

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: app-config
    data:
      database_url: "postgres://user:password@db:5432/mydb"
      feature_flags: "true"
  4. Secret Management: We can use Kubernetes YAML files to keep sensitive information safe. This includes API keys and passwords. We use Secrets for this.

    apiVersion: v1
    kind: Secret
    metadata:
      name: db-secret
    type: Opaque
    data:
      username: dXNlcm5hbWU= # base64 encoded
      password: cGFzc3dvcmQ= # base64 encoded
  5. Persistent Storage Configuration: YAML files can define Persistent Volumes (PV) and Persistent Volume Claims (PVC). These are very important for applications that need to save data.

    apiVersion: v1
    kind: PersistentVolume
    metadata:
      name: my-pv
    spec:
      capacity:
        storage: 10Gi
      accessModes:
        - ReadWriteOnce
      hostPath:
        path: /data
    ---
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
      name: my-pvc
    spec:
      accessModes:
        - ReadWriteOnce
      resources:
        requests:
          storage: 5Gi
  6. Autoscaling Applications: We can define Horizontal Pod Autoscalers in YAML. This helps scale applications automatically based on CPU usage or other metrics.

    apiVersion: autoscaling/v2beta2
    kind: HorizontalPodAutoscaler
    metadata:
      name: user-service-hpa
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: user-service
      minReplicas: 2
      maxReplicas: 10
      metrics:
      - type: Resource
        resource:
          name: cpu
          target:
            type: Utilization
            averageUtilization: 80
  7. Continuous Deployment Pipelines: YAML files are used in CI/CD pipelines. They help define deployment strategies. This makes sure applications are deployed smoothly with little downtime.

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: myapp
    spec:
      replicas: 3
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxSurge: 1
          maxUnavailable: 0
      template:
        metadata:
          labels:
            app: myapp
        spec:
          containers:
          - name: myapp
            image: myregistry/myapp:v2

These use cases show how flexible and powerful Kubernetes YAML files are. They help us manage complex applications. We can do easy deployments, manage configurations, and scale our applications. For more information on Kubernetes and its parts, we can read what are the key components of a Kubernetes cluster.

How to Use YAML for Kubernetes Ingress Resources?

Kubernetes Ingress resources help us manage how users access services outside the cluster. Usually, we use HTTP for this. Here is a simple way to define an Ingress resource with YAML.

Basic Ingress Example

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: example-service
            port:
              number: 80

Explanation of Key Properties

  • apiVersion: This shows the version of the API for Ingress resource.
  • kind: This tells us the type of resource. Here, it is Ingress.
  • metadata: This has the name and annotations for the Ingress.
  • spec: This sets the rules for routing traffic.
    • rules: This includes a list of hostnames and paths.
    • http: This shows how to route HTTP traffic.
    • paths: This tells us the rules for path-based routing. It routes traffic to the backend service.

TLS Configuration

If we want to secure our Ingress with TLS, we need to add a TLS section:

spec:
  tls:
  - hosts:
    - example.com
    secretName: example-tls
  rules:
  - host: example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: example-service
            port:
              number: 80

Using Multiple Paths

We can define many paths and services in one Ingress resource:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: multi-path-ingress
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /app1
        pathType: Prefix
        backend:
          service:
            name: app1-service
            port:
              number: 80
      - path: /app2
        pathType: Prefix
        backend:
          service:
            name: app2-service
            port:
              number: 80

Ingress Annotations

We can use annotations to set special features for the Ingress controller. For example, to enable SSL redirection with NGINX, we write:

metadata:
  annotations:
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"

By using these YAML settings for Kubernetes Ingress resources, we can manage external access to our applications in the cluster easily. If we want to know more about Kubernetes configurations, we can check the article on Kubernetes Services.

What are Helm Chart YAML Examples?

Helm is a tool for Kubernetes. It helps us to deploy and manage applications easily. Helm Charts are groups of YAML files. They describe the Kubernetes resources we need to run an application. Here are some useful examples of Helm Chart YAML files:

Chart.yaml

The Chart.yaml file holds important information about the chart. This includes its name, version, and description.

apiVersion: v2
name: my-application
description: A Helm chart for Kubernetes
type: application
version: 1.0.0
appVersion: "1.0"

values.yaml

The values.yaml file lets us set default values for the chart. We can change these values when we install it.

replicaCount: 3

image:
  repository: my-docker-repo/my-application
  tag: latest
  pullPolicy: IfNotPresent

service:
  enabled: true
  type: ClusterIP
  port: 80

resources: {}

templates/deployment.yaml

The deployment.yaml file defines the Deployment resource. It uses values from values.yaml.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Release.Name }}-deployment
  labels:
    app: {{ .Release.Name }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app: {{ .Release.Name }}
    spec:
      containers:
        - name: {{ .Release.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          ports:
            - name: http
              containerPort: 80
          resources:
            {{- toYaml .Values.resources | nindent 12 }}

templates/service.yaml

The service.yaml file defines the Service resource for the application.

apiVersion: v1
kind: Service
metadata:
  name: {{ .Release.Name }}-service
spec:
  type: {{ .Values.service.type }}
  ports:
    - port: {{ .Values.service.port }}
  selector:
    app: {{ .Release.Name }}

templates/ingress.yaml

The ingress.yaml file defines the Ingress resource. This allows outside access to the service.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ .Release.Name }}-ingress
spec:
  rules:
    - host: {{ .Values.ingress.host }}
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: {{ .Release.Name }}-service
                port:
                  number: {{ .Values.service.port }}

These examples show us how to organize a Helm chart with YAML files. Each file is important for setting up the deployment. This makes it easier for us to manage Kubernetes applications. For more details about Helm and how to use it, we can look at this article on Helm.

Frequently Asked Questions

What are the common components in Kubernetes YAML files?

Kubernetes YAML files usually have parts like Pods, Deployments, Services, ConfigMaps, and Secrets. Each part has a special job in managing container apps. For example, Pods are the smallest units we can deploy. Deployments help us with scaling and updating these Pods. Knowing these parts is important for using Kubernetes YAML files well.

How can I validate my Kubernetes YAML files?

To make sure our Kubernetes YAML files are correct, we can use tools like kubectl to check them. We can run kubectl apply --dry-run=client -f <your-file>.yaml to find syntax errors without changing our cluster. Also, online linters and IDE plugins can help us find common mistakes. This makes our Kubernetes YAML files better for deployments.

What are the best practices for organizing Kubernetes YAML files?

Organizing Kubernetes YAML files well helps us keep things easy to manage and work together. We should group related resources into folders based on what they do. For example, we can have folders like deployments, services, or configmaps. Using a naming style for our files and adding comments in the YAML files can help make things clear. For more tips on managing Kubernetes resources, check our article on Kubernetes deployments.

How do I manage secrets in Kubernetes using YAML?

We can define Kubernetes Secrets in YAML files to keep sensitive info safe, like passwords or API keys. A typical Secrets YAML file has apiVersion, kind, and data fields. The data field has base64-encoded values. For a full guide on working with Secrets, look at our resource on managing secrets in Kubernetes.

Can I automate Kubernetes YAML deployments?

Yes, we can automate our Kubernetes YAML deployments using CI/CD pipelines. Tools like Jenkins, GitLab CI, or GitHub Actions can be set up to deploy Kubernetes resources automatically when we change our YAML files in version control. This way, we can make sure the deployment process is the same every time. It also makes our applications more reliable in a Kubernetes environment. For more insights, check out our article on using Helm for Kubernetes deployments.