DevOps

Declarative Elasticsearch Infrastructure Management via Kubernetes Operator: ECK and Custom CRDs

Ruslan Ismailov Published 18 min read
D

Introduction: Why Kubernetes Operators Are Changing the Way We Manage Elasticsearch

The traditional approach to running Elasticsearch in production — manual configuration, bash scripts, and painful rolling upgrades — is becoming a thing of the past. Kubernetes Operators bring declarative management to this process: you describe the desired state of the cluster, and the operator continuously monitors reality against that description, automatically resolving any discrepancies.

Elastic Cloud on Kubernetes (ECK) is the official Kubernetes Operator from Elastic, implementing this approach for the entire stack: Elasticsearch, Kibana, Beats, Logstash, and APM Server. By 2026, ECK has reached the maturity required for large-scale production deployments: multi-node topology support, automated rolling upgrades, native integration with cert-manager and Vault, and an extended API for index lifecycle management.

In this article, we'll take a deep dive into the ECK architecture, production configurations via CRDs, writing a custom operator in Go for managing ILM policies, and integrating with GitOps pipelines.

ECK Architecture: How the Operator Monitors Cluster State

ECK implements the Kubernetes Operator pattern through controllers and custom resources. The central component is the elastic-operator — a Pod running in the elastic-system namespace — which contains multiple controllers: one for Elasticsearch, one for Kibana, one for APM Server, and so on.

Each controller implements a reconciliation loop — an infinite cycle of comparison:

  1. The operator reads the current state of Kubernetes objects (StatefulSets, Services, Secrets, ConfigMaps).
  2. It compares this with the desired state described in the CRD (e.g., Elasticsearch or Kibana).
  3. It computes the delta and applies changes — creating, updating, or deleting resources.
  4. It updates the CRD status to reflect the current health of the cluster.

Key CRDs registered by ECK:

  • elasticsearch.k8s.elastic.co — the primary resource for managing an Elasticsearch cluster.
  • kibana.k8s.elastic.co — Kibana management.
  • apmserver.k8s.elastic.co — APM Server.
  • beat.k8s.elastic.co — Beats (Filebeat, Metricbeat, etc.).
  • elasticmapsserver.k8s.elastic.co — Elastic Maps Server.

ECK uses a StatefulSet per nodeSet model: each group of nodes sharing the same roles and configuration gets its own StatefulSet, ensuring correct scaling and isolation during rolling upgrades.

Installing and Configuring ECK in 2026

In 2026, the recommended way to install ECK is via a Helm chart with GitOps support. Minimum requirements: Kubernetes 1.28+, Helm 3.12+, and cluster-admin privileges for installing CRDs and ClusterRoleBindings.

Add the repository and install the operator:

helm repo add elastic https://helm.elastic.co
helm repo update

helm install elastic-operator elastic/eck-operator \
  --namespace elastic-system \
  --create-namespace \
  --set installCRDs=true \
  --set config.metricsPort=8080 \
  --set config.logVerbosity=0 \
  --set resources.limits.memory=512Mi \
  --set resources.limits.cpu=500m \
  --version 2.14.0

Verify that the operator is running and the CRDs are registered:

kubectl get pods -n elastic-system
kubectl get crd | grep elastic

# Expected output:
# elastic-operator-0   Running
# agents.agent.k8s.elastic.co
# apmservers.apm.k8s.elastic.co
# beats.beat.k8s.elastic.co
# elasticsearches.elasticsearch.k8s.elastic.co
# kibanas.kibana.k8s.elastic.co

For production environments, make sure to set resource limits for the operator itself, enable the metrics endpoint, and configure appropriate RBAC permissions that restrict the operator's access to only the required namespaces.

Deploying a Production Cluster via CRD: nodeSets, Roles, and Resource Configuration

A production Elasticsearch cluster should have dedicated node roles: master, data, and coordinating. ECK lets you describe each group of nodes through a nodeSet, specifying roles, resources, affinity rules, and Elasticsearch configuration independently for each group.

