# Deploying Sourcegraph Executors natively on Kubernetes

<Callout type="warning">
	Native Kubernetes executors are in beta. For production workloads, consider deploying using
	[Terraform](/self-hosted/executors/deploy-executors-terraform) or the
	[Linux binary](/self-hosted/executors/deploy-executors-binary) for better long-term support.
</Callout>

The native Kubernetes Executors have a master Executor pod that schedules worker pods via the Kubernetes API. The master Executor pod manages the lifecycle of jobs, while the worker pods process the actual [batch change](/batch-changes/server-side) or [precise auto indexing](/code-navigation/auto-indexing) job specs. Review the [deployment method comparison](/self-hosted/executors#choose-a-deployment-method) for its isolation and support status.

![Native Kubernetes executor architecture](https://storage.googleapis.com/sourcegraph-assets/executor_kubernetes_native_arch.png)

## How it works

The executor runs as a pod and polls Sourcegraph for work. After dequeuing a job, it asks the Kubernetes API to create a job pod with its own workspace volume. The pod's first init container clones the target repository into the workspace, then each step runs sequentially as an init container in that pod. The executor streams the step logs and final job status back to Sourcegraph, then deletes the job pod.

**On this page**

- [Requirements](#requirements)
- [Deployment](#deployment)
- [Upgrading executors](#upgrading-executors)
- [Additional notes](#additional-notes)
- [Related configuration](#related-configuration)

## Requirements

Executors interact with the Kubernetes API to manage the lifecycle of individual executor jobs. The following are the RBAC Roles needed to run Executors natively on Kubernetes.

| API Groups | Resources          | Verbs                  | Reason                                                                                    |
| ---------- | ------------------ | ---------------------- | ----------------------------------------------------------------------------------------- |
| `batch`    | `jobs`             | `create`, `delete`     | Executors create Job pods to run processes. Once Jobs are completed, they are cleaned up. |
|            | `pods`, `pods/log` | `get`, `list`, `watch` | Executors need to look up and stream logs from the Job Pods.                               |
|            | `secrets`          | `create`, `delete`     | Each job gets a Secret holding its access token and workspace files.                       |

Here's an example Role YAML to demonstrate the RBAC requirements for native Kubernetes Executors:

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
    name: sg-executor-batches-role
    namespace: default
rules:
    - apiGroups:
          - batch
      resources:
          - jobs
      verbs:
          - create
          - delete
    - apiGroups:
          - ''
      resources:
          - pods
          - pods/log
      verbs:
          - get
          - list
          - watch
    # Secrets are required post 5.5, when all pods run a single job
    - apiGroups:
          - ''
      resources:
          - secrets
      verbs:
          - create
          - delete
    # PVCs are required if KUBERNETES_JOB_VOLUME_TYPE is "pvc"
#  - apiGroups:
#      - ""
#    resources:
#      - persistentvolumeclaims
#    verbs:
#      - create
#      - delete
```

## Deployment

Native Kubernetes Executors can be deployed via either the `sourcegraph-executor-k8s` [Helm chart](https://github.com/sourcegraph/deploy-sourcegraph-helm/tree/main/charts/sourcegraph-executor/k8s) or by using the `executors/k8s` [Kustomize component](https://github.com/sourcegraph/deploy-sourcegraph-k8s/tree/main/components/executors/k8s).

### Steps

1. If you are deploying Executors for processing Batch Changes, set `batchChanges.nativeServerSideExecution` to `true` in your [advanced configuration](/admin/config/site-config). Only enable this when using Executors on Kubernetes.

    > **Note:** Batch Changes on native Kubernetes executors inherits the beta limitations of
    > the native Kubernetes runtime. See the warning at the top of this page.
2. Configure the following environment variables on the Executor Deployment:

    1. `EXECUTOR_FRONTEND_URL` should match the URL of your Sourcegraph instance
    2. `EXECUTOR_FRONTEND_PASSWORD` should match the `executors.accessToken` key in the Sourcegraph instance's advanced configuration
    3. Either `EXECUTOR_QUEUE_NAMES` or `EXECUTOR_QUEUE_NAME` should be set to the [queues](/self-hosted/executors/executors-config#queues) the Executor will serve. Executors that process batch changes should serve `batches,batches-hooks`; executors for precise auto-indexing serve `codeintel`.
    4. `EXECUTOR_KUBERNETES_NAMESPACE` should be set to the Kubernetes namespace where you intend to run the worker pods. This should generally match the namespace where you deploy the Executor resources in the next step.

    <Callout type="note">
    	Additional environment variables may need to be configured for your
    	Executors deployment. See [here](/self-hosted/executors/executors-config) for
    	a complete list.
    </Callout>

3. Deploy the native Kubernetes Executor resources to your Kubernetes cluster via either the `sourcegraph-executor-k8s` [Helm chart](https://github.com/sourcegraph/deploy-sourcegraph-helm/tree/main/charts/sourcegraph-executor/k8s) or the `executors/k8s` [Kustomize component](https://github.com/sourcegraph/deploy-sourcegraph-k8s/tree/main/components/executors/k8s).
    1. For more details on how to work with the Sourcegraph Helm chart, see the [Helm chart docs](/self-hosted/deploy/kubernetes#configuration) (_Note: The same Helm values `override.yaml` file can be used for both the main `sourcegraph` Helm chart as well as the `sourcegraph-executor-k8s` chart_)
    2. For more details on how to configure the `executors/k8s` component for your Kustomize deployment, see the [Kustomize configuration docs](/self-hosted/deploy/kubernetes/configure#overview)
4. Once all the native Kubernetes Executor resources have been deployed to your cluster, confirm that the Executors are online by checking the _Executors_ page under **Administration > Executors > Instances**

## Upgrading executors

Upgrading native Kubernetes executors follows the same pattern as the initial deployment. Check the [changelog](https://sourcegraph.com/changelog) for any executor-related breaking changes or new features.

### Helm

1. Update your Helm repo to fetch the latest chart versions:

    ```bash
    helm repo update sourcegraph
    ```

2. Run `helm upgrade` with the target Sourcegraph version:

    ```bash
    helm upgrade --install --values ./override.yaml --version <target Sourcegraph version> sg-executor sourcegraph/sourcegraph-executor-k8s
    ```

3. Verify the executor pod restarts with the new version:

    ```bash
    kubectl get pods -l app.kubernetes.io/component=executor
    ```

4. Confirm the executor is online and reporting the expected version under **Administration > Executors > Instances**.

### Kustomize

1. Update the `deploy-sourcegraph-k8s` repository to the tag matching your target Sourcegraph version.
2. Re-apply the Kustomize overlay:

    ```bash
    kubectl apply --prune -l deploy=sourcegraph -f <path to your overlay output>
    ```

3. Confirm the executor is online under **Administration > Executors > Instances**.

## Additional Notes

### Firecracker

Executors deployed on Kubernetes do not use [Firecracker](/self-hosted/executors/firecracker).

If you have security concerns, consider deploying via [terraform](/self-hosted/executors/deploy-executors-terraform)
or [installing the binary](/self-hosted/executors/deploy-executors-binary) directly.

### Scale and schedule jobs

Each executor pod runs up to `EXECUTOR_MAXIMUM_NUM_JOBS` jobs at once (Helm value `executor.maximumNumJobs`, default 10). To run more jobs at once, raise that value, run more executor pods, or both. Executor pods can serve the same queues: each pod dequeues its own jobs, and no two pods get the same job. With Helm, set `executor.replicas`; with Kustomize, scale the executor Deployment. The most jobs that run at once is the number of executor pods times `EXECUTOR_MAXIMUM_NUM_JOBS`.

Several pods with fewer jobs each scale better than one pod with many jobs. Each executor pod dequeues one job at a time and has its own limit on requests to the Kubernetes API, `EXECUTOR_KUBERNETES_CLIENT_QPS` and `EXECUTOR_KUBERNETES_CLIENT_BURST` (Helm values `executor.kubernetesClient.qps` and `burst`, defaults 50 and 100), shared by all of the pod's jobs. Each job makes about 10 API calls.

Each job runs in its own pod and has its own workspace volume. By default, the workspace uses an `emptyDir` volume, so job pods do not need to run on the same node as the executor pod. If `KUBERNETES_JOB_VOLUME_TYPE` is set to `pvc`, the executor creates a separate PVC for each job.

Without additional scheduling configuration, the Kubernetes scheduler can place job pods on any suitable node. Use the following optional environment variables to constrain their placement:

-   `EXECUTOR_KUBERNETES_NODE_NAME`
-   `EXECUTOR_KUBERNETES_NODE_SELECTOR`
-   `EXECUTOR_KUBERNETES_NODE_REQUIRED_AFFINITY_MATCH_EXPRESSIONS`
-   `EXECUTOR_KUBERNETES_NODE_REQUIRED_AFFINITY_MATCH_FIELDS`

For example, use `EXECUTOR_KUBERNETES_NODE_SELECTOR` to restrict Jobs to a dedicated node pool.

With the Helm chart, set these under `executor.kubernetesJob` as plain YAML; the chart encodes lists and maps as the JSON the executor expects. For example, to run 40 jobs at once on a tainted node pool in a `restricted` namespace:

```yaml
executor:
  replicas: 4
  maximumNumJobs: 10
  kubernetesClient:
    qps: 50
    burst: 100
  kubernetesJob:
    resources:
      requests:
        cpu: "1"
        memory: 2Gi
        ephemeralStorage: 5Gi
      limits:
        memory: 4Gi
        ephemeralStorage: 10Gi
    node:
      selector: node-pool=executor-jobs
      tolerations:
        - key: dedicated
          operator: Equal
          value: executor-jobs
          effect: NoSchedule
    podSecurityContext:
      runAsNonRoot: true
      runAsUser: 1000
      runAsGroup: 1000
      fsGroup: 1000
      seccompProfile:
        type: RuntimeDefault
    containerSecurityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: [ALL]
```

Quote YAML values such as `"y"`, `"n"`, `"on"`, and `"off"` in these lists, or YAML reads them as booleans and the executor rejects the value.

When many jobs run at once, check these Kubernetes settings on the nodes that run job pods:

-   **Pods per node:** the kubelet runs at most `maxPods` pods per node, 110 by default. Job pods over the limit stay `Pending` with the event `Too many pods` until a node frees up or the cluster autoscaler adds one. GKE and AKS set the limit when the node pool is created.
-   **Pod IP addresses:** every job pod needs an IP address from the cluster network. On Amazon EKS with the VPC CNI, a node has a limited number of IP addresses per network interface, and the CNI assigns more as pods start. When many job pods start at once, some fail with the event `FailedCreatePodSandBox ... failed to assign an IP address to container`, and the kubelet retries them, which delays the job. Enable prefix delegation (`ENABLE_PREFIX_DELEGATION=true` on the `aws-node` DaemonSet), or raise `WARM_IP_TARGET` or `MINIMUM_IP_TARGET`, and check that the node subnets have enough free addresses. Other network plugins have similar per-node address ranges.
-   **Requests:** the scheduler places job pods by their requests. Job pods that do not fit stay `Pending` with the event `Insufficient memory` or `Insufficient cpu`. Set `EXECUTOR_KUBERNETES_RESOURCE_REQUEST_MEMORY` and `EXECUTOR_KUBERNETES_RESOURCE_REQUEST_CPU` to what a job needs. With the default `emptyDir` workspace, set `EXECUTOR_KUBERNETES_RESOURCE_REQUEST_EPHEMERAL_STORAGE` to at least `KUBERNETES_JOB_VOLUME_SIZE` (default `5Gi`), so the scheduler does not place more jobs on a node than its disk holds.
-   **Image pulls:** by default the kubelet pulls one image at a time (`serializeImagePulls`; the Amazon EKS optimized AMIs turn it off), so many new job pods on one node wait for each other's pulls. Pre-pull or mirror the step images if job pods start slowly.
-   **API server limits:** the Kubernetes API server's API Priority and Fairness can throttle a busy executor's service account. Check for HTTP 429 responses in the executor logs.
-   **Quotas:** a `ResourceQuota` in the job namespace can cap pods, Secrets, Jobs, CPU, or memory. When a job pod would go over it, Kubernetes does not create the pod (event `exceeded quota`), and the Job controller retries with a growing delay while the job holds an executor slot. Keep the job pods' requests, times `EXECUTOR_MAXIMUM_NUM_JOBS`, times the number of executor pods, within the quota.
-   **Pod Security:** in a namespace that enforces the `restricted` Pod Security Standard, the API server rejects the executor pod and job pods without a restricted security context (event `violates PodSecurity "restricted:latest"`). Set the executor pod's with the Helm values `executor.podSecurityContext` and `executor.containerSecurityContext`. Set the job pods' with the Helm values `executor.kubernetesJob.podSecurityContext` and `containerSecurityContext`, as in the example above, or the JSON environment variables `KUBERNETES_EXECUTOR_POD_SECURITY_CONTEXT` and `KUBERNETES_EXECUTOR_CONTAINER_SECURITY_CONTEXT`. Steps then run as that user, so steps that need root fail.

Jobs left behind when an executor pod stops, such as during an upgrade, are deleted by Kubernetes one hour after they finish.

### Firewall Rules

The following are Firewall rules that are _highly recommended_ when running Executors on Kubernetes in a Cloud
Environment.

-   Disable access to internal resources.
-   Disable access to `169.254.169.254` (AWS / GCP Instance Metadata Service).

### Docker Image

The Executor Docker image is available on Docker Hub at [`sourcegraph/executor-kubernetes`](https://hub.docker.com/r/sourcegraph/executor-kubernetes/tags).

### Example Configuration YAML

For an example of how to configure the Executor in Kubernetes, see the [`sourcegraph-executor-k8s` Helm chart values reference](https://github.com/sourcegraph/deploy-sourcegraph-helm/blob/main/charts/sourcegraph-executor/k8s/values.yaml).

## Related configuration

- [Add custom certificates using Kubernetes manifests](/self-hosted/executors/custom-certificates#add-certificates-to-a-kubernetes-deployment-using-manifests)
- [Add custom certificates using Helm](/self-hosted/executors/custom-certificates#add-certificates-to-a-kubernetes-deployment-using-helm)
- [Use private container registries](/self-hosted/executors/private-registries)
