# Kubernetes

Unikraft Cloud integrates seamlessly with any Kubernetes cluster through a virtual [kubelet](https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/) known as **Kraftlet**.
This is a lightweight Kubernetes node implementation which connects your cluster to Unikraft Cloud's high-performance compute instead of running real pods locally.
This enables developers to deploy and manage Unikraft microVMs as if they were native Kubernetes pods.

This integration extends Kubernetes' scheduling and orchestration capabilities to the Unikraft Cloud platform.
This allows workloads to take advantage of microVM-level I/O performance, security, cold start and transparent scale-to-zero efficiency while retaining full compatibility with existing Kubernetes tooling.

Upon startup, Kraftlet will register itself as a worker node with the Kubernetes API.
Once Kraftlet registers itself as a node, Kubernetes can schedule Pods onto it.

Any Pod scheduled to the Kraftlet node won't run as a container within the cluster.
Instead, it will run a highly optimized microVM on Unikraft Cloud.
Kraftlet will manage the Pod lifecycle to make sure the apps are up and running.


## Getting started

Make sure to log into Unikraft Cloud and pick a [metro](/platform/metros) close to you.
Grab the metro name and your API token from the dashboard and set them as environment variables:

```bash title=""
# Set Unikraft Cloud access token
export UKC_TOKEN=token
# Set metro to Frankfurt, DE
export UKC_METRO=fra
```

You can install Kraftlet into a Kubernetes cluster using its Helm chart:

```bash
helm install kraftlet \
  --namespace kraftlet \
  --create-namespace \
  --set ukc.metro=${UKC_METRO} \
  --set ukc.token=${UKC_TOKEN} \
  oci://ghcr.io/unikraft-cloud/helm-charts/kraftlet
```

The chart deploys Kraftlet as a StatefulSet.
You can check if Kraftlet is running by checking its pods:

```bash
kubectl get pods -n kraftlet
```

Which should return a single pod running:

```ansi title=""
[1mNAME[0m         [1mREADY[0m   [1mSTATUS[0m    [1mRESTARTS[0m   [1mAGE[0m
kraftlet-0   1/1     Running   0          38s
```

You can also check if the kraftlet successfully registered as a node:

```bash
kubectl get nodes
```

Which should, among other nodes, return Kraftlet:

```ansi title=""
[1mNAME[0m       [1mSTATUS[0m   [1mROLES[0m   [1mAGE[0m   [1mVERSION[0m
kraftlet   Ready    agent   58s   v0.6.0
```

### Node taint and labels

Kraftlet taints its node so that nothing lands on Unikraft Cloud by accident.
The default taint is `virtual-kubelet.io/provider=ukc` with the `NoSchedule` effect, so every Pod you want on Unikraft Cloud needs a matching toleration and a node selector.
Turn the taint off with `--set node.taint.enable=false`, or change it through the other `node.taint.*` values.

Kraftlet advertises the following labels on its node, which you can select on:

| Label | Value |
|---|---|
| `kubernetes.io/hostname` | The node name, `kraftlet` by default. |
| `kubernetes.io/role` | `agent` |
| `kubernetes.io/os` | `linux` |
| `kubernetes.io/arch` | The value of `node.architecture`, `amd64` by default. |
| `type` | `kubelet` |
| `unikraft.com/virtual-kubelet` | `true` |

Anything you add under `node.labels` joins this set.

:::note
With `kraftlet.replication.enabled=true`, each replica registers a node named after its own Pod, such as `kraftlet-0` and `kraftlet-1`.
Select on `unikraft.com/virtual-kubelet` rather than on `kubernetes.io/hostname` to spread Pods across every replica.
:::

## Autoscaling the cluster

The chart above registers one node per Kraftlet, against capacity that already exists.
To let the cluster create that capacity on demand, add the [Karpenter provider for Unikraft](/integrations/karpenter).
It launches a machine when a Pod has nowhere to run, installs Kraftlet against it, joins it as a node, and removes both again once the capacity goes unused.

## Examples

Below are examples of Kubernetes configurations that define Unikraft Cloud apps through Kubernetes concepts.
You will notice that each workload object defines `tolerations` and `nodeSelector` so Pods get scheduled on the Kraftlet node.

:::warning
Make sure Kraftlet is up and running before trying out examples below.
:::

### Simple app

The configuration below defines an app with three replicas running the NGINX image and a single Kubernetes service that exposes port `443`.
For each service backed by a Pod scheduled to the Kraftlet node, Kraftlet will create a corresponding service.
In this case, Kraftlet will create three NGINX instances and a single service that exposes port 443.

```yaml title="simple.yaml"
# simple.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      tolerations:
        - key: "virtual-kubelet.io/provider"
          operator: "Equal"
          value: "ukc"
          effect: "NoSchedule"
      nodeSelector:
        kubernetes.io/hostname: kraftlet
      containers:
        - name: nginx
          image: nginx:latest
          ports:
            - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
    - port: 443
      targetPort: 8080
      protocol: TCP
```

You can apply the configuration with:

```bash
kubectl apply -f simple.yaml
```

Once applied, you can check the status of your newly created pods in the Kubernetes cluster:

```bash
kubectl get pods
```

```ansi title=""
[1mNAME[0m                      [1mREADY[0m   [1mSTATUS[0m    [1mRESTARTS[0m   [1mAGE[0m
my-app-78c766fb67-k2dgk   1/1     Running   0          104s
my-app-78c766fb67-mfp77   1/1     Running   0          104s
my-app-78c766fb67-tkkxq   1/1     Running   0          104s
```