Example of a full production manifest:

apiVersion: elasticsearch.k8s.elastic.co/v1
kind: Elasticsearch
metadata:
  name: production-cluster
  namespace: elastic
spec:
  version: 8.17.0
  image: docker.elastic.co/elasticsearch/elasticsearch:8.17.0

  # Global Elasticsearch settings
  nodeSets:
    # Dedicated master nodes
    - name: masters
      count: 3
      config:
        node.roles: ["master"]
        xpack.ml.enabled: false
        cluster.routing.allocation.disk.watermark.low: "85%"
        cluster.routing.allocation.disk.watermark.high: "90%"
        cluster.routing.allocation.disk.watermark.flood_stage: "95%"
      podTemplate:
        spec:
          affinity:
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                - labelSelector:
                    matchLabels:
                      elasticsearch.k8s.elastic.co/node-master: "true"
                  topologyKey: kubernetes.io/hostname
          containers:
            - name: elasticsearch
              resources:
                requests:
                  memory: 4Gi
                  cpu: 1
                limits:
                  memory: 4Gi
                  cpu: 2
              env:
                - name: ES_JAVA_OPTS
                  value: "-Xms2g -Xmx2g"
      volumeClaimTemplates:
        - metadata:
            name: elasticsearch-data
          spec:
            accessModes: ["ReadWriteOnce"]
            resources:
              requests:
                storage: 50Gi
            storageClassName: fast-ssd

    # Dedicated data nodes (hot tier)
    - name: data-hot
      count: 3
      config:
        node.roles: ["data", "data_content", "data_hot", "ingest"]
        node.attr.data: hot
      podTemplate:
        spec:
          affinity:
            podAntiAffinity:
              preferredDuringSchedulingIgnoredDuringExecution:
                - weight: 100
                  podAffinityTerm:
                    labelSelector:
                      matchLabels:
                        elasticsearch.k8s.elastic.co/node-data: "true"
                    topologyKey: kubernetes.io/hostname
          initContainers:
            - name: sysctl
              securityContext:
                privileged: true
              command: ['sh', '-c', 'sysctl -w vm.max_map_count=262144']
          containers:
            - name: elasticsearch
              resources:
                requests:
                  memory: 16Gi
                  cpu: 4
                limits:
                  memory: 16Gi
                  cpu: 8
              env:
                - name: ES_JAVA_OPTS
                  value: "-Xms8g -Xmx8g"
      volumeClaimTemplates:
        - metadata:
            name: elasticsearch-data
          spec:
            accessModes: ["ReadWriteOnce"]
            resources:
              requests:
                storage: 1Ti
            storageClassName: nvme-ssd

    # Warm tier data nodes
    - name: data-warm
      count: 2
      config:
        node.roles: ["data_warm"]
        node.attr.data: warm
      podTemplate:
        spec:
          containers:
            - name: elasticsearch
              resources:
                requests:
                  memory: 8Gi
                  cpu: 2
                limits:
                  memory: 8Gi
                  cpu: 4
              env:
                - name: ES_JAVA_OPTS
                  value: "-Xms4g -Xmx4g"
      volumeClaimTemplates:
        - metadata:
            name: elasticsearch-data
          spec:
            accessModes: ["ReadWriteOnce"]
            resources:
              requests:
                storage: 4Ti
            storageClassName: standard-hdd

    # Coordinating-only nodes
    - name: coordinating
      count: 2
      config:
        node.roles: []
      podTemplate:
        spec:
          containers:
            - name: elasticsearch
              resources:
                requests:
                  memory: 4Gi
                  cpu: 2
                limits:
                  memory: 4Gi
                  cpu: 4

  # TLS configuration
  http:
    tls:
      selfSignedCertificate:
        disabled: false
    service:
      spec:
        type: ClusterIP

  # Monitoring via Elastic Stack
  monitoring:
    metrics:
      elasticsearchRefs:
        - name: monitoring-cluster
          namespace: monitoring
    logs:
      elasticsearchRefs:
        - name: monitoring-cluster
          namespace: monitoring

