February 20, 2025

Expose native k8s services using Cloudflared

Prerequisites

Steps

  1. Install Cloudflared
brew install cloudflared
  1. Log in to your Cloudflare account
cloudflared tunnel login

Note: if you have multiple domains, you might have to select the one you want the tunnel to be created on

  1. Create a tunnel
cloudflared tunnel create <your-tunnel-name>
# example
cloudflared tunnel create sample-nginx-service
  1. Create an nginx pod and expose it as a service
kubectl run nginx --image nginx
kubectl expose pod nginx --selector="run=nginx" --port=80 --target-port=80 --type=ClusterIP
  1. Create a config file (config.yaml) with hostname and service mapping
tunnel: 82c1e1f0-b98f-4672-987e-89d0b074d272
credentials-file: /etc/cloudflared/creds/credentials.json
ingress:
  - hostname: sample-nginx-service.cognitivenode.com
    service: http://nginx:80
  - service: http_status:404
  1. Create a configmap from the above config file
kubectl create configmap cloudflared-config --from-file=config.yaml
  1. Create kubernetes secrets for tunnel credentials and certificate
kubectl create secret generic tunnel-credentials --from-file=credentials.json=$HOME/.cloudflared/82c1e1f0-b98f-4672-987e-89d0b074d272.json 
kubectl create secret generic tunnel-cert --from-file=cert.pem=$HOME/.cloudflared/cert.pem
  1. Deploy Cloudflared to Kubernetes. Create a file named cloudflared-deployment.yaml with the following content:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cloudflared
spec:
  replicas: 2
  selector:
    matchLabels:
      app: cloudflared
  template:
    metadata:
      labels:
        app: cloudflared
    spec:
      containers:
      - name: cloudflared
        image: cloudflare/cloudflared:latest
        args:
        - tunnel
        - --config
        - /etc/cloudflared/config.yml
        - run
        volumeMounts:
        - name: config
          mountPath: /etc/cloudflared
        - name: creds
          mountPath: /etc/cloudflared/creds
      volumes:
      - name: creds
        secret:
          secretName: tunnel-credentials
      - name: config
        configMap:
          name: cloudflared-config
  1. Apply the Cloudflared deployment
kubectl apply -f cloudflared-deployment.yaml

After completing these steps, your Kubernetes service should be exposed via Cloudflare Tunnel. Access it using the hostname specified in the config file.

© Nataraj Basappa 2025