Your app is now managed from the Kubernetes cluster, but is actually running on Unikraft Cloud.

To check the instances, run:

```bash
unikraft instances list
```

Which will return a list of instances created from pods above:

```ansi
[1mMETRO[22m  [1mNAME[22m                                         [1mSTATE[22m    [1mIMAGE[22m           [1mARGS[22m  [1mMEMORY[22m  [1mVCPUS[22m  [1mFQDN[22m                                                                   [1mCREATED[22m
fra    pfCUcp2sg0toDx3N60IerjgiXdqj8BqTzRPfgIX7M8R  [38;2;0;188;125mrunning[0m  <my-org>/nginx        128MiB  1      MFyBmK4Hm5BTcjtMvVTYs2RXn3BzCzSPToyTBvjdVIO-orjlyrac.fra.unikraft.app  2 minutes ago
fra    N1z7fNY4CmhOP6UhqIQsbeRmu8a5Ti8zzhk20okCTwW  [38;2;0;188;125mrunning[0m  <my-org>/nginx        128MiB  1      MFyBmK4Hm5BTcjtMvVTYs2RXn3BzCzSPToyTBvjdVIO-orjlyrac.fra.unikraft.app  2 minutes ago
fra    O830nhB9LeT1sLGh3SiqbjiTmM3u26gOZcvA2eKtOVt  [38;2;0;188;125mrunning[0m  <my-org>/nginx        128MiB  1      MFyBmK4Hm5BTcjtMvVTYs2RXn3BzCzSPToyTBvjdVIO-orjlyrac.fra.unikraft.app  2 minutes ago
```

