Prerequisites
- Kubernetes cluster
kubectl
configured- Domain and a Cloudflare account
- Homebrew (for macOS users)
Steps
- Install Cloudflared
brew install cloudflared
- 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
- Create a tunnel
cloudflared tunnel create <your-tunnel-name>
# example
cloudflared tunnel create sample-nginx-service
- 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
- 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
- Create a configmap from the above config file
kubectl create configmap cloudflared-config --from-file=config.yaml
- 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
- 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
- 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.