Note several key practices: podAntiAffinity ensures master nodes are distributed across different physical hosts, initContainers sets vm.max_map_count, and separate storageClassName values help reduce storage costs for the warm tier.

Managing Updates and Zero-Downtime Rolling Upgrades with ECK

One of ECK's greatest strengths is automated rolling upgrades. When the version in spec.version is changed, the operator begins a sequential node upgrade, maintaining the master quorum and waiting for a green cluster status before moving on to the next node.

The rolling upgrade algorithm in ECK:

  1. The operator checks cluster health (must be green or yellow).
  2. Temporarily disables shard rebalancing: cluster.routing.allocation.enable: none.
  3. Updates one Pod (removes the old one, creates a new one with the new image).
  4. Waits for the new Pod to reach Running state and for the cluster to return to its target health.
  5. Resumes rebalancing and moves to the next node.

To control the upgrade pace, you can configure updateStrategy:

apiVersion: elasticsearch.k8s.elastic.co/v1
kind: Elasticsearch
metadata:
  name: production-cluster
spec:
  version: 8.17.0
  updateStrategy:
    changeBudget:
      maxSurge: 1
      maxUnavailable: 1
  nodeSets:
    - name: data-hot
      count: 3
      # ...

The maxUnavailable: 1 parameter means that at any given moment, no more than one node can be unavailable. maxSurge: 1 allows a temporary extra node to be created, which is especially useful when scaling up.

For large clusters, it is recommended to explicitly set maxUnavailable: 0 and maxSurge: 1 — this guarantees no loss of availability, but requires additional resources during the upgrade window.

Writing a Custom CRD in Go for Custom Elasticsearch Policies

ECK covers most operational scenarios, but managing business logic — ILM policies, index templates, cluster settings — requires developing custom operators. Let's walk through creating a CRD for managing ILM policies in Go using controller-runtime.

Defining the CRD structure:

// api/v1alpha1/ilmpolicy_types.go
package v1alpha1

