### Init Containers for Database and Configuration Setup Source: https://context7.com/stakater/application/llms.txt Demonstrates the use of init containers to perform setup tasks before the main application container starts. Includes waiting for a database service, running database migrations, and downloading configuration files. These containers ensure dependencies are met and the environment is ready. ```yaml initContainers: wait-for-db: image: busybox:1.35 imagePullPolicy: IfNotPresent command: - sh - -c - "until nslookup postgres.database.svc.cluster.local; do echo waiting for database; sleep 2; done" migrate-db: image: docker.io/migrate/migrate:v4.15.2 imagePullPolicy: IfNotPresent command: ["/bin/sh"] args: - "-c" - "migrate -path=/migrations -database=$DATABASE_URL up" env: - name: DATABASE_URL valueFrom: secretKeyRef: name: db-connection key: url volumeMounts: - name: migrations mountPath: /migrations download-config: image: curlimages/curl:latest command: - sh - -c - "curl -o /config/app-config.json https://config-server/config" volumeMounts: - name: config-cache mountPath: /config ``` -------------------------------- ### Health Probes Configuration for Applications Source: https://context7.com/stakater/application/llms.txt Example `values.yaml` demonstrating health probe configuration, including startup, readiness, and liveness probes using HTTP GET requests. Specifies probe parameters like failure threshold and period. ```yaml # values.yaml - Health probe configuration deployment: enabled: true # Startup probe - allows slow-starting applications more time to initialize startupProbe: enabled: true httpGet: path: /health/startup port: 8080 failureThreshold: 30 periodSeconds: 10 successThreshold: 1 timeoutSeconds: 1 # Readiness probe - determines when pod should receive traffic readinessProbe: enabled: true httpGet: path: /health/ready port: 8080 failureThreshold: 3 periodSeconds: 10 successThreshold: 1 timeoutSeconds: 5 # Liveness probe - determines when to restart container livenessProbe: enabled: true httpGet: path: /health/live port: 8080 failureThreshold: 3 periodSeconds: 10 successThreshold: 1 timeoutSeconds: 5 ``` -------------------------------- ### Install and Manage Application Helm Chart Source: https://context7.com/stakater/application/llms.txt Commands to add the Helm repository, update cache, install, upgrade, and uninstall the Application Helm Chart. Assumes Helm is installed and configured. ```bash # Add the Stakater Helm repository helm repo add stakater https://stakater.github.io/stakater-charts # Update repository cache helm repo update # Install chart with release name 'my-application' in namespace 'test' helm install my-application stakater/application --namespace test # Install with custom values file helm install my-application stakater/application \ --namespace test \ --values custom-values.yaml # Upgrade existing release helm upgrade my-application stakater/application \ --namespace test \ --values custom-values.yaml # Uninstall the chart helm delete --namespace test my-application ``` -------------------------------- ### Basic Web Application Deployment Configuration Source: https://context7.com/stakater/application/llms.txt Example `values.yaml` for a basic web application deployment. Configures application name, deployment settings (replicas, image, resources, ports, env), service, and ingress. ```yaml # values.yaml - Basic web application deployment applicationName: my-web-app deployment: enabled: true replicas: 3 image: repository: docker.io/myorg/myapp tag: v1.2.3 pullPolicy: IfNotPresent resources: requests: memory: 256Mi cpu: 100m limits: memory: 512Mi cpu: 500m ports: - name: http containerPort: 8080 protocol: TCP env: APP_ENV: value: production LOG_LEVEL: value: info service: enabled: true type: ClusterIP ports: - name: http port: 80 targetPort: 8080 protocol: TCP ingress: enabled: true ingressClassName: nginx hosts: - host: myapp.example.com paths: - path: / pathType: Prefix serviceName: my-web-app servicePort: http tls: - secretName: myapp-tls hosts: - myapp.example.com ``` -------------------------------- ### Configure HTTP Get Liveness Probe - YAML Source: https://github.com/stakater/application/blob/main/README.md This snippet demonstrates configuring the liveness probe to use the 'httpGet' handler. It includes enabling the probe and specifying the path and port for the HTTP request. ```yaml livenessProbe: enabled: true httpGet: path: '/path' port: 8080 ``` -------------------------------- ### Environment Variables Configuration (Direct Values) Source: https://context7.com/stakater/application/llms.txt Example `values.yaml` snippet showing how to configure simple environment variables for a deployment by directly specifying their values. Suitable for static configuration parameters. ```yaml # values.yaml - Direct environment variable values deployment: env: DATABASE_HOST: value: postgres.database.svc.cluster.local DATABASE_PORT: value: "5432" API_TIMEOUT: value: "30" FEATURE_FLAG_NEW_UI: value: "true" ``` -------------------------------- ### Consuming Environment Variables from ConfigMap using envFrom Source: https://github.com/stakater/application/blob/main/README.md Demonstrates how to consume all key-value pairs from a ConfigMap as environment variables using `envFrom`. This simplifies the process when many variables need to be exposed from a single ConfigMap. You can specify a `nameSuffix` for the ConfigMap or a static `name`. The `optional` field indicates if the pod can start without the ConfigMap. ```yaml envFrom: application-config-env: type: configmap nameSuffix: application-config ``` -------------------------------- ### Topology Spread Constraints for Even Pod Distribution Source: https://context7.com/stakater/application/llms.txt Configures how pods are spread across topology domains like zones or nodes. This example uses topologySpreadConstraints to ensure pods are distributed evenly, preventing over-concentration in a single domain for improved availability and performance. ```yaml topologySpreadConstraints: - maxSkew: 1 topologyKey: topology.kubernetes.io/zone whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: app.kubernetes.io/name: my-application - maxSkew: 2 topologyKey: kubernetes.io/hostname whenUnsatisfiable: ScheduleAnyway labelSelector: matchLabels: app.kubernetes.io/name: my-application ``` -------------------------------- ### Alternative Health Probe Types (Exec, TCP, gRPC) Source: https://context7.com/stakater/application/llms.txt Configuration examples for alternative health probe types: Exec-based, TCP Socket, and gRPC probes within the `values.yaml` file. Useful for applications with different health check mechanisms. ```yaml # Exec-based probe deployment: livenessProbe: enabled: true exec: command: - cat - /tmp/healthy failureThreshold: 3 periodSeconds: 10 # TCP Socket probe deployment: readinessProbe: enabled: true tcpSocket: port: 8080 failureThreshold: 3 periodSeconds: 10 # gRPC probe deployment: startupProbe: enabled: true grpc: port: 9090 service: myservice failureThreshold: 30 periodSeconds: 10 ``` -------------------------------- ### Node Affinity Configuration for Specific Node Types Source: https://context7.com/stakater/application/llms.txt Specifies requirements for nodes on which pods can be scheduled based on node labels. This example uses 'requiredDuringSchedulingIgnoredDuringExecution' to ensure pods only run on nodes of specific instance types (e.g., c5.large, c5.xlarge). ```yaml nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: node.kubernetes.io/instance-type operator: In values: - c5.large - c5.xlarge - c5.2xlarge ``` -------------------------------- ### Configure Exec Liveness Probe - YAML Source: https://github.com/stakater/application/blob/main/README.md This snippet illustrates how to configure the liveness probe to use the 'exec' handler. It involves enabling the probe and providing the command to be executed as a list of strings. ```yaml livenessProbe: enabled: true exec: command: - cat - /tmp/healthy ``` -------------------------------- ### Consuming Simple Key/Value Environment Variables in Deployment/CronJob Source: https://github.com/stakater/application/blob/main/README.md Illustrates how to define simple key-value environment variables for deployments or cron jobs. The `env` block is used, where each environment variable key is provided with a `value` field specifying its string value. This is the most straightforward method for setting environment variables. ```yaml env: KEY: value: MY_VALUE ``` -------------------------------- ### Configure Kubernetes Services for ClusterIP, headless, and LoadBalancer types Source: https://context7.com/stakater/application/llms.txt Demonstrates three service configuration patterns for different use cases. Includes a standard ClusterIP service with multiple ports for web and metrics, a headless service for stateful applications, and a LoadBalancer service with MetalLB integration. Each configuration includes annotations for monitoring and load balancing. ```yaml # values.yaml - Various service configurations # ClusterIP service (default) service: enabled: true type: ClusterIP ports: - name: http port: 80 targetPort: 8080 protocol: TCP - name: metrics port: 9090 targetPort: 9090 protocol: TCP additionalLabels: monitoring: prometheus annotations: prometheus.io/scrape: "true" prometheus.io/port: "9090" # Headless service for StatefulSet-like patterns service: enabled: true type: ClusterIP clusterIP: None # Creates headless service ports: - name: peer port: 2380 targetPort: 2380 # LoadBalancer service service: enabled: true type: LoadBalancer loadBalancerClass: metallb.io/metallb ports: - name: http port: 80 targetPort: 8080 annotations: metallb.universe.tf/address-pool: public-pool ``` -------------------------------- ### Configure container lifecycle hooks in Helm values.yaml Source: https://context7.com/stakater/application/llms.txt This snippet defines lifecycle hooks, security contexts, command arguments, and deployment strategy for a Kubernetes pod. It includes postStart and preStop exec commands, DNS settings, and resource limits. Suitable for Helm charts deploying applications that need graceful startup and shutdown handling. ```yaml deployment: enabled: true # Host network for applications that need it hostNetwork: false # Graceful shutdown configuration terminationGracePeriodSeconds: 60 # Minimum ready time before considering pod available minReadySeconds: 10 # Container lifecycle hooks lifecycle: postStart: exec: command: - /bin/sh - -c - "echo 'Container started' > /tmp/startup && curl -X POST http://monitor/started" preStop: exec: command: - /bin/sh - -c - | # Graceful shutdown: stop accepting traffic and drain connections touch /tmp/shutdown sleep 15 curl -X POST http://monitor/stopping # DNS configuration dnsPolicy: ClusterFirst dnsConfig: options: - name: ndots value: "1" - name: use-vc - name: timeout value: "2" nameservers: - 8.8.8.8 searches: - my-namespace.svc.cluster.local - svc.cluster.local # Host aliases for custom DNS entries hostAliases: - ip: "127.0.0.1" hostnames: - "localhost.local" - ip: "10.20.30.40" hostnames: - "legacy-api.example.com" # Security context at pod level securityContext: runAsUser: 1000 runAsGroup: 3000 fsGroup: 2000 fsGroupChangePolicy: OnRootMismatch seccompProfile: type: RuntimeDefault # Security context at container level containerSecurityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true runAsNonRoot: true runAsUser: 1000 capabilities: drop: - ALL add: - NET_BIND_SERVICE # Custom command and args command: ["/app/server"] args: - "--config=/etc/config/app.yaml" - "--log-level=info" - "--port=8080" # Deployment strategy strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 25% maxSurge: 25% # Revision history limit revisionHistoryLimit: 5 # Automatic reload on ConfigMap/Secret changes reloadOnChange: true # Image pull secrets imagePullSecrets: - name: docker-registry-secret - name: private-registry-secret ``` -------------------------------- ### Configure Forecastle Application Discovery Portal Source: https://context7.com/stakater/application/llms.txt Configures Forecastle discovery portal integration with application metadata. Displays application in portal with custom icon, grouping, and properties. Requires ingress to be enabled. ```yaml forecastle: enabled: true displayName: My Application group: Production Apps icon: https://raw.githubusercontent.com/stakater/ForecastleIcons/master/application.png networkRestricted: false properties: Version: v1.2.3 Team: Platform Engineering Documentation: https://docs.example.com/my-app Repository: https://github.com/example/my-app additionalLabels: category: web-application environment: production ingress: enabled: true hosts: - host: app.example.com paths: - path: / pathType: Prefix ``` -------------------------------- ### Set up Kubernetes Ingress with TLS termination and rate limiting Source: https://context7.com/stakater/application/llms.txt Configures NGINX Ingress with TLS certificates managed by cert-manager for secure HTTPS access. Supports multiple hostnames with path-based routing for web and API endpoints. Includes rate limiting annotations and separate TLS secrets for different domains. ```yaml # values.yaml - Ingress with TLS applicationName: my-web-app ingress: enabled: true ingressClassName: nginx annotations: cert-manager.io/cluster-issuer: letsencrypt-prod nginx.ingress.kubernetes.io/ssl-redirect: "true" nginx.ingress.kubernetes.io/rate-limit: "100" hosts: - host: app.example.com paths: - path: / pathType: Prefix serviceName: my-web-app servicePort: http - path: /api pathType: Prefix serviceName: my-web-app servicePort: http - host: api.example.com paths: - path: / pathType: Prefix serviceName: my-web-app servicePort: http tls: - secretName: app-tls hosts: - app.example.com - secretName: api-tls hosts: - api.example.com ``` -------------------------------- ### Configure OpenShift Route Source: https://context7.com/stakater/application/llms.txt Sets up an OpenShift Route to expose an application. This configuration specifies the hostname, path, port, backend services, TLS termination settings, and annotations for router behavior. ```yaml # values.yaml - OpenShift Route configuration route: enabled: true host: myapp.apps.openshift.example.com path: / port: targetPort: http to: weight: 100 alternateBackends: - name: my-app-canary weight: 10 tls: termination: edge insecureEdgeTerminationPolicy: Redirect wildcardPolicy: None additionalLabels: app.openshift.io/runtime: nodejs annotations: haproxy.router.openshift.io/rate-limit-connections: "true" ``` -------------------------------- ### Define Kubernetes Job for database migration with Helm hooks Source: https://context7.com/stakater/application/llms.txt Configures a one-time Kubernetes Job for running database migrations before application deployment. Uses Helm lifecycle hooks to execute pre-install and pre-upgrade, with automatic cleanup after completion. Includes init container for service dependency management and resource constraints for controlled execution. ```yaml # values.yaml - Database migration job applicationName: my-application job: enabled: true jobs: db-migration: # Helm hook annotations for running before install/upgrade additionalPodAnnotations: helm.sh/hook: "pre-install,pre-upgrade" helm.sh/hook-weight: "-1" helm.sh/hook-delete-policy: "before-hook-creation" backoffLimit: 3 completions: 1 parallelism: 1 activeDeadlineSeconds: 600 ttlSecondsAfterFinished: 300 image: repository: docker.io/migrate/migrate tag: v4.15.2 pullPolicy: IfNotPresent command: ["/bin/sh"] args: - "-c" - "migrate -path=/migrations -database=$DATABASE_URL up" env: DATABASE_URL: valueFrom: secretKeyRef: name: my-application-db-url key: url resources: requests: memory: 128Mi cpu: 100m limits: memory: 256Mi cpu: 200m initContainers: wait-for-db: image: busybox command: - sh - -c - "until nc -z postgres 5432; do echo waiting for db; sleep 2; done" ``` -------------------------------- ### Configure Velero backup schedule and settings in Helm values.yaml Source: https://context7.com/stakater/application/llms.txt This snippet sets up Velero (or OADP) backup options, including a daily Cron schedule, retention period, storage location, and volume snapshot behavior. It also defines namespace and resource inclusion/exclusion, label selectors, and additional backup labels. Ideal for automating disaster recovery of Kubernetes resources. ```yaml backup: enabled: true namespace: my-namespace # Schedule using CronJob syntax schedule: "0 2 * * *" # Daily at 2 AM # Backup retention ttl: 720h0m0s # 30 days # Storage location for backups storageLocation: default # Snapshot persistent volumes snapshotVolumes: true # Use Restic for file-level backup defaultVolumesToRestic: true # Include specific namespaces includedNamespaces: - "{{ include \"application.namespace\" $ }}" - my-namespace # Include only specific resource types includedResources: - deployments - configmaps - secrets - services - persistentvolumeclaims # Exclude specific resource types excludedResources: - events - events.events.k8s.io # Label selector for resources to backup labelSelector: matchLabels: backup: enabled # Ordered backup of resources orderedResources: pods: "deployment.kubernetes.io/name" additionalLabels: backup-type: application retention: long-term annotations: backup.velero.io/backup-volumes: data-volume,config-volume ``` -------------------------------- ### Configure IngressMonitorController for Endpoint Monitoring Source: https://context7.com/stakater/application/llms.txt Sets up endpoint monitoring with UptimeRobot and StatusCake providers. Requires ingress controller and proper DNS configuration. Supports HTTPS enforcement and custom health endpoints. ```yaml endpointMonitor: enabled: true additionalLabels: monitoring: imc annotations: uptime.stakater.com/enabled: "true" # Endpoint monitoring configuration forceHttps: true url: https://app.example.com healthEndpoint: /health providers: - name: UptimeRobot config: alertContacts: "0544483_0_0-2628365_0_0" interval: 300 monitorType: https - name: StatusCake config: checkRate: 300 testType: HTTP contactGroup: "platform-team" ``` -------------------------------- ### ConfigMap configuration and environment injection Source: https://context7.com/stakater/application/llms.txt Defines a ConfigMap to hold non-sensitive application settings and shows how to reference specific keys or load all keys as environment variables in a Deployment. Suitable for DEBUG-level logging, TTLs, and connection limits. ```yaml applicationName: my-application configMap: enabled: true files: application-config: LOG_LEVEL: DEBUG VERBOSE: v1 CACHE_TTL: "3600" MAX_CONNECTIONS: "100" deployment: # Reference specific ConfigMap key env: APP_LOG_LEVEL: valueFrom: configMapKeyRef: name: my-application-application-config key: LOG_LEVEL # Load all ConfigMap keys as environment variables envFrom: application-config-env: type: configmap nameSuffix: application-config optional: false ``` -------------------------------- ### Consuming Environment Variables from ConfigMap using valueFrom Source: https://github.com/stakater/application/blob/main/README.md Shows how to consume environment variables from a ConfigMap using `valueFrom.configMapKeyRef`. This method allows specific keys from a ConfigMap to be injected as environment variables into a pod. It requires specifying the ConfigMap name and the key within that ConfigMap. ```yaml env: APP_LOG_LEVEL: valueFrom: configMapKeyRef: name: my-application-application-config key: LOG ``` -------------------------------- ### Volumes and persistence (PVC, emptyDir, configMap volume) Source: https://context7.com/stakater/application/llms.txt Configures persistent volume claims for application data, plus ephemeral cache using emptyDir. Also mounts a ConfigMap as a volume for static files. Includes cloud storage class and provisioner annotations for AWS EBS CSI. ```yaml applicationName: data-processor persistence: enabled: true mountPVC: true mountPath: /data name: data-processor-storage accessMode: ReadWriteOnce storageClass: fast-ssd storageSize: 50Gi volumeMode: Filesystem additionalLabels: storage-tier: premium annotations: volume.beta.kubernetes.io/storage-provisioner: ebs.csi.aws.com deployment: enabled: true volumes: config-volume: configMap: name: app-config cache-volume: emptyDir: sizeLimit: 1Gi volumeMounts: config-volume: mountPath: /etc/config readOnly: true cache-volume: mountPath: /tmp/cache readOnly: false ``` -------------------------------- ### Sidecar Containers for Logging and Metrics Source: https://context7.com/stakater/application/llms.txt Illustrates the implementation of sidecar containers that run alongside the main application container. These include a log shipper (fluent-bit) for log aggregation and a metrics exporter (statsd-exporter) for collecting application metrics. They enhance observability and management capabilities. ```yaml additionalContainers: - name: log-shipper image: fluent/fluent-bit:2.0 resources: requests: memory: 64Mi cpu: 50m limits: memory: 128Mi cpu: 100m volumeMounts: - name: log-volume mountPath: /var/log - name: fluent-bit-config mountPath: /fluent-bit/etc - name: metrics-exporter image: prom/statsd-exporter:v0.24.0 ports: - name: metrics containerPort: 9102 protocol: TCP resources: requests: memory: 32Mi cpu: 25m ``` -------------------------------- ### Kubernetes Pod Disruption Budget Configuration using values.yaml Source: https://context7.com/stakater/application/llms.txt This snippet shows how to configure a Pod Disruption Budget (PDB) in a values.yaml file for Kubernetes. It outlines parameters like `minAvailable` and `maxUnavailable` to ensure a minimum number of pods remain available during voluntary disruptions. Dependencies include the Kubernetes PDB API. ```yaml # values.yaml - PodDisruptionBudget pdb: enabled: true minAvailable: 2 # Minimum pods that must remain available additionalLabels: criticality: high annotations: description: "Ensure minimum availability during disruptions" # Alternative: maxUnavailable approach pdb: enabled: true maxUnavailable: 1 # Maximum pods that can be unavailable ``` -------------------------------- ### Deploy Extra Kubernetes Objects and Custom Resources Source: https://context7.com/stakater/application/llms.txt Deploys additional Kubernetes resources including ConfigMaps, Secrets, and Custom Resources. Supports templating and multiple definition formats. Useful for application-specific configurations. ```yaml extraObjects: # Can be defined as a list - apiVersion: v1 kind: ConfigMap metadata: name: custom-config namespace: "{{ include \"application.namespace\" $ }}" data: custom.conf: | key=value - apiVersion: v1 kind: Secret metadata: name: custom-secret namespace: "{{ include \"application.namespace\" $ }}" type: Opaque stringData: token: custom-token-value # Alternative: define as object (keys ignored, only values used) extraObjects: monitoring-config: apiVersion: v1 kind: ConfigMap metadata: name: prometheus-rules labels: prometheus: kube-prometheus data: rules.yaml: | groups: - name: custom-rules rules: - alert: CustomAlert expr: up == 0 custom-resource: apiVersion: custom.io/v1 kind: CustomResource metadata: name: my-custom-resource spec: replicas: 3 config: enabled: true # Using raw YAML string with templating extraObjects: raw-manifest: | apiVersion: v1 kind: Service metadata: name: external-service namespace: {{ include "application.namespace" $ }} spec: type: ExternalName externalName: external-api.example.com ``` -------------------------------- ### Configure Gateway API HTTPRoute Source: https://context7.com/stakater/application/llms.txt Configures an HTTPRoute for the Gateway API, defining hostnames, path matching, header conditions, and backend service references. It supports multiple hostnames and path-based routing with specific versioning. ```yaml # values.yaml - Gateway API configuration httpRoute: enabled: true gatewayNamespace: gateway-system useDefaultGateways: internal parentRefs: - name: internal-gateway namespace: gateway-system sectionName: https hostnames: - app.example.com - www.app.example.com rules: - matches: - path: type: PathPrefix value: /api headers: - name: X-API-Version value: v2 backendRefs: - name: "{{ include \"application.name\" $ }}" port: 8080 weight: 100 - matches: - path: type: PathPrefix value: / backendRefs: - name: "{{ include \"application.name\" $ }}" port: 8080 additionalLabels: gateway: internal annotations: external-dns.alpha.kubernetes.io/hostname: app.example.com ``` -------------------------------- ### Grafana Dashboard Configuration for Stakater Application Source: https://context7.com/stakater/application/llms.txt Defines Grafana dashboard configurations, allowing dashboards to be loaded either from a URL or directly via inline JSON. This enables visualization of application metrics and overview within Grafana. Configured in values.yaml. ```yaml # values.yaml - Grafana dashboard deployment grafanaDashboard: enabled: true additionalLabels: grafana: main annotations: grafana.com/folder: Applications contents: app-overview: # Option 1: Load from URL url: https://raw.githubusercontent.com/example/dashboards/main/app-dashboard.json app-metrics: # Option 2: Inline JSON dashboard json: | { "dashboard": { "title": "Application Metrics", "panels": [ { "title": "Request Rate", "targets": [ { "expr": "rate(http_requests_total[5m])" } ] } ] } } ``` -------------------------------- ### Kubernetes Pod Scheduling with Node Selectors and Taints/Tolerations Source: https://context7.com/stakater/application/llms.txt Configures how pods are scheduled onto nodes. It includes node selectors to target specific nodes based on labels, and tolerations to allow pods to be scheduled on nodes with specific taints. This ensures pods land on appropriate infrastructure. ```yaml nodeSelector: node.kubernetes.io/instance-type: c5.xlarge topology.kubernetes.io/zone: us-east-1a tolerations: - key: dedicated operator: Equal value: compute effect: NoSchedule - key: gpu operator: Exists effect: NoSchedule - key: node.kubernetes.io/unreachable operator: Exists effect: NoExecute tolerationSeconds: 30 ``` -------------------------------- ### Consuming Environment Variables from Secret using envFrom Source: https://github.com/stakater/application/blob/main/README.md Shows how to expose all key-value pairs from a Secret as environment variables using `envFrom`. This is convenient for managing multiple related secret values. Similar to ConfigMaps, you can use `nameSuffix` or a static `name`, and control the necessity of the Secret with the `optional` flag. ```yaml envFrom: database-credentials: type: secret nameSuffix: db-credentials ``` -------------------------------- ### Configure Kubernetes CronJobs for scheduled database backup and log cleanup tasks Source: https://context7.com/stakater/application/llms.txt Defines multiple CronJob resources for automated maintenance tasks. The database backup job runs daily at 2 AM using PostgreSQL tools, while the log cleanup job runs weekly to remove old files. Both configurations include resource limits, environment variables, and volume mounts for persistent storage. ```yaml # values.yaml - Multiple CronJob definitions applicationName: scheduled-tasks cronJob: enabled: true jobs: # Database backup job db-backup: schedule: "0 2 * * *" # Daily at 2 AM suspend: false concurrencyPolicy: Forbid successfulJobsHistoryLimit: 3 failedJobsHistoryLimit: 5 priorityClassName: high-priority startingDeadlineSeconds: 300 activeDeadlineSeconds: 3600 image: repository: docker.io/postgres tag: "15-alpine" pullPolicy: IfNotPresent command: ["/bin/sh"] args: - "-c" - "pg_dump -h $DB_HOST -U $DB_USER $DB_NAME | gzip > /backup/db_$(date +%Y%m%d).sql.gz" env: DB_HOST: value: postgres.database.svc.cluster.local DB_NAME: value: myapp envFrom: db-credentials: type: secret name: postgres-credentials resources: requests: memory: 512Mi cpu: 250m limits: memory: 1Gi cpu: 500m volumeMounts: backup-volume: mountPath: /backup volumes: backup-volume: persistentVolumeClaim: claimName: backup-storage # Log cleanup job cleanup-logs: schedule: "0 0 * * 0" # Weekly on Sunday suspend: false concurrencyPolicy: Replace image: repository: busybox tag: latest command: ["/bin/sh", "-c"] args: - "find /logs -type f -mtime +30 -delete" resources: requests: memory: 64Mi cpu: 50m ``` -------------------------------- ### Kubernetes Network Policy Configuration using values.yaml Source: https://context7.com/stakater/application/llms.txt This snippet details the network policy configuration in a values.yaml file for a Kubernetes application. It defines ingress and egress rules to control network traffic, specifying allowed connections to and from the application pods, including rules for ingress controllers, Prometheus, DNS, databases, and external HTTPS services. Dependencies include the Kubernetes NetworkPolicy API. ```yaml # values.yaml - NetworkPolicy configuration networkPolicy: enabled: true additionalLabels: security: restricted annotations: description: "Restrict traffic to application pods" # Ingress rules - what can connect TO this application ingress: - from: # Allow from same namespace - podSelector: matchLabels: app.kubernetes.io/part-of: my-platform # Allow from ingress controller namespace - namespaceSelector: matchLabels: name: ingress-nginx podSelector: matchLabels: app.kubernetes.io/name: ingress-nginx ports: - protocol: TCP port: 8080 - protocol: TCP port: 9090 - from: # Allow Prometheus scraping - namespaceSelector: matchLabels: name: monitoring podSelector: matchLabels: app: prometheus ports: - protocol: TCP port: 9090 # Egress rules - what this application can connect TO egress: - to: # Allow DNS - namespaceSelector: matchLabels: name: kube-system podSelector: matchLabels: k8s-app: kube-dns ports: - protocol: UDP port: 53 - to: # Allow database connections - podSelector: matchLabels: app: postgresql ports: - protocol: TCP port: 5432 - to: # Allow HTTPS to external services - namespaceSelector: {} ports: - protocol: TCP port: 443 ``` -------------------------------- ### Consuming Environment Variables from Secret using valueFrom Source: https://github.com/stakater/application/blob/main/README.md Explains how to inject specific keys from a Secret into a pod as environment variables using `valueFrom.secretKeyRef`. This is useful for sensitive information like passwords or API keys. It requires specifying the Secret name and the key within that Secret. ```yaml env: KEY: valueFrom: secretKeyRef: name: my-application-db-credentials key: USER ``` -------------------------------- ### Configure Prometheus ServiceMonitor Source: https://context7.com/stakater/application/llms.txt Defines a ServiceMonitor resource for Prometheus to discover and scrape metrics from an application. It specifies endpoints, relabeling rules, and additional labels for Prometheus configuration. ```yaml # values.yaml - Prometheus ServiceMonitor serviceMonitor: enabled: true additionalLabels: prometheus: kube-prometheus release: monitoring annotations: monitoring.stakater.com/enabled: "true" endpoints: - port: http path: /metrics interval: 30s scrapeTimeout: 10s scheme: http - port: http path: /actuator/prometheus interval: 30s scheme: http relabelings: - sourceLabels: [__meta_kubernetes_pod_name] targetLabel: pod - sourceLabels: [__meta_kubernetes_namespace] targetLabel: namespace ``` -------------------------------- ### Configure OpenShift OAuth proxy sidecar in Helm values.yaml Source: https://context7.com/stakater/application/llms.txt This snippet defines an OpenShift OAuth proxy sidecar container with custom arguments, TLS settings, and service/route exposure. It includes port definitions, image reference, and authentication parameters for secure access to the application. Useful for integrating OpenShift OAuth authentication into deployed services. ```yaml deployment: enabled: true ports: - name: https containerPort: 8443 protocol: TCP - name: http containerPort: 8080 protocol: TCP openshiftOAuthProxy: enabled: true port: 8080 # Application port secretName: oauth-proxy-tls image: quay.io/openshift/origin-oauth-proxy:4.13 # Use HTTP instead of HTTPS for proxy disableTLSArg: false # Additional OAuth proxy arguments args: - --provider=openshift - --https-address=:8443 - --http-address=:8081 - --upstream=http://localhost:8080 - --tls-cert=/etc/tls/private/tls.crt - --tls-key=/etc/tls/private/tls.key - --cookie-secret=SECRET - --openshift-service-account=my-application-sa - --openshift-ca=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt - --skip-auth-regex=^/metrics - --skip-auth-regex=^/health service: enabled: true ports: - name: proxy port: 8443 targetPort: 8443 protocol: TCP route: enabled: true port: targetPort: proxy tls: termination: reencrypt ``` -------------------------------- ### Secret-based environment variables (Kubernetes Secrets) Source: https://context7.com/stakater/application/llms.txt Manages sensitive data (database credentials and API keys) using Kubernetes Secrets with both data (base64) and stringData. Shows per-key and bulk environment variable references in a Deployment. ```yaml applicationName: my-application secret: enabled: true files: db-credentials: data: username: cG9zdGdyZXM= # base64 encoded 'postgres' password: c3VwZXJzZWNyZXQ= # base64 encoded 'supersecret' api-keys: stringData: api_key: sk-1234567890abcdef webhook_secret: whsec_abcdefghijklmnop deployment: # Reference specific secret key env: DB_USERNAME: valueFrom: secretKeyRef: name: my-application-db-credentials key: username DB_PASSWORD: valueFrom: secretKeyRef: name: my-application-db-credentials key: password # Load all secret keys as environment variables envFrom: database-credentials: type: secret nameSuffix: db-credentials optional: false ``` -------------------------------- ### Cert-Manager Certificate Resource Configuration for Stakater Application Source: https://context7.com/stakater/application/llms.txt Configures a Kubernetes Certificate resource for cert-manager, specifying details for TLS certificate generation, including DNS names, IP addresses, SANs, issuer reference, and key parameters. This ensures secure communication for the application. Defined in values.yaml. ```yaml # values.yaml - Certificate resource configuration certificate: enabled: true secretName: app-tls-cert duration: 2160h0m0s # 90 days renewBefore: 720h0m0s # 30 days dnsNames: - app.example.com - "*.app.example.com" - api.example.com ipAddresses: - 192.168.1.100 uriSANs: - spiffe://cluster.local/ns/default/sa/my-application emailSANs: - admin@example.com subject: organizations: - Example Inc organizationalUnits: - Platform Team countries: - US provinces: - California localities: - San Francisco commonName: app.example.com keyAlgorithm: rsa keySize: 4096 keyEncoding: pkcs1 isCA: false usages: - digital signature - key encipherment - server auth - client auth issuerRef: name: letsencrypt-prod kind: ClusterIssuer group: cert-manager.io privateKey: enabled: true rotationPolicy: Always keystores: enabled: true pkcs12: create: true key: keystore name: tls-keystore-secret jks: create: true key: truststore name: tls-truststore-secret additionalLabels: cert-type: application annotations: cert-manager.io/issue-temporary-certificate: "true" ``` -------------------------------- ### Configure Vertical Pod Autoscaler (VPA) Source: https://context7.com/stakater/application/llms.txt Configures the Vertical Pod Autoscaler to automatically adjust the resource requests (CPU and memory) for application pods. It supports different update modes and defines minimum and maximum resource limits per container. ```yaml # values.yaml - VPA configuration vpa: enabled: true updatePolicy: updateMode: Auto # Options: Auto, Recreate, Initial, Off resourcePolicy: containerPolicies: - containerName: my-application minAllowed: cpu: 100m memory: 128Mi maxAllowed: cpu: 2 memory: 2Gi controlledResources: - cpu - memory mode: Auto additionalLabels: cost-optimization: enabled annotations: vpa.kubernetes.io/update-mode: "auto" ``` -------------------------------- ### Advanced Pod Affinity and Anti-Affinity Rules Source: https://context7.com/stakater/application/llms.txt Defines rules for co-locating or spreading pods across nodes and zones. It uses podAffinity and podAntiAffinity to prefer or require pods to run on the same or different nodes/zones based on labels. This is crucial for performance and resilience. ```yaml affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: app.kubernetes.io/name operator: In values: - my-application topologyKey: kubernetes.io/hostname requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: app.kubernetes.io/name operator: In values: - redis-cache topologyKey: topology.kubernetes.io/zone podAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 50 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - postgresql topologyKey: kubernetes.io/hostname ``` -------------------------------- ### Configure Horizontal Pod Autoscaler (HPA) Source: https://context7.com/stakater/application/llms.txt Defines the Horizontal Pod Autoscaler configuration, enabling automatic scaling of application pods based on CPU utilization, memory utilization, or custom metrics like HTTP requests per second. It includes scaling behavior policies for scale-down and scale-up. ```yaml # values.yaml - HPA configuration applicationName: my-application autoscaling: enabled: true minReplicas: 2 maxReplicas: 20 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 - type: Resource resource: name: memory target: type: Utilization averageUtilization: 80 - type: Pods pods: metric: name: http_requests_per_second target: type: AverageValue averageValue: "1000" behavior: scaleDown: stabilizationWindowSeconds: 300 policies: - type: Percent value: 50 periodSeconds: 60 scaleUp: stabilizationWindowSeconds: 0 policies: - type: Percent value: 100 periodSeconds: 15 - type: Pods value: 4 periodSeconds: 15 selectPolicy: Max additionalLabels: monitoring: enabled # Disable fixed replicas when HPA is enabled deployment: replicas: null ``` -------------------------------- ### Kubernetes RBAC Configuration using values.yaml Source: https://context7.com/stakater/application/llms.txt This snippet defines the RBAC configuration for a Kubernetes application within a values.yaml file. It includes settings for service accounts, roles, and role-based access control rules, specifying permissions for accessing resources like configmaps, secrets, and deployments. Dependencies include the Kubernetes API. ```yaml # values.yaml - RBAC configuration rbac: enabled: true serviceAccount: enabled: true name: my-application-sa annotations: eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/my-app-role additionalLabels: app.kubernetes.io/component: serviceaccount roles: - name: app-role rules: - apiGroups: [""] resources: ["configmaps"] verbs: ["get", "list", "watch"] - apiGroups: [""] resources: ["secrets"] resourceNames: ["app-specific-secret"] verbs: ["get"] - apiGroups: ["apps"] resources: ["deployments"] verbs: ["get", "list"] - name: monitoring-role rules: - apiGroups: [""] resources: ["pods", "services", "endpoints"] verbs: ["get", "list", "watch"] deployment: enabled: true serviceAccountName: my-application-sa ``` -------------------------------- ### Helm Chart Naming Convention for ConfigMap, Secret, SealedSecret, ExternalSecret Source: https://github.com/stakater/application/blob/main/README.md Defines the naming convention for ConfigMap, Secret, SealedSecret, and ExternalSecret resources generated by the Helm chart. The name is formed by combining the application name (derived from `.Values.applicationName` or chart name) with a suffix from the respective `files` key. This ensures consistent naming for related resources. ```yaml applicationName: helloworld # {{ template "application.name" $ }} configMap: files: config: # {{ $nameSuffix }} key: value ``` -------------------------------- ### Disable Liveness Probe - YAML Source: https://github.com/stakater/application/blob/main/README.md This snippet shows how to disable the liveness probe by setting the 'enabled' field to 'false' in the YAML configuration. ```yaml livenessProbe: enabled: false ```