# Expose a workload

Create an `IngressClass` that uses a Cloudflare Tunnel, then publish an nginx
Deployment on a hostname in your Cloudflare zone. Kite's tunnel controller
runs on either control plane. It creates the tunnel, runs `cloudflared` in the
cluster, and creates the DNS records.

## What you need

- A Ready node that can pull `nginx:1.27`, and `kubectl` signed in to the
  cluster.
- A Cloudflare zone and a hostname in it.
- A Cloudflare API token with these permissions:

| Scope   | Permission                   | Resources                                 |
| ------- | ---------------------------- | ----------------------------------------- |
| Account | `Cloudflare Tunnel` — `Edit` | Only your account                         |
| Zone    | `DNS` — `Edit`               | Only the zone that contains your hostname |

Give the token an end date under **TTL**, and replace it in the Secret before
then. See [Credentials](/docs/ingress/#credentials).

<Aside type="caution">
  The token can change every tunnel in the account and every DNS record in the zone. Do not put it
  in a manifest, commit it, or paste it into shell history. Anyone who can read Secrets in its
  namespace can use it. See [Security model](/docs/security/#ingress-credentials).
</Aside>

## 1. Store the Cloudflare token

Set your account and zone IDs, the namespace for the credentials and the
name of the class, then create the namespace:

```bash

kubectl apply -f - <<EOF
apiVersion: v1
kind: Namespace
metadata:
  name: ${CF_NAMESPACE}
EOF
```

Create the Secret. This script prompts for the token and keeps it out of your
shell history and `kubectl` arguments:

```bash
umask 077
TOKEN_FILE="$(mktemp)"
trap 'rm -f "$TOKEN_FILE"' EXIT
read -rsp 'Cloudflare API token: ' CF_API_TOKEN
printf '\n'
printf %s "$CF_API_TOKEN" > "$TOKEN_FILE"
unset CF_API_TOKEN

kubectl create secret generic cloudflare-credentials \
  --namespace "$CF_NAMESPACE" \
  --from-literal=accountId="$CF_ACCOUNT_ID" \
  --from-literal=zoneId="$CF_ZONE_ID" \
  --from-file=apiToken="$TOKEN_FILE"

rm -f "$TOKEN_FILE"
trap - EXIT
```

## 2. Create the IngressClass

```bash
kubectl apply -f - <<EOF
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
  name: ${CF_CLASS}
spec:
  controller: cloudflare.com/tunnel
  parameters:
    kind: Secret
    name: cloudflare-credentials
    scope: Namespace
    namespace: ${CF_NAMESPACE}
EOF

kubectl rollout status deployment/${CF_CLASS}-tunnel \
  --namespace "$CF_NAMESPACE" \
  --timeout=180s
```

The tunnel controller runs two `cloudflared` pods for the class in
`$CF_NAMESPACE`.

### If the rollout times out

Run `kubectl describe ingressclass "$CF_CLASS"` and read the Warning Events:

| Event reason          | Fix                                                                                                      |
| --------------------- | -------------------------------------------------------------------------------------------------------- |
| `CredentialsUnusable` | The Secret is wrong. Fix it.                                                                             |
| `TunnelUnavailable`   | A Cloudflare API call failed, for example because the account and the zone do not match. Fix the Secret. |

The controller runs again when you edit the Secret, so watch the rollout again
after the fix.

## 3. Create an HTTP workload and route

Choose a hostname in your zone. This manifest creates a namespace, a
Deployment, a Service, and an Ingress:

```bash

kubectl apply -f - <<EOF
apiVersion: v1
kind: Namespace
metadata:
  name: ${APP_NAMESPACE}
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello
  namespace: ${APP_NAMESPACE}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hello
  template:
    metadata:
      labels:
        app: hello
    spec:
      containers:
        - name: hello
          image: nginx:1.27
          ports:
            - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: hello
  namespace: ${APP_NAMESPACE}
spec:
  selector:
    app: hello
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: hello
  namespace: ${APP_NAMESPACE}
spec:
  ingressClassName: ${CF_CLASS}
  rules:
    - host: ${APP_HOST}
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: hello
                port:
                  number: 80
EOF

kubectl rollout status deployment/hello --namespace "$APP_NAMESPACE"
kubectl get ingress hello --namespace "$APP_NAMESPACE" \
  -o jsonpath='{.status.loadBalancer.ingress[0].hostname}{"\n"}'
```

The last command prints an empty line until the controller adds the Ingress to
the tunnel. Then it prints a `*.cfargotunnel.com` hostname. The controller also
creates a DNS record for `APP_HOST`. Once the record has propagated, request
the hostname:

```bash
curl --fail --show-error "https://${APP_HOST}/"
```

You see the nginx welcome page.

<Aside type="note">
  To publish a Service that you already have, create only the Ingress. The backend port must serve
  plain HTTP. For a backend that serves TLS, set `appProtocol` as in [Reach a TLS
  backend](/docs/ingress/#reach-a-tls-backend). The controller does not route raw TCP or UDP.
</Aside>

### If the route doesn't respond

Run `kubectl describe ingress hello --namespace "$APP_NAMESPACE"` and
`kubectl describe ingressclass "$CF_CLASS"`:

| What you see                                    | What to check                                                                                                                                                                   |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A Warning Event on the Ingress                  | The controller skipped the Ingress. [Tunnel reasons](/docs/reference/events/#tunnel-reasons) explains the reason.                                                               |
| A `TunnelUnavailable` Event on the IngressClass | The hostname is in your zone.                                                                                                                                                   |
| No Event                                        | The Ingress's `ingressClassName` names a class that exists. Then check that the Service has endpoints and that the `${CF_CLASS}-tunnel` Deployment in `$CF_NAMESPACE` is ready. |

## Publish a LoadBalancer Service

You can publish a Service of `type: LoadBalancer` without an Ingress. Set the
hostname in the `cloudflare.com/hostname` annotation and the class in
`cloudflare.com/ingress-class`:

```bash

kubectl apply -f - <<EOF
apiVersion: v1
kind: Service
metadata:
  name: hello-lb
  namespace: ${APP_NAMESPACE}
  annotations:
    cloudflare.com/hostname: ${APP_LB_HOST}
    cloudflare.com/ingress-class: ${CF_CLASS}
spec:
  type: LoadBalancer
  selector:
    app: hello
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 80
EOF

kubectl get service hello-lb --namespace "$APP_NAMESPACE"
```

`EXTERNAL-IP` shows `<pending>`, then a `*.cfargotunnel.com` hostname. The
Service must have exactly one HTTP port, as
[Publish a LoadBalancer Service](/docs/ingress/#publish-a-loadbalancer-service)
defines it. Otherwise the controller records the reason as an Event on the
Service.

## Choose the nodes that run cloudflared

Create a ConfigMap named `${CF_CLASS}-tunnel-override` in `$CF_NAMESPACE`. Its
`podTemplate` key contains JSON that the controller merges over the
`cloudflared` pod template. This ConfigMap places the pods on nodes with the
label `edge: "true"`:

```bash
kubectl apply -f - <<EOF
apiVersion: v1
kind: ConfigMap
metadata:
  name: ${CF_CLASS}-tunnel-override
  namespace: ${CF_NAMESPACE}
data:
  podTemplate: |
    {"spec":{"nodeSelector":{"edge":"true"}}}
EOF
```

The controller reads the ConfigMap the next time it runs for the class. The
class from step 2 already exists, so annotate it to make the controller run
now. Annotate it again after each edit of the ConfigMap:

```bash
kubectl annotate ingressclass "$CF_CLASS" retried-at="$(date +%s)" --overwrite
```

Do not edit the Deployment that the controller creates, because the controller
overwrites it.

## Clean up

```bash
kubectl delete namespace "$APP_NAMESPACE"
```

Once no Ingress uses the class, delete the class and the credentials:

```bash
kubectl delete ingressclass "$CF_CLASS"
kubectl delete secret cloudflare-credentials --namespace "$CF_NAMESPACE"
```

Deleting the class removes the `cloudflared` pods, the DNS records, and the
Cloudflare tunnel. Cloudflare deletes the tunnel only after its pods
disconnect, so the controller retries for a few minutes.
[Ingress and load balancing](/docs/ingress/) lists the Events that a
failed teardown records.

## Next

- [Ingress and load balancing](/docs/ingress/): protocols, ownership, and
  recovery.
- [Networking](/docs/networking/): how the `cloudflared` pods reach your
  Service over the pod network.
- [Tunnel reasons](/docs/reference/events/#tunnel-reasons): each Event that the tunnel
  controller records.