Kraftlet derives every Unikraft Cloud resource name from a hash, so the names carry no trace of the Pod they belong to.
Use the [tags](#tags) Kraftlet attaches instead to find the instance behind a Pod:

```bash
unikraft instances list --filter 'tags.*==k8s.io:pod=my-app-78c766fb67-k2dgk'
```

As you can see, all instances have the same FQDN.
This is because Kraftlet created a corresponding Unikraft Cloud service for the Kubernetes service defined in YAML above.
You can check the created service with the following command:

```bash
unikraft services list
```

```ansi
[1mMETRO[22m  [1mNAME[22m                                         [1mAUTOSCALE[22m  [1mCREATED[22m        [1mFQDN[22m                                                                   [1mSOURCE[22m  [1mDESTINATION[22m  [1mHANDLERS[22m
fra    MFyBmK4Hm5BTcjtMvVTYs2RXn3BzCzSPToyTBvjdVIO  false      6 minutes ago  MFyBmK4Hm5BTcjtMvVTYs2RXn3BzCzSPToyTBvjdVIO-orjlyrac.fra.unikraft.app  443     8080         ["tls", "http"]
```

:::tip
The generated FQDN follows the hashed service name.
Annotate the Kubernetes Service with `cloud.unikraft.v1.services/domain` to pick a readable hostname instead, as described under [Service annotations](#service-annotations).
:::

You can now manage your app running in Unikraft Cloud via Kubernetes resources!

### Stateful apps

The example below deploys a stateful app on Unikraft Cloud that has access to a volume.

To support provisioning Unikraft Cloud volumes through Kubernetes, Kraftlet watches [PersistentVolumeClaim](https://kubernetes.io/docs/concepts/storage/persistent-volumes/) (PVC) objects with storage class `ukc-volume`.
Creating a new PVC object with that storage class triggers Kraftlet to create a Unikraft Cloud volume and a PersistentVolume object that marks the PVC as `Bound`.

:::note
This watcher is off by default.
Install the chart with `--set kraftlet.enablePvcWatcher=true` to let Kraftlet manage `ukc-volume` claims.
:::

Below is an example PVC with the Unikraft Cloud storage class you can apply to your cluster.

```yaml title="pvc.yaml"
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-claim
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: ukc-volume
  resources:
    requests:
      storage: 10Mi
```

Once applied, you can check the created PVC status:

```bash
kubectl get pvc
```

```ansi title=""
[1mNAME[0m       [1mSTATUS[0m   [1mVOLUME[0m                                    [1mCAPACITY[0m   [1mACCESS MODES[0m   [1mSTORAGECLASS[0m   [1mVOLUMEATTRIBUTESCLASS[0m   [1mAGE[0m
my-claim   Bound    pv-7ab06383-ac03-4a81-968a-1b0cff03c23a   10Mi       RWO            ukc-volume     <unset>                 4s
```

You can also check the volume on Unikraft Cloud:

```bash
unikraft volumes list
```

At this point, the volume exists but no instance mounts it, so it reports the `available` state.
To create an instance that uses the volume, create a Kubernetes Pod that references the PVC:

```yaml title="pod.yaml"
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
spec:
  tolerations:
    - key: "virtual-kubelet.io/provider"
      operator: "Equal"
      value: "ukc"
      effect: "NoSchedule"
  nodeSelector:
    kubernetes.io/hostname: kraftlet
  containers:
    - name: nginx
      image: nginx:latest
      ports:
        - containerPort: 8080
      volumeMounts:
        - mountPath: /usr/share/nginx/html
          name: nginx-storage
  volumes:
    - name: nginx-storage
      persistentVolumeClaim:
        claimName: my-claim
```

Once the Pod runs, the same volume reports the `mounted` state and names the instance that attached it.
Every Pod that references the same `ukc-volume` claim mounts the same Unikraft Cloud volume.

### Running commands with `kubectl exec`

Kraftlet serves `kubectl exec` through the [sandbox plugin](/features/plugins#sandbox-plugin), which runs inside the instance next to your app.

Exec needs chart version 0.10.0 or later, and stays off until you give Kraftlet the plugin image.
Set it by upgrading your existing Kraftlet release:

```bash
helm upgrade kraftlet \
  --namespace kraftlet \
  --reuse-values \
  --set kraftlet.env.KRAFTLET_EXEC_PLUGIN_IMAGE=plugins/sandbox:latest \
  oci://ghcr.io/unikraft-cloud/helm-charts/kraftlet
```

On a fresh install, add the same `--set` flag to the [`helm install`](#getting-started) command instead.

Exec needs Kraftlet to authenticate requests to its kubelet API.
The chart sets this up by default with the cluster CA.
Without it, Kraftlet refuses to start with exec on.
The API server also has to trust the [serving certificate](#serving-certificate) of Kraftlet, which Kraftlet can get with a CertificateSigningRequest.

Each Pod opts in with the `cloud.unikraft.v1.instances/enable-exec` annotation.
Kraftlet adds the plugin only to instances whose Pod carries it:

```yaml title="exec.yaml"
apiVersion: v1
kind: Pod
metadata:
  name: nginx-exec
  annotations:
    cloud.unikraft.v1.instances/enable-exec: "true"
spec:
  tolerations:
    - key: "virtual-kubelet.io/provider"
      operator: "Equal"
      value: "ukc"
      effect: "NoSchedule"
  nodeSelector:
    kubernetes.io/hostname: kraftlet
  containers:
    - name: nginx
      image: nginx:latest
      ports:
        - containerPort: 8080
```

Apply it, and once the Pod runs, run a command inside its instance:

```bash
kubectl apply -f exec.yaml
kubectl exec nginx-exec -- nginx -T
```

The command runs inside the instance, and `kubectl` prints its output and returns its exit code.
Kraftlet passes the arguments straight to the plugin without a shell, so the program must exist in the image.
To use pipes or globs, call a shell the image ships, for example `kubectl exec nginx-exec -- sh -c 'ls /etc | wc -l'`.

A few details differ from a regular kubelet:

* Commands run without a real terminal.
  `kubectl exec -it` still forwards your input, but full-screen programs and line editing don't work.
* Kraftlet collects output by polling the plugin, so each line shows up after a short delay.
  Set `KRAFTLET_EXEC_POLL_INTERVAL` through `kraftlet.env` to change that delay from its `250ms` default.
* An instance created before you enabled exec has no plugin.
  Recreate its Pod to add one.

### Serving certificate

The Kubernetes API server connects to Kraftlet to run `kubectl exec` and `kubectl logs`.
By default, Kraftlet serves a self-signed certificate.
If the API server checks the certificate, as on Amazon Elastic Kubernetes Service (EKS), both commands fail with `x509: certificate signed by unknown authority`.

From chart version 0.14.0, `tls.signerName` makes Kraftlet get its certificate from the cluster.
Kraftlet sends a CertificateSigningRequest to that signer, approves it, and renews the certificate before it expires.
The chart gives Kraftlet the permissions to do this for that signer only:

```bash
helm upgrade kraftlet \
  --namespace kraftlet \
  --reuse-values \
  --set tls.signerName=kubernetes.io/kubelet-serving \
  oci://ghcr.io/unikraft-cloud/helm-charts/kraftlet
```

On Amazon EKS, set `tls.signerName` to `beta.eks.amazonaws.com/app-serving` instead.
EKS issues `kubernetes.io/kubelet-serving` certificates only to the kubelets of its EC2 nodes, so a request from Kraftlet stays approved but never gets a certificate.

To use a certificate of your own, put it in a Secret and set `tls.secretName` and `tls.secretKeys` instead.
Set only one of `tls.signerName` and `tls.secretName`, because Kraftlet doesn't start with both.

### Egress filtering with a network shield

A [network shield](/features/network-shield) is an egress firewall for sandboxes.
It starts closed and only lets out what a policy allows, by host, network, port, or protocol.
It can also intercept TLS, rate-limit requests, and inject secrets into outgoing headers.
Kraftlet runs the shield as a sidecar: the container of the Pod that `cloud.unikraft.v1.instances/relay-container` names.

The shield container runs the shield image, with the `netshield` plugin attached through `cloud.unikraft.v1.instances/plugins.<container>`.
The `CA_CERT` and `CA_KEY` environment variables hold the [certificate authority](/features/network-shield#certificate-authority) it signs intercepted connections with.
Create a Secret from the `ca.crt` and `ca.key` files of the CA:

```bash
kubectl create secret generic shield-ca \
  --from-file=CA_CERT=ca.crt \
  --from-file=CA_KEY=ca.key
```

Then create a ConfigMap with the `netshield` plugin.
The plugin's `sandbox_iface` setting names `eth1`, the interface of the shield that the other instances of the Pod relay through:

```yaml title="netshield-plugins.yaml"
apiVersion: v1
kind: ConfigMap
metadata:
  name: netshield-plugins
data:
  plugins.json: |
    [
      {"name": "netshield", "rom": "plugins/netshield:latest", "config": {"sandbox_iface": "eth1"}}
    ]
```

The Pod runs the official shield image and reads the CA from the Secret:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: sandbox
  annotations:
    cloud.unikraft.v1.instances/relay-container: shield
    cloud.unikraft.v1.instances/plugins.shield: netshield-plugins
spec:
  containers:
    - name: app
      image: my-app:latest
    - name: shield
      image: official/utils/netshield:latest
      envFrom:
        - secretRef:
            name: shield-ca
```

Kraftlet creates the shield instance first, then relays every other instance of the Pod through it, init containers too.
DNS requests go through the shield as well.
It publishes the address of each plugin on the shield as `cloud.unikraft.v1.instances/plugins.<container>.<plugin>.url` on the Pod, which is where you send the policy.

Note the following:

- The shield restarts whenever it stops.
  Stateless scale-to-zero would wipe its in-memory state, so Kraftlet turns scale-to-zero off for the shield.
  Scale-to-zero annotations on the Pod override that, and apply to the shield as well.
- The Pod isn't `Running` until the shield runs.
  Services don't route to the shield, and the Pod IP is that of the other container.
- The Pod-wide `cloud.unikraft.v1.instances/template` annotation skips the shield.
  Give the shield a template of its own with `cloud.unikraft.v1.instances/template.<container>`.
- Kraftlet deletes the shield with the Pod, after the other instances.
- Every sandbox behind a shield has to [trust its certificate authority](/features/network-shield#trust-the-ca-in-a-sandbox), or intercepted connections fail.
- The official shield image needs two network interfaces.
  Kraftlet gives them to the shield container from version 0.6.0.
- A shield whose policy fails to apply stays closed, so replace the Pod.
- The shield drops inbound traffic until an inbound policy allows it.
  `kubectl exec` reaches the plugin of the sandbox through the shield, so it fails with `504 Gateway Time-out` until a policy opens the plugin ports, 20000 to 29999:

  ```json
  {
    "id": "sandbox-plugin",
    "direction": "inbound",
    "handler": "passthrough",
    "match": {"networks": ["0.0.0.0/0"], "port_ranges": [{"first": 20000, "last": 29999}]}
  }
  ```

- With `cloud.unikraft.v1.instances/enable-exec`, Kraftlet adds the plugin to the shield too, and the environment of the shield holds `CA_KEY`.
  Give `pods/exec` on the Pod only to users who may read the `shield-ca` Secret.
- A Pod with a shield can't use CNI.

## Kraftlet internals

This section describes how Kraftlet translates Kubernetes objects into Unikraft Cloud resources.

### Resource names

Kraftlet names every Unikraft Cloud resource after a base62-encoded hash of the Kubernetes object that owns it.
Hashing makes the names opaque, so map a resource back to its Kubernetes owner through the tags below rather than through the name.

### Tags

Kraftlet [tags](/platform/tagging) every instance and volume it creates with the Kubernetes object it belongs to:

| Tag | Instances | Volumes |
|---|---|---|
| `kraftlet:node=<node>` | Yes | Yes |
| `k8s.io:namespace=<namespace>` | Yes | Yes |
| `k8s.io:pod=<pod>` | Yes | No |
| `k8s.io:container=<container>` | Yes | No |
| `k8s.io:pvc=<claim>` | No | Yes |

Kraftlet replaces characters outside `A-Za-z0-9-+_.:=` with `_` and truncates any tag longer than 256 bytes.
Filter on these tags to find the resources behind a Kubernetes object:

```bash
unikraft instances list --filter 'tags.*==kraftlet:node=kraftlet'
unikraft volumes list --filter 'tags.*==k8s.io:pvc=my-claim'
```

### Ports and handlers

When Kraftlet maps a Kubernetes Service port to a Unikraft Cloud service, it derives the [handler](/platform/services#handlers) from the port number automatically:

| Port | Handler applied |
|------|-----------------|
| `80` | `http` |
| `443` | `tls + http` |
| Any other port | `tls` |

This is why the example above produces `443:8080/tls+http` in the service list.
Kraftlet infers `tls+http` from port 443.

A Service port only maps to a container when the port's `targetPort` matches a port the container declares, either by number or by name.
Kraftlet skips container ports without such a match, so declare every port you expose in the container specification.

A Pod that backs no Service, or whose Service ports match no container port, still reaches the network as long as it declares exactly one container port.
In that case Kraftlet creates a service on port 443 with the `tls` and `http` handlers, and the platform assigns a generated FQDN.
A Pod that backs no Service and declares more than one container port fails, and so does a Pod whose labels match more than one Kubernetes Service.

### Multi-container pods

Kraftlet maps each container in a pod to a **separate Unikraft Cloud instance**.
When a Pod has a single container, the Unikraft Cloud service covers the whole Kubernetes Service.
When a Pod has more than one container, each container gets its own Unikraft Cloud service derived from the Service name and the container name.

Kraftlet supports init containers.
Kraftlet schedules both regular containers and init containers as Unikraft Cloud instances, and deletes them together when you delete the Pod.

Some containers only make sense inside a cluster, such as a log shipper or a service mesh sidecar that a Unikraft Cloud instance never needs.
List those in the `cloud.unikraft.v1.instances/ignore` annotation and Kraftlet skips them.
An ignored container gets no instance and no service, and Kraftlet reports it as running so the Pod still becomes ready.

### Compute resources

Kraftlet sizes each instance from the container resource block, preferring limits over requests:

| Instance property | Source | Default |
|---|---|---|
| Memory | `limits.memory`, otherwise `requests.memory`, rounded up to whole MiB | `128` MiB |
| vCPUs | `limits.cpu`, otherwise `requests.cpu`, rounded up to whole CPUs | `1` |

A request such as `cpu: 500m` yields a single vCPU, and `cpu: 2` yields two.

Kraftlet passes the rest of the container specification through as well:

| Pod or container field | Unikraft Cloud instance property |
|---|---|
| `image` | Image, prefixed with `oci://` when Kraftlet resolves pull credentials |
| `imagePullPolicy` | Pull policy |
| `command` and `args` | Instance arguments, concatenated in that order |
| `env` | Instance environment |
| `spec.restartPolicy` | Restart policy: `Always`, `OnFailure` or `Never` |

The `cloud.unikraft.v1.instances/template` annotation changes this mapping.
Kraftlet then creates the instance from the named [instance template](/platform/instances#instance-templates).
The template supplies the image, resources, arguments, environment and volumes, and Kraftlet adds only the service, ROMs, plugins, scale-to-zero settings and tags.

### Environment variables

Kraftlet resolves the container environment in the cluster before it creates the instance, the same way a kubelet does.
It supports `envFrom` with a ConfigMap or Secret reference, `valueFrom` with `configMapKeyRef`, `secretKeyRef` or `fieldRef`, `$(VAR)` expansion between variables, and the service link variables Kubernetes injects for Services in the same namespace.
It marks optional references that go missing with a Pod event instead of failing.
It doesn't support `resourceFieldRef`.

### Files from ConfigMaps, Secrets and images

Kraftlet turns file-shaped volume mounts into [ROMs](/features/roms), one ROM per container, and mount.
The mount path becomes the ROM mountpoint, and every key becomes a file inside it:

| Pod volume source | ROM content |
|---|---|
| `configMap` | One file per key, or one file per entry under `items` |
| `secret` | One file per key, or one file per entry under `items` |
| `downwardAPI` | One file per entry, holding the referenced Pod field |
| `projected` | The merged content of its ConfigMap, Secret, downward API and service account token sources |
| `image` | The referenced image, attached directly as a ROM image |

Kraftlet requests service account tokens from the API server through the TokenRequest API, so projected tokens carry the expiry the Pod asks for.
It honors `optional: true` on ConfigMap and Secret sources and skips whatever it can't find.

:::note
Kraftlet resolves ROM content when it creates the instance.
Later edits to a ConfigMap or Secret don't reach an instance that already runs, so restart the Pod to pick them up.
:::

### Volumes

Kraftlet maps the remaining volume types onto Unikraft Cloud storage:

| Pod volume | Unikraft Cloud resource |
|---|---|
| Claim with the `ukc-volume` storage class | One [volume](/platform/volumes) per claim, shared by every Pod that mounts it |
| Claim with any other CSI storage class | One volume per Pod, staged through the CSI driver |
| `emptyDir` | One volume per Pod and mount, sized from `sizeLimit` and defaulting to 100 MiB |
| `emptyDir` with `medium: Memory` | Nothing, Kraftlet skips the mount |
| `hostPath` | One [managed volume](/features/managed-volumes) per Pod and mount |

Kraftlet rounds an `emptyDir` size limit up to whole MiB.
It deletes the volumes it created for `emptyDir` and `hostPath` mounts together with the Pod, while a `ukc-volume` claim keeps its volume until you delete the claim.

`hostPath` support stays off unless you set `KRAFTLET_ENABLE_HOST_PATH_VOLUMES=true` through `kraftlet.env`.

#### Third-party CSI drivers

Kraftlet can serve claims that belong to another storage system, such as a cloud block store, by driving that system through its CSI driver.
Register each driver under `csi.plugins` as a `driverName: host:port` pair, or as a path to its socket.

```yaml title="values.yaml"
csi:
  plugins:
    ebs.csi.aws.com: "ebs-csi-node.kube-system.svc:9000"
```

For a Pod that mounts such a claim, Kraftlet waits for the volume attachment when the driver needs one, then calls the driver to stage the volume under `csi.stagingBasePath`.
It then creates a managed volume that points at the staging path.
It health-checks every registered driver on the `csi.healthCheckInterval` and refuses to stage through a driver that reports unhealthy.
Setting any `csi` value also makes the chart advertise the `volumes.kubernetes.io/controller-managed-attach-detach` node annotation.

:::note
The platform resolves a managed volume path on the machine that runs the instance.
This flow expects Kraftlet to stage volumes on that same machine, which holds for on-prem and bring-your-own-cloud installations.
:::

### Init containers

Kraftlet runs init containers as ordinary instances, one after another, before it creates the instances for the regular containers.
Each init instance starts with autostart off, restarts off and scale-to-zero off.
Kraftlet starts it, waits for it to stop, and treats a non-zero exit code as a failure.

A Pod with the `Always` or `OnFailure` restart policy makes Kraftlet retry a failed init instance with an exponential backoff that grows from one second to five minutes.
With `Never`, the first failure stops the Pod from starting.

### Private registries

Kraftlet reads the Secrets listed under `spec.imagePullSecrets` and passes the matching credentials to the platform with the image.
It accepts both the `kubernetes.io/dockerconfigjson` and the `kubernetes.io/dockercfg` Secret types, and matches an entry to the image by registry host.
An image without a registry host, such as `nginx:latest`, and an image on `docker.io` both match the `index.docker.io` entry.

### Pod status

Kraftlet subscribes to the platform's [event stream](/platform/audit-events) and updates a Pod as soon as its instance stops, fails, or errors.
It also keeps refreshing the status of every Pod it manages on the `kraftlet.podStatusUpdateInterval`, which defaults to 15 seconds, to catch changes the stream misses.
When the stream drops events, it re-syncs every Pod on the node.
A move into `running` or `standby` triggers no refresh, so scale-to-zero churn doesn't flood the Kubernetes API.
Set `KRAFTLET_ENABLE_INSTANCE_EVENTS=false` through `kraftlet.env` to go back to polling only.
Kraftlet reads instance state through an instance cache instead of asking the platform once per Pod.
The cache merges the lookups that arrive together into shared requests, and remembers newly created instances so their first status updates need no extra request.
As a result, the time from creating a Pod to seeing it `Running` stays flat as the node grows.

It derives the Pod phase from the state of the backing instances:

| Instance state | Pod phase |
|---|---|
| `starting` | `Pending` |
| `running`, `draining`, `stopping` | `Running` |
| `standby` | `Running`, or `Pending` while the platform reports a failure |
| `stopped` after a clean shutdown | `Succeeded` |
| `stopped` after a fault or a failed image pull | `Failed` |
| Any state, once the platform stopped the instance for insufficient quota | `Failed` |

The container status carries the detail behind a failure.
An instance the platform stopped for running out of memory surfaces as `OOMKilled` with exit code 137.
A failed image pull surfaces as `ErrImagePull`, a stop for insufficient quota surfaces as `QuotaExceeded` with exit code 1, and any other platform-side stop surfaces as `PlatformError`.
Note that the running quota is dynamic, so on the next request, an instance which failed to start with `QuotaExceeded` might succeed.
An instance with exactly one network interface also contributes its private IP as the Pod IP.

Kraftlet records what it does on the Pod as events:

```ansi title=""
[1mLAST SEEN[0m   [1mTYPE[0m     [1mREASON[0m                  [1mOBJECT[0m                        [1mMESSAGE[0m
12s         Normal   CreateInstanceSuccess   pod/my-app-78c766fb67-k2dgk   started instances
```

`CreateInstanceFailed` and `PodCreateServiceFailed` carry the platform error that blocked the Pod.

`kubectl logs` works against a Pod on the Kraftlet node, if the API server trusts the [serving certificate](#serving-certificate) of Kraftlet.
Kraftlet serves it from the instance console and returns the last 4096 bytes.
The `--tail` and `--limit-bytes` flags move that window, and Kraftlet counts both in bytes rather than in lines.

### Node capacity and conditions

Kraftlet reports the node capacity from your Unikraft Cloud [quotas](/platform/quotas), so the Kubernetes scheduler stops placing Pods once you run out of headroom:

| Node resource | Quota |
|---|---|
| `cpu` | Live vCPU quota |
| `memory` | Live memory quota |
| `pods` | Instance quota |

Kraftlet reports allocatable capacity equal to capacity, and refreshes both on every node status interval.
It also maps quota exhaustion and platform health onto node conditions:

| Condition | Kraftlet sets it when |
|---|---|
| `Ready` | The platform answers its health check |
| `MemoryPressure` | The workloads use up the live memory quota |
| `DiskPressure` | The volumes use up the storage quota |
| `PIDPressure` | The instances use up the live instance quota |
| `UnikraftPlatformHealthy` | The platform health endpoint reports a healthy state |

An unreachable platform turns `Ready` to false, so the scheduler stops placing new Pods on the node until the platform answers again.

### Pod rescheduling

Idle instances go to `standby` and hold no live memory, which lets a node carry far more Pods than its live memory quota can run at once.
Resuming one can fail once the quota is full, and the platform then leaves the instance in a stopped or scaled-to-zero state rather than starting it.

Kraftlet reports such a Pod as `Failed` with the reason `QuotaExceeded`, and then deletes the Pod so the controller that owns it schedules a replacement.
The node reports `MemoryPressure` as soon as its next quota refresh finds the live memory quota exhausted.
That condition becomes a `node.kubernetes.io/memory-pressure:NoSchedule` taint, which your Pods don't tolerate, so the replacement stays off that node until live memory frees up.
On a cluster that [autoscales with Karpenter](/integrations/karpenter), the replacement lands on another node, or on a node the autoscaler creates for it.

Keep these in mind when running your workloads:

* Run Pods under a Deployment, ReplicaSet, StatefulSet or Job, since Kraftlet reclaims only a Pod that has a controller behind it.
  It leaves a bare Pod `Failed` in place, because deleting that Pod would leave nothing behind to replace it.
* Reclaiming a Pod runs the same teardown as a delete, so its instances and Pod-scoped volumes (including `emptyDir` and `hostPath` volumes) go with it.
  Volumes behind PersistentVolumeClaims remain until you delete their claims.

Kraftlet reclaims failed Pods by default.
Set `kraftlet.enableFailedPodReclaim=false` to leave them in place instead.

### Resource lifecycle

Kraftlet adds the `cloud.unikraft.v1/resources` finalizer to every Pod it accepts, so a delete only completes once Kraftlet removes the Unikraft Cloud resources.
When you delete a Kubernetes object, Kraftlet deletes the corresponding Unikraft Cloud resources:

| Kubernetes object deleted | Unikraft Cloud resources deleted |
|---|---|
| Pod or Deployment replica | Instances for its containers and init containers, the service once no instance uses it, the volumes for its `emptyDir` and `hostPath` mounts, and any certificate the service held |
| PersistentVolumeClaim with the `ukc-volume` class | The volume behind the claim |

Kraftlet also cleans up a Pod that finishes on its own.
Once every container reaches a successful stop and the Pod phase becomes `Succeeded`, Kraftlet deletes its instances and volumes.

:::caution
Turn off finalizers by setting `KRAFTLET_POD_FINALIZER=""`, but be careful-this risks leaking resources on the Unikraft platform when the Kraftlet node is draining.
:::

## Platform features

Kraftlet supports the following Unikraft Cloud platform features on Kraftlet-managed resources:

* [**Instance templates**](/platform/instances#instance-templates)

  Frequently deployed workloads can go into instance templates.
  Templates pre-warm the snapshot, reducing cold-start latency for every new instance created from the template.
  Point a Pod at one with the `cloud.unikraft.v1.instances/template` annotation.

* [**Scale-to-zero**](/features/scale-to-zero)

  Instances that back a service or carry plugins suspend automatically when idle.
  Scale-to-zero runs by default for those instances and you can configure it through Pod annotations.
  Kraftlet turns it off for an instance with neither a service nor a plugin, since nothing would wake it again.

* [**ROMs**](/features/roms)

  Kraftlet ships ConfigMaps, Secrets, downward API fields and image volumes to instances as ROMs.

* [**Plugins**](/features/plugins)

  A Pod can attach plugins to its instances through a ConfigMap, and Kraftlet annotates the Pod with the endpoint of each running plugin.

* [**Managed volumes**](/features/managed-volumes)

  `hostPath` mounts and volumes staged through third-party CSI drivers become managed volumes.

* [**Tagging**](/platform/tagging)

  Every instance and volume Kraftlet creates carries the identity of its Kubernetes owner.

* [**Custom network configuration**](/features/custom-network-configuration)

  Instances can carry addresses and TAP devices that you choose instead of ones from the platform pool.
  Kraftlet drives this through CNI plugins.

* [**Annotations**](/features/annotations)

  Instance metadata that also reaches the guest.
  Kraftlet writes the [CNI result](/features/annotations#guest-network-configuration-with-cni) that a guest configures its own interfaces from.

* [**Network shield**](/features/network-shield)

  A sidecar container of the Pod filters its egress traffic.
  See [egress filtering with a network shield](#egress-filtering-with-a-network-shield).

## Custom networking with CNI

{/* vale off */}
:::caution[**Limited Access**]
CNI-based networking for Kraftlet is available as part of enterprise plans.
To enable it for your account, reach out to the [Unikraft Cloud Discord](https://unikraft.com/discord) or send an email to [support@unikraft.com](mailto:support@unikraft.com).
:::
{/* vale on */}

The [Container Network Interface](https://www.cni.dev/) (CNI) configures the networking stack of a workload through plugins.
This split lets vendors such as AWS, Tigera and Isovalent each ship their own plugin for configuring networking.
Kubernetes builds on the same interface, and the kubelet invokes the installed CNI plugins on every node of the cluster.

Kraftlet takes that role for Pods on its node that opt in with the `cloud.unikraft.v1.instances/cni-enabled` annotation.
It invokes the CNI plugins of your cluster and passes the resulting interfaces and addresses to Unikraft Cloud.
The platform then creates the instance with [custom network interfaces](/features/custom-network-configuration) rather than with interfaces from its own address pool.
Instances join the same networks as native Pods and follow the same address management as the rest of the cluster.

A companion component, `remote-cni`, exposes the plugins over gRPC for clusters where Kraftlet runs apart from the machine that hosts the instances.

An instance's `network_interfaces` only accept IPv4 addresses.
Therefore, the Kraftlet hands the rest of a plugin result—IPv6 addresses, in practice—to the guest through the [`unikraft.com/cni` annotation](/features/annotations#guest-network-configuration-with-cni), and the guest configures them on its own interfaces.
Kraftlet does this for the Pod's default network, a secondary network contributes its IPv4 addresses alone.
You can write the same annotation yourself on an instance you create through the API, for an [interface without an address](/features/custom-network-configuration#interfaces-without-an-address) whose addressing an IPAM system owns.

A CNI Pod can bring its own resolvers.
Kraftlet passes the Pod's `spec.dnsConfig`, its nameservers, search domains, and options, to the instance, and falls back to the DNS from the CNI result when the Pod sets none:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  annotations:
    cloud.unikraft.v1.instances/cni-enabled: "true"
spec:
  dnsPolicy: None
  dnsConfig:
    nameservers: ["2001:4860:4860::8888"]
    searches: ["svc.example.internal"]
```

`dnsPolicy` itself has no effect, and a Pod without CNI keeps the platform's resolver.

## Annotations

Kraftlet reads the following annotations from Pod and Service objects to configure Unikraft Cloud resources.

### Pod annotations

| Annotation | Type | Default | Description |
|---|---|---|---|
| `cloud.unikraft.v1.instances/autostart` | boolean | `true` | Whether the instance starts automatically when Kraftlet schedules the Pod. |
| `cloud.unikraft.v1.instances/cni-enabled` | boolean | `false` | Configures the Pod's networking through the CNI plugins of the cluster, as [custom networking with CNI](#custom-networking-with-cni) describes. |
| `cloud.unikraft.v1.instances/template` | string | — | Name of a pre-existing Unikraft Cloud instance template to use instead of the container image. |
| `cloud.unikraft.v1.instances/template.<container>` | string | — | Same as above, for a single container, where an empty value keeps that container on its image. |
| `cloud.unikraft.v1.instances/ignore` | string | — | Comma-separated container names that Kraftlet leaves out of Unikraft Cloud. |
| `cloud.unikraft.v1.instances/enable-exec` | boolean | `false` | Adds the sandbox plugin so [`kubectl exec`](#running-commands-with-kubectl-exec) reaches the instance. Needs exec turned on in Kraftlet. |
| `cloud.unikraft.v1.instances/plugins` | string | — | ConfigMap holding the plugin list, written as `<configmap>` or `<configmap>/<key>`. |
| `cloud.unikraft.v1.instances/plugins.<container>` | string | — | Same as above, for a single container of a multi-container Pod. |
| `cloud.unikraft.v1.instances/relay-container` | string | — | Container of the Pod that runs as its [network shield](#egress-filtering-with-a-network-shield), with every other instance of the Pod relaying through it. |
| `cloud.unikraft.v1.instances/scale_to_zero.policy` | `on` \| `off` \| `idle` | `on` | Enables or disables scale-to-zero for instances that back a service or carry plugins. |
| `cloud.unikraft.v1.instances/scale_to_zero.stateful` | boolean | `false` | When `true`, Kraftlet retains the instance state when scaling to zero. |
| `cloud.unikraft.v1.instances/scale_to_zero.cooldown_time_ms` | integer | `1000` | Idle time in milliseconds before Kraftlet suspends the instance. |

The plugin ConfigMap holds a JSON array of plugin objects under the `plugins.json` key, or under the key you name in the annotation.
Kraftlet also accepts a ConfigMap with a single key of any name.

```yaml title="plugins.yaml"
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-plugins
data:
  plugins.json: |
    [
      {"name": "metrics", "rom": "my-org/metrics:latest", "config": {"interval": 5}}
    ]
```

### Service annotations

| Annotation | Type | Default | Description |
|---|---|---|---|
| `cloud.unikraft.v1.services/domain` | string | — | Custom [domain](/platform/domains) for the Unikraft Cloud service. |
| `cloud.unikraft.v1.services/domain.<container>` | string | — | Per-container domain for a multi-container Pod. |

A bare label such as `my-app` becomes a subdomain of the metro, giving `my-app.fra.unikraft.app`.
A fully qualified name such as `app.example.com` makes the platform request a [certificate](/platform/certificates) for it.
For a multi-container Pod, the global annotation applies to every container as `<container>-<domain>`, and the per-container form overrides it.

### Status annotations

Kraftlet writes a few annotations back onto the Pod as it reports status:

| Annotation | Description |
|---|---|
| `cloud.unikraft.v1.instances/plugins.<plugin>.url` | Address of a running plugin, prefixed with the container name for multi-container Pods and for the network shield. |
| `cloud.unikraft.v1.instances/fqdns` | JSON object mapping each container to the private and service FQDN of its instance. |

The FQDN annotation stays off until you install the chart with `--set kraftlet.enableInstanceFqdnAnnotations=true`.

## Helm chart values

The values below cover the settings most deployments touch.

| Value | Default | Description |
|---|---|---|
| `ukc.metro` | — | Metro name such as `fra`, or a full API endpoint address. |
| `ukc.token` | — | Unikraft Cloud token, which the chart stores in a Secret. |
| `image.name` and `image.tag` | `ghcr.io/unikraft-cloud/kraftlet` and `latest` | Kraftlet image. |
| `node.name` | `kraftlet` | Name Kraftlet registers with the control plane. |
| `node.architecture` | `amd64` | Architecture the node advertises. |
| `node.taint.enable` | `true` | Whether Kraftlet taints its node. |
| `node.taint.key`, `node.taint.value`, `node.taint.effect` | `virtual-kubelet.io/provider`, `ukc`, `NoSchedule` | The taint Kraftlet applies. |
| `node.labels` and `node.annotations` | — | Extra labels and annotations for the node object. |
| `node.providerId` | — | Provider ID of the machine backing the node. |
| `kraftlet.replication.enabled` and `kraftlet.replication.replicas` | `false` and `1` | Run more than one Kraftlet, each registering its own node. |
| `kraftlet.enablePvcWatcher` | `false` | Manage the lifecycle of `ukc-volume` claims. |
| `kraftlet.enableInstanceFqdnAnnotations` | `false` | Annotate Pods with the FQDNs of their instances. |
| `kraftlet.enableFailedPodReclaim` | `true` | Delete a Pod that fails because the live memory quota is full, so its controller replaces it. |
| `kraftlet.podStatusUpdateInterval` | `15s` | How often Kraftlet refreshes Pod status from the platform, alongside the event stream. |
| `kraftlet.podSyncWorkers` | `1` | Number of Pod reconcile workers. |
| `kraftlet.logLevel` and `kraftlet.logType` | `info` and `json` | Log verbosity and format. |
| `kraftlet.port` | `10250` | Port for the kubelet API that serves logs and Pod listings. |
| `kraftlet.k8s.qps` and `kraftlet.k8s.burst` | — | Rate limits for the API server client. |
| `kraftlet.env` | — | Extra environment variables for the Kraftlet container. |
| `csi.plugins` | — | CSI drivers Kraftlet calls, as `driverName: host:port` pairs. |
| `csi.stagingBasePath` | `/var/lib/kubelet/plugins/kubernetes.io/csi/staging` | Where Kraftlet stages CSI volumes. |
| `csi.healthCheckInterval` | `10s` | How often Kraftlet health-checks each CSI driver. |
| `tls.secretName` and `tls.secretKeys` | — | Serving certificate for the kubelet API. |
| `resources` | — | Resource requests and limits for the Kraftlet pod. |
| `priorityClassName` | — | PriorityClass for the Kraftlet pod, which keeps its node registered under pressure. |

## Current limitations

A Kraftlet node is a virtual kubelet in front of a remote platform, so a few kubelet behaviors have no counterpart:

* `kubectl attach` doesn't reach an instance.
  Use [`kubectl exec`](#running-commands-with-kubectl-exec) to run commands inside it instead.
* `kubectl top pod` returns nothing, since Kraftlet serves no stats summary.
  Read [instance metrics](/platform/instances#instance-metrics) instead.
* Liveness, readiness, and startup probes never run.
  Kraftlet reports readiness from the instance state.
* Kraftlet applies no in-place updates to a Pod specification.
  Recreate the Pod to change the instance behind it.
* A Pod may back at most one Kubernetes Service.
* `subPath` on a volume mount has no effect.
* An `emptyDir` with `medium: Memory` gets no backing volume.
