Running Conduit from Kubernetes resources
With the kubernetes feature Conduit reads its sites from ConduitSite objects instead of a config file. Each object is
one virtual site; Conduit watches the namespace, builds one config from every object, validates it and swaps it in
without a restart.
Table of Contents
- What you need
- Install
- Your first site
- What a
ConduitSitemay contain - What happens on every change
- What does not apply live
- Who may write
ConduitSiteobjects - Troubleshooting
What you need
- The full image,
ghcr.io/lopatnov/conduit:latest(or a build with--features kubernetes). The other image variants do not contain the Kubernetes provider; see deployment.md. kubectlaccess to a cluster that may create aCustomResourceDefinition.- A service account for the Conduit pod that may
get,listandwatchconduitsites.
The pod is started with --kubernetes-namespace <namespace> ('*' for every namespace) and no config file. Conduit
connects with the pod’s service account, or with KUBECONFIG outside a cluster.
Install
1. The ConduitSite definition, once per cluster:
kubectl apply -f contrib/k8s/conduitsite-crd.yaml
2. A service account that may read the objects. One namespace needs a Role; --kubernetes-namespace '*' needs a
ClusterRole and a ClusterRoleBinding with the same rules.
apiVersion: v1
kind: ServiceAccount
metadata:
name: conduit
namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: conduit
namespace: default
rules:
- apiGroups: ["conduit.lopatnov.github.io"]
resources: ["conduitsites"]
verbs: ["get", "list", "watch"]
- apiGroups: ["conduit.lopatnov.github.io"]
resources: ["conduitsites/status"]
verbs: ["patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: conduit
namespace: default
subjects:
- kind: ServiceAccount
name: conduit
namespace: default
roleRef:
kind: Role
name: conduit
apiGroup: rbac.authorization.k8s.io
Conduit reads the objects and writes only their status (the patch rule on conduitsites/status): READY and a
message in kubectl get conduitsites, true and Valid for a site whose spec Conduit accepted. The server can still refuse the whole update (two sites
with one host and port, a change that needs a restart); that is in its log, not in the status. Without that rule
Conduit works as before and says once in the log that it cannot write the status.
3. A Deployment and a Service. A site listens on the port of its spec; the Service forwards to the same port.
apiVersion: apps/v1
kind: Deployment
metadata:
name: conduit
namespace: default
spec:
replicas: 2
selector:
matchLabels: { app: conduit }
template:
metadata:
labels: { app: conduit }
spec:
serviceAccountName: conduit
containers:
- name: conduit
image: ghcr.io/lopatnov/conduit:latest
args: ["--kubernetes-namespace", "default"]
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: [ALL] }
ports:
- { name: http, containerPort: 8080 }
readinessProbe:
httpGet: { path: /__health__, port: http }
---
apiVersion: v1
kind: Service
metadata:
name: conduit
namespace: default
spec:
selector: { app: conduit }
ports:
- { name: http, port: 80, targetPort: http }
The readiness probe asks for /__health__, which exists only on a site that sets healthCheck: true: give the site on
port 8080 that setting, as the example below does. The image runs as an unprivileged user, so a site listens on a port
above 1024 unless the pod is given the right to bind lower ones.
The Admin API listens on 127.0.0.1:2019 inside the pod in this mode, and its bind address cannot be set from a
ConduitSite. It always has a token, because a ConduitSite can route to loopback (see
who may write): the one in the pod’s CONDUIT_ADMIN_TOKEN environment variable
(from a Secret, for example), or, when that is not set, a random one that nobody knows, which closes the API. The
conduit status and the other admin commands read the same variable, so run them in the pod with it set.
Redis for shared limits and caches. Several replicas share a rate limit or a cache through one Redis, and the operator
names it once, in the Deployment: the CONDUIT_REDIS_URL environment variable (from a Secret, because the URL may carry a
password). A ConduitSite then only says store: redis, and never an address: a redis:// address in a ConduitSite is
refused like a host path, and store: redis without CONDUIT_REDIS_URL in the pod makes that site invalid.
env:
- name: CONDUIT_REDIS_URL
valueFrom:
secretKeyRef: { name: conduit-redis, key: url } # redis://:password@redis.default.svc:6379
rateLimit: { windowSecs: 60, limit: 100, store: redis }
The address is read when the pod starts: changing the Secret takes a rollout (kubectl rollout restart deployment/conduit).
Your first site
apiVersion: conduit.lopatnov.github.io/v1
kind: ConduitSite
metadata:
name: my-app
namespace: default
spec:
port: 8080
host: app.example.com
healthCheck: true
proxy:
/api:
targets: [http://api-svc:4000]
healthCheck: { path: /health }
rateLimit: { windowSecs: 60, limit: 500 }
securityHeaders: true
kubectl apply -f my-app.yaml
kubectl get conduitsites # PORT, HOST, READY and AGE of every site
kubectl logs deploy/conduit | grep ConduitSite
Within a few seconds the log shows config updated from ConduitSite CRDs and then live config update received, and
the site answers.
A spec holds the same fields as one entry of sites: in a config file. To check a spec before it goes to the cluster,
put it in a file and run conduit validate:
sites:
- port: 8080
host: app.example.com
healthCheck: true
proxy:
/api:
targets: [http://api-svc:4000]
healthCheck: { path: /health }
rateLimit: { windowSecs: 60, limit: 500 }
securityHeaders: true
conduit validate -c sites.yaml
conduit validate runs the checks every config gets. It does not apply the rule of the next section: a path on the host
is accepted in a file and refused in a ConduitSite.
More examples
An API that needs a JWT (the keys are fetched from the JWKS URL; nothing secret is in the object):
apiVersion: conduit.lopatnov.github.io/v1
kind: ConduitSite
metadata:
name: my-api
namespace: default
spec:
port: 8081
host: api.example.com
jwtAuth:
jwksUrl: https://auth.example.com/.well-known/jwks.json
proxy:
/v1: http://api-svc:4000
healthCheck: true
Two upstreams with the least busy one chosen, passive ejection of a failing one, and the upstream’s 5xx bodies hidden:
apiVersion: conduit.lopatnov.github.io/v1
kind: ConduitSite
metadata:
name: orders
namespace: default
spec:
port: 8082
host: orders.example.com
proxy:
/:
targets: [http://orders-a:4000, http://orders-b:4000]
strategy: least-conn
outlierDetection: { consecutive5xx: 5, baseEjectionTimeSecs: 30 }
maskErrors: true
A raw TCP site (a database, needs the tcp feature of the full image). It has no host, as TCP has no Host header:
apiVersion: conduit.lopatnov.github.io/v1
kind: ConduitSite
metadata:
name: postgres
namespace: default
spec:
port: 5432
tcp:
targets: ["postgres.default.svc:5432"]
What a ConduitSite may contain
Every field of a site of the configuration reference: proxy and routes, tls, jwtAuth,
consumers, forwardAuth, rateLimit, ipFilter, limits, securityHeaders, cors, compression, redirects,
headers, fallback, tcp and the rest. A key that is not a site field is reported in the log as a warning and has no
effect, as in a config file; check the spelling of a field that seems to do nothing.
Three differences from a file:
- No host paths. A spec that sets one is refused:
static,upload,middleware,tls.cert,tls.key,tls.ca,tls.clientAuth,tls.acme.storage,logging.file,fallback.file,fallback.byAccept.*.fileand acache.storeof the formdisk:<path>, also insideroutes. Serve static content from an upstream, get certificates fromtls.acme, and use a file config for the rest.tls.acmekeeps its certificates in./certsof the working directory, which is/certsin the image: mount a writable volume there, because the root filesystem of the example above is read-only. - No
$VARexpansion. A config file expands$VARand${VAR}from the environment; aConduitSiteis taken as written, so$PASSWORDis the literal text$PASSWORD. Whatever a spec holds is readable by anyone who maygetthe object, so do not put a secret in one that those people should not see. Credentials are plain text in the spec wherever the config has one:basicAuthandapiKey,jwtAuth.secret, the keys, passwords and secrets ofconsumers,proxy.*.sticky.secretandmetrics.token. PreferjwtAuthwith a public JWKS URL orforwardAuth. - No
global. Workers, the Admin API and the shutdown period belong to the pod, not to a site. Conduit supplies a config whose Admin API is on loopback with a token (see Install).
What happens on every change
Any ConduitSite that is added, changed or deleted makes Conduit list all objects in the namespace again and build the
whole config from them. The result is checked like a config file and swapped in only if it passes.
| Step | Failure | Result |
|---|---|---|
| Read the spec of each site | the spec is refused (a host path, a field of the wrong type) or the site alone has a hard validation error | ConduitSite <name> is invalid in the log and in its status; only that site is affected (see below) |
| Validate the whole config | a hard error between sites: two sites with one host and port, … |
config error at <path>: <message> and live config update rejected: the previous config stays |
| Compare with the running one | a change the running listeners cannot follow (see below) | cold field changed — restart required and live config update rejected |
| Swap | none | the new config is in use, without a restart |
An invalid ConduitSite does not hold back the others. If it worked before, the last good version of that site stays
in the config (keeping the last version that was valid in the log), so a bad edit does not take a working site down. If
it never worked, for example a new object, it is not active (not active in the log). Its host is not passed on to
another site: where other sites listen on the same port, requests for that host get a 503, so that they do not reach
the upstream of someone else. A site without a host is answered the same way, as a catch-all. (Alone on its port there is
nothing to answer with: the connection is refused. No answer is added either where it would clash with another site: a
tcp site on the port, or another site with the same host.) The same holds at start: the pod starts with the sites that are valid. What no single site can show is checked on the whole config, and there the whole previous
config stays: two sites with the same host and port are refused as a whole, and so is a change in the table’s third
row. Warnings, such as a certificate close to expiry, are logged and do not stop an update. At start, a failure of the
whole config (or of the API call) stops the process, because there is no previous config to keep.
What does not apply live
These need a new pod, for example kubectl rollout restart deployment/conduit:
- A new or a removed port. The listeners are bound at start. Adding a site on a port no site uses, or deleting the
last site of a port, is rejected as
listeners[<port>].port. Another site on a port that is already bound is live. tls.certandtls.keyof a port (aConduitSitecannot set them anyway) and every field oftls.acme(email,directory,challenge,profile).global.workers,global.shutdownTimeoutSecsand the Admin API bind: not settable from aConduitSite.
Everything else is live: proxy targets, routes, auth, rate limits, headers, redirects, limits, and so on. A runtime
change made through the Admin API (conduit upstreams add, a dynamic ip-deny) is kept in memory only and is
replaced by the next update.
Who may write ConduitSite objects
A ConduitSite decides which requests Conduit accepts and where it sends them, so write access to the object is
access to that traffic. The host-path rule above stops a writer from reading, writing or serving files of the Conduit
pod. It does not limit where the site sends traffic: a writer can route a host and port to any address the pod can
reach, including services of other namespaces, and tcp opens a raw TCP port to any host:port, with none of the
checks of an HTTP site. A writer cannot name a Redis address: cache.store and rateLimit.store may say redis, and the address is the operator’s (CONDUIT_REDIS_URL, below), so the counters and cached responses of all sites go to the one Redis the operator chose; a redis:// address in a ConduitSite is refused like a host path.
Loopback is covered: the Admin API, which could otherwise be reached through a site that proxies to 127.0.0.1:2019,
has a token that a writer does not know. In practice:
- Give
createandupdateonconduitsitesonly to the people who may configure that traffic, with aRolein the namespace you watch. Watching'*'makes every namespace’s writers able to change the one shared config. - Two sites with the same
hostandportare a validation error for the whole config (the table above): in'*'mode a mistake, or a deliberate collision, in one namespace holds back the updates of all the others. If tenants are not to be able to affect each other, run one Conduit per namespace, and note that this separates their updates and not the traffic they can send from the pod. - A site that uses
tls.acmemust have ahostthat is a plain DNS name; it becomes a file name in./certs.
Troubleshooting
| You see | Why |
|---|---|
The pod exits at start with kubernetes provider error: ... |
The API call failed: no RBAC for list/watch conduitsites (the apiGroups of the Role must be conduit.lopatnov.github.io), the CRD is not installed, or the wrong namespace |
ConduitSite <name> is invalid in the log |
That site is not active (its host answers 503), or is kept at the last version that was valid; the message names the cause, for example host file paths cannot be set from a ConduitSite (the message lists them: remove them, or use a file config) |
kubectl apply works, the site never changes |
Look for ConduitSite <name> is invalid and live config update rejected in kubectl logs: this site is invalid, or two sites collide |
| A field of the spec has no effect | unknown key warning in the log: the field name is misspelled (field names are camelCase, as in a config file) |
cold field changed — restart required |
See what does not apply live |
READY is false, or empty |
false: the spec is invalid, and kubectl get conduitsites -o jsonpath='{.status.message}' says why and whether the last valid version still serves. Empty: Conduit may not write the status (see the RBAC above); the log says so once |
ConduitSite watch error in the log |
The watch on the API server failed; the current config stays active, retries use exponential backoff, and reconnection triggers a namespace relist |
Upgrading from a release that used the group conduit.io. The API group is conduit.lopatnov.github.io since this
version (conduit.io is a domain the project does not own). Objects of the old group are not read. Keep the manifests you
applied: they are what you apply again. If you have only the objects in the cluster, export them, and remove what the API
server sets before you apply them under the new group (it refuses an object that carries a resourceVersion):
kubectl get conduitsites.conduit.io -A -o yaml \
| yq 'del(.items[].metadata.resourceVersion, .items[].metadata.uid, .items[].metadata.creationTimestamp,
.items[].metadata.generation, .items[].metadata.managedFields, .items[].status)
| .items[].apiVersion = "conduit.lopatnov.github.io/v1"' > conduitsites-new.yaml
Then delete the old CRD (kubectl delete crd conduitsites.conduit.io, which deletes its objects), apply the new CRD, change
apiGroups in the RBAC Role, and apply the manifests.
The effective config is not printed. To see what Conduit built, look at the log lines above and at the objects
(kubectl get conduitsites -o yaml): the config is exactly the list of their specs, in the order the API returns them.