import (
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// ILMPolicySpec defines the desired state of the ILM policy
type ILMPolicySpec struct {
    // Reference to the Elasticsearch cluster (ECK)
    ElasticsearchRef ElasticsearchReference `json:"elasticsearchRef"`

    // Policy name in Elasticsearch
    PolicyName string `json:"policyName"`

    // ILM policy phases
    Phases ILMPhases `json:"phases"`
}

type ElasticsearchReference struct {
    Name      string `json:"name"`
    Namespace string `json:"namespace,omitempty"`
}

type ILMPhases struct {
    Hot   *HotPhase   `json:"hot,omitempty"`
    Warm  *WarmPhase  `json:"warm,omitempty"`
    Cold  *ColdPhase  `json:"cold,omitempty"`
    Delete *DeletePhase `json:"delete,omitempty"`
}

type HotPhase struct {
    MinAge   string `json:"minAge,omitempty"`
    Rollover *RolloverAction `json:"rollover,omitempty"`
    Priority *PriorityAction `json:"priority,omitempty"`
}

type RolloverAction struct {
    MaxSize string `json:"maxSize,omitempty"`
    MaxAge  string `json:"maxAge,omitempty"`
    MaxDocs int64  `json:"maxDocs,omitempty"`
}

type PriorityAction struct {
    Priority int `json:"priority"`
}

type WarmPhase struct {
    MinAge    string           `json:"minAge"`
    Allocate  *AllocateAction  `json:"allocate,omitempty"`
    Shrink    *ShrinkAction    `json:"shrink,omitempty"`
    ForceMerge *ForceMergeAction `json:"forceMerge,omitempty"`
}

type AllocateAction struct {
    NumberOfReplicas int               `json:"numberOfReplicas,omitempty"`
    Require          map[string]string `json:"require,omitempty"`
}

type ShrinkAction struct {
    NumberOfShards int `json:"numberOfShards"`
}

type ForceMergeAction struct {
    MaxNumSegments int `json:"maxNumSegments"`
}

type ColdPhase struct {
    MinAge   string          `json:"minAge"`
    Freeze   *FreezeAction   `json:"freeze,omitempty"`
    Allocate *AllocateAction `json:"allocate,omitempty"`
}

type FreezeAction struct{}

type DeletePhase struct {
    MinAge string `json:"minAge"`
}

// ILMPolicyStatus describes the observed state of the policy
type ILMPolicyStatus struct {
    // Resource lifecycle phase
    Phase string `json:"phase,omitempty"`
    // Last successful application
    LastApplied *metav1.Time `json:"lastApplied,omitempty"`
    // Policy version in Elasticsearch
    PolicyVersion int64 `json:"policyVersion,omitempty"`
    // Conditions
    Conditions []metav1.Condition `json:"conditions,omitempty"`
}

//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
//+kubebuilder:printcolumn:name="Policy",type=string,JSONPath=`.spec.policyName`
//+kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase`
//+kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp`

type ILMPolicy struct {
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`
    Spec   ILMPolicySpec   `json:"spec,omitempty"`
    Status ILMPolicyStatus `json:"status,omitempty"`
}

//+kubebuilder:object:root=true
type ILMPolicyList struct {
    metav1.TypeMeta `json:",inline"`
    metav1.ListMeta `json:"metadata,omitempty"`
    Items           []ILMPolicy `json:"items"`
}

Now let's implement the Reconciler, which will apply the policy to Elasticsearch via the REST API:

// controllers/ilmpolicy_controller.go
package controllers

import (
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "time"

    "github.com/elastic/go-elasticsearch/v8"
    corev1 "k8s.io/api/core/v1"
    "k8s.io/apimachinery/pkg/api/errors"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/apimachinery/pkg/types"
    ctrl "sigs.k8s.io/controller-runtime"
    "sigs.k8s.io/controller-runtime/pkg/client"
    "sigs.k8s.io/controller-runtime/pkg/log"

    elasticv1alpha1 "github.com/myorg/es-operator/api/v1alpha1"
)

type ILMPolicyReconciler struct {
    client.Client
    Scheme *runtime.Scheme
}

const (
    phasePending  = "Pending"
    phaseApplied  = "Applied"
    phaseFailed   = "Failed"
    requeueAfter  = 5 * time.Minute
)

func (r *ILMPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    logger := log.FromContext(ctx)

    // Load the ILMPolicy object
    policy := &elasticv1alpha1.ILMPolicy{}
    if err := r.Get(ctx, req.NamespacedName, policy); err != nil {
        if errors.IsNotFound(err) {
            return ctrl.Result{}, nil
        }
        return ctrl.Result{}, err
    }

    // Handle deletion (finalizer)
    if !policy.DeletionTimestamp.IsZero() {
        return r.handleDeletion(ctx, policy)
    }

    // Get credentials for connecting to ES
    esClient, err := r.buildESClient(ctx, policy)
    if err != nil {
        logger.Error(err, "Failed to build Elasticsearch client")
        return r.updateStatus(ctx, policy, phaseFailed, err.Error())
    }

    // Apply the ILM policy
    if err := r.applyILMPolicy(ctx, esClient, policy); err != nil {
        logger.Error(err, "Failed to apply ILM policy")
        return r.updateStatus(ctx, policy, phaseFailed, err.Error())
    }

    logger.Info("ILM policy applied successfully", "policy", policy.Spec.PolicyName)
    return r.updateStatus(ctx, policy, phaseApplied, "")
}

func (r *ILMPolicyReconciler) buildESClient(
    ctx context.Context,
    policy *elasticv1alpha1.ILMPolicy,
) (*elasticsearch.Client, error) {
    // Get the credentials Secret from ECK
    secretName := fmt.Sprintf("%s-es-elastic-user", policy.Spec.ElasticsearchRef.Name)
    ns := policy.Spec.ElasticsearchRef.Namespace
    if ns == "" {
        ns = policy.Namespace
    }

    secret := &corev1.Secret{}
    if err := r.Get(ctx, types.NamespacedName{Name: secretName, Namespace: ns}, secret); err != nil {
        return nil, fmt.Errorf("failed to get ES credentials secret: %w", err)
    }

    password := string(secret.Data["elastic"])

    // Get the CA certificate from ECK
    caSecretName := fmt.Sprintf("%s-es-http-ca-internal", policy.Spec.ElasticsearchRef.Name)
    caSecret := &corev1.Secret{}
    if err := r.Get(ctx, types.NamespacedName{Name: caSecretName, Namespace: ns}, caSecret); err != nil {
        return nil, fmt.Errorf("failed to get ES CA secret: %w", err)
    }

    esServiceURL := fmt.Sprintf(
        "https://%s-es-http.%s.svc:9200",
        policy.Spec.ElasticsearchRef.Name, ns,
    )

    cfg := elasticsearch.Config{
        Addresses: []string{esServiceURL},
        Username:  "elastic",
        Password:  password,
        CACert:    caSecret.Data["ca.crt"],
        Transport: &http.Transport{
            TLSHandshakeTimeout: 10 * time.Second,
        },
    }

    return elasticsearch.NewClient(cfg)
}

func (r *ILMPolicyReconciler) applyILMPolicy(
    ctx context.Context,
    esClient *elasticsearch.Client,
    policy *elasticv1alpha1.ILMPolicy,
) error {
    // Build the request body from the spec
    policyBody := buildILMPolicyBody(policy.Spec.Phases)

    bodyBytes, err := json.Marshal(map[string]interface{}{
        "policy": policyBody,
    })
    if err != nil {
        return fmt.Errorf("failed to marshal ILM policy: %w", err)
    }

    res, err := esClient.ILM.PutLifecycle(
        policy.Spec.PolicyName,
        esClient.ILM.PutLifecycle.WithBody(
            bytes.NewReader(bodyBytes),
        ),
        esClient.ILM.PutLifecycle.WithContext(ctx),
    )
    if err != nil {
        return fmt.Errorf("elasticsearch API error: %w", err)
    }
    defer res.Body.Close()

    if res.IsError() {
        return fmt.Errorf("elasticsearch returned error: %s", res.String())
    }

    return nil
}

func (r *ILMPolicyReconciler) updateStatus(
    ctx context.Context,
    policy *elasticv1alpha1.ILMPolicy,
    phase string,
    errMsg string,
) (ctrl.Result, error) {
    policy.Status.Phase = phase
    if phase == phaseApplied {
        now := metav1.Now()
        policy.Status.LastApplied = &now
    }

    condition := metav1.Condition{
        Type:               "Ready",
        Status:             metav1.ConditionTrue,
        LastTransitionTime: metav1.Now(),
        Reason:             "Reconciled",
        Message:            "ILM policy applied successfully",
    }
    if phase == phaseFailed {
        condition.Status = metav1.ConditionFalse
        condition.Reason = "ReconciliationFailed"
        condition.Message = errMsg
    }

    policy.Status.Conditions = []metav1.Condition{condition}

    if err := r.Status().Update(ctx, policy); err != nil {
        return ctrl.Result{}, err
    }

    if phase == phaseFailed {
        return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
    }
    return ctrl.Result{RequeueAfter: requeueAfter}, nil
}

func (r *ILMPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error {
    return ctrl.NewControllerManagedBy(mgr).
        For(&elasticv1alpha1.ILMPolicy{}).
        Complete(r)
}

Example manifest for using our CRD:

apiVersion: elastic.myorg.io/v1alpha1
kind: ILMPolicy
metadata:
  name: logs-policy
  namespace: elastic
spec:
  elasticsearchRef:
    name: production-cluster
    namespace: elastic
  policyName: logs-ilm-policy
  phases:
    hot:
      minAge: 0ms
      rollover:
        maxSize: 50gb
        maxAge: 1d
      priority:
        priority: 100
    warm:
      minAge: 7d
      allocate:
        numberOfReplicas: 1
        require:
          data: warm
      shrink:
        numberOfShards: 1
      forceMerge:
        maxNumSegments: 1
    cold:
      minAge: 30d
      allocate:
        numberOfReplicas: 0
        require:
          data: cold
    delete:
      minAge: 90d

CI/CD Integration: Declarative Management via GitOps

The declarative approach of Kubernetes Operators pairs perfectly with GitOps methodology. All manifests — Elasticsearch CRDs, ILMPolicies, index templates — are stored in Git and applied automatically upon merge to the main branch.

A typical GitOps stack for managing Elasticsearch in Kubernetes in 2026: ArgoCD or Flux CD for syncing cluster state with Git, Helm for configuration templating, and Kustomize for environment-specific overrides.

Repository structure:

elasticsearch-gitops/
├── base/
│   ├── namespace.yaml
│   ├── elasticsearch.yaml          # Base cluster
│   ├── kibana.yaml
│   └── kustomization.yaml
├── overlays/
│   ├── staging/
│   │   ├── elasticsearch-patch.yaml  # 1 node, small resources
│   │   └── kustomization.yaml
│   └── production/
│       ├── elasticsearch-patch.yaml  # 3+3+2 nodes, full resources
│       └── kustomization.yaml
├── ilm-policies/
│   ├── logs-policy.yaml
│   └── metrics-policy.yaml
└── index-templates/
    └── logs-template.yaml

ArgoCD Application for the production environment:

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: elasticsearch-production
  namespace: argocd
spec:
  project: production
  source:
    repoURL: https://github.com/myorg/elasticsearch-gitops
    targetRevision: main
    path: overlays/production
  destination:
    server: https://kubernetes.default.svc
    namespace: elastic
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true
      - ServerSideApply=true
    retry:
      limit: 5
      backoff:
        duration: 5s
        factor: 2
        maxDuration: 3m

An important detail: when using ServerSideApply=true, ArgoCD correctly handles CRDs with large specs, avoiding annotation conflicts during updates.

Monitoring and Observability for Elasticsearch in Kubernetes

Comprehensive monitoring of Elasticsearch in Kubernetes covers three levels: ES cluster metrics, ECK operator metrics, and Kubernetes metrics (Pod resources, PVCs).

ECK supports native monitoring via a dedicated monitoring cluster. For Prometheus integration, use elasticsearch-exporter:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: elasticsearch-exporter
  namespace: elastic
  labels:
    release: prometheus
spec:
  selector:
    matchLabels:
      app: elasticsearch-exporter
  endpoints:
    - port: http
      interval: 30s
      scrapeTimeout: 10s
      path: /metrics
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: elasticsearch-exporter
  namespace: elastic
spec:
  replicas: 1
  selector:
    matchLabels:
      app: elasticsearch-exporter
  template:
    spec:
      containers:
        - name: exporter
          image: quay.io/prometheuscommunity/elasticsearch-exporter:v1.8.0
          args:
            - --es.uri=https://elastic:$(ES_PASSWORD)@production-cluster-es-http:9200
            - --es.ssl-skip-verify=false
            - --es.ca=/certs/ca.crt
            - --es.all
            - --es.cluster_settings
            - --es.indices
            - --es.shards
          env:
            - name: ES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: production-cluster-es-elastic-user
                  key: elastic
          volumeMounts:
            - name: es-certs
              mountPath: /certs
              readOnly: true
      volumes:
        - name: es-certs
          secret:
            secretName: production-cluster-es-http-ca-internal

Key Prometheus alerts:

groups:
  - name: elasticsearch.rules
    rules:
      - alert: ElasticsearchClusterNotHealthy
        expr: elasticsearch_cluster_health_status{color="red"} == 1
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Elasticsearch cluster RED"
          description: "Cluster {{ $labels.cluster }} is in RED state for more than 2 minutes"

      - alert: ElasticsearchJVMHeapTooHigh
        expr: |
          (elasticsearch_jvm_memory_used_bytes{area="heap"} /
           elasticsearch_jvm_memory_max_bytes{area="heap"}) > 0.85
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Elasticsearch JVM heap high"
          description: "Node {{ $labels.name }}: JVM heap usage is {{ $value | humanizePercentage }}"

      - alert: ElasticsearchDiskSpaceLow
        expr: |
          (elasticsearch_filesystem_data_available_bytes /
           elasticsearch_filesystem_data_size_bytes) < 0.15
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Elasticsearch disk space low"

      - alert: ElasticsearchUnassignedShards
        expr: elasticsearch_cluster_health_unassigned_shards > 0
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Elasticsearch has unassigned shards"
          description: "{{ $value }} unassigned shards in cluster {{ $labels.cluster }}"

      - alert: ECKOperatorReconciliationErrors
        expr: rate(controller_runtime_reconcile_errors_total[5m]) > 0
        for: 2m
        labels:
          severity: warning
        annotations:
          summary: "ECK operator reconciliation errors detected"

Common Production Issues and How to Solve Them

Issue 1: OOMKilled — out of memory on nodes. This often results from an incorrect ratio between heap size and memory limits. The rule of thumb: heap = 50% of available memory, but no more than 31 GB. If the Pod limit is 16 GB, use -Xms8g -Xmx8g. Make sure requests.memory == limits.memory — this prevents throttling and unpredictable scheduler behavior.

Issue 2: Stuck rolling upgrade. ECK can get "stuck" during an upgrade if one of the Pods fails to become Ready. Check: free PVC availability, pod events (kubectl describe pod), and shard status. Temporarily increasing maxUnavailable can sometimes help.

Issue 3: Split-brain when master quorum is lost. Always use an odd number of master-eligible nodes (3 or 5) and configure podAntiAffinity with requiredDuringSchedulingIgnoredDuringExecution to guarantee that master nodes are placed on different Kubernetes nodes.

Issue 4: Slow recovery after Pod restart. Tune cluster.routing.allocation.node_concurrent_recoveries and indices.recovery.max_bytes_per_sec according to your storage throughput. For NVMe SSDs, you can safely set 500mb or higher.

Issue 5: Conflicts when using ECK alongside custom operators. If your operator and ECK are managing the same Secrets or ConfigMaps, reconciliation conflicts may occur. Use Owner References and explicit co.elastic.k8s/owner annotations to prevent ECK from overwriting your resources.

Issue 6: PVCs not deleted when scaling down. Kubernetes does not automatically delete PVCs when the count in a nodeSet is reduced — this is a safeguard against data loss. When reducing the number of data nodes, ensure shards are rebalanced before updating the manifest, then manually delete the unneeded PVCs.

Conclusion

Declarative management of Elasticsearch via Kubernetes Operators is not just a trendy approach — it is a mature practice that delivers reproducibility, reliability, and operational automation. In 2026, ECK handles the majority of production scenarios out of the box: zero-downtime rolling upgrades, certificate management, and monitoring via a dedicated cluster.

Developing custom CRDs in Go allows you to extend this model to cover business logic: ILM policy management, index templates, security settings — all of which can be moved into Git and managed declaratively through a GitOps pipeline.

Key recommendations for production:

  • Always use dedicated node roles — keep master nodes separate from data nodes.
  • Configure podAntiAffinity for critical node groups.
  • Store all manifests in Git and apply them via ArgoCD or Flux.
  • Monitor not only Elasticsearch metrics, but also the metrics of the ECK operator itself.
  • Test rolling upgrades in a staging environment before applying them to production.

Investing in the operator-based approach pays off quickly: operational burden decreases, manual errors disappear, and the cluster state becomes fully transparent and reproducible.

Technologies

Tags

Ruslan Ismailov

Senior Web / Backend Developer. Senior web/backend developer with 9 years of experience. Stack: PHP, Laravel, PostgreSQL, Redis, Docker, Kubernetes, REST, microservices, CI/CD. More about me →