From e667b6ec69bb18c8907a06847f859f761e4e66bb Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 19:42:48 +0000 Subject: [PATCH] docs(examples): add a standalone Kubernetes deployment (#13) examples/standalone is a kustomization for the compiled gateway with restart draining, a configMapGenerator config, placeholder Secrets and an optional Traefik route. TestHandleChat_RequestLimitExceeded_BodyNeverRead now pins the limiter clock and uses an unreachable local upstream, so it no longer flakes at a minute boundary or calls api.openai.com. --- README.md | 7 ++ examples/standalone/config.yaml | 26 +++++ examples/standalone/deployment.yaml | 125 +++++++++++++++++++++++++ examples/standalone/kustomization.yaml | 22 +++++ examples/standalone/namespace.yaml | 4 + examples/standalone/secrets.yaml | 25 +++++ examples/standalone/traefik.yaml | 29 ++++++ routes_unified_test.go | 6 +- 8 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 examples/standalone/config.yaml create mode 100644 examples/standalone/deployment.yaml create mode 100644 examples/standalone/kustomization.yaml create mode 100644 examples/standalone/namespace.yaml create mode 100644 examples/standalone/secrets.yaml create mode 100644 examples/standalone/traefik.yaml diff --git a/README.md b/README.md index db01973..de03d27 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,13 @@ cosign verify ghcr.io/lukaszraczylo/traefik-llmgateway: \ --certificate-oidc-issuer https://token.actions.githubusercontent.com ``` +For Kubernetes, [`examples/standalone/`](examples/standalone/) is a complete +kustomization: a 3-replica Deployment with restart draining, a Service, a +PodDisruptionBudget, the config as a `configMapGenerator` (an edit rolls +the pods), placeholder Secrets for provider keys and users, and an optional +Traefik IngressRoute with a long response timeout. Apply it with +`kubectl apply -k examples/standalone`. + To build from source: ```sh diff --git a/examples/standalone/config.yaml b/examples/standalone/config.yaml new file mode 100644 index 0000000..4b25d7e --- /dev/null +++ b/examples/standalone/config.yaml @@ -0,0 +1,26 @@ +# Gateway configuration (README "Configuration reference"). Unknown keys +# stop the binary from starting, so a typo fails loudly. +providers: + openai: + type: openai + # Read from the environment of the gateway container (deployment.yaml, + # Secret llmgateway-provider-keys). file:/path works too. + apiKey: env:OPENAI_API_KEY + discovery: true +groups: + engineering: + providers: [] + general: + providers: [openai] +users: + # Mounted from Secret llmgateway-users; edits are picked up without a restart. + file: /llmgw/users/users.json +metrics: + # No allowedCIDRs: behind a proxy every request arrives from the proxy's + # address, so a CIDR allowlist would admit anyone who can reach it. + # Scrape /metrics with an admin key instead. + enabled: true +# Uncomment to share limits, breakers and metrics across the replicas. +# redis: +# address: redis.example.svc:6379 +# sharedState: true diff --git a/examples/standalone/deployment.yaml b/examples/standalone/deployment.yaml new file mode 100644 index 0000000..a022b8f --- /dev/null +++ b/examples/standalone/deployment.yaml @@ -0,0 +1,125 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: llmgateway + labels: + app.kubernetes.io/name: llmgateway +spec: + replicas: 3 + strategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 0 + maxSurge: 1 + selector: + matchLabels: + app.kubernetes.io/name: llmgateway + template: + metadata: + labels: + app.kubernetes.io/name: llmgateway + spec: + # Restart drain: on SIGTERM /readyz fails at once, requests that still + # arrive during LLMGW_DRAIN_DELAY are served, then the listener closes + # and in-flight requests (streams included) run to completion for up + # to LLMGW_SHUTDOWN_TIMEOUT. Keep the grace period above drain plus + # shutdown, and the shutdown timeout above your longest generation. + terminationGracePeriodSeconds: 1230 + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + seccompProfile: + type: RuntimeDefault + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: llmgateway + containers: + - name: llmgateway + # Pin a release, ideally by digest: @sha256:. + image: ghcr.io/lukaszraczylo/traefik-llmgateway:1.0.169 + args: ["-config", "/etc/llmgateway/config.yaml", "-listen", ":8080"] + env: + - name: LLMGW_DRAIN_DELAY + value: "10s" + - name: LLMGW_SHUTDOWN_TIMEOUT + value: "20m" + envFrom: + - secretRef: + name: llmgateway-provider-keys + ports: + - name: http + containerPort: 8080 + # The listener opens after provider discovery, which can take a + # while with many providers. + startupProbe: + httpGet: + path: /healthz + port: http + periodSeconds: 5 + failureThreshold: 60 + livenessProbe: + httpGet: + path: /healthz + port: http + periodSeconds: 10 + readinessProbe: + httpGet: + path: /readyz + port: http + periodSeconds: 5 + failureThreshold: 2 + resources: + requests: + cpu: 100m + memory: 128Mi + limits: + memory: 1Gi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + volumeMounts: + - name: config + mountPath: /etc/llmgateway + readOnly: true + - name: users + mountPath: /llmgw/users + readOnly: true + volumes: + - name: config + configMap: + name: llmgateway-config + - name: users + secret: + secretName: llmgateway-users +--- +apiVersion: v1 +kind: Service +metadata: + name: llmgateway + labels: + app.kubernetes.io/name: llmgateway +spec: + selector: + app.kubernetes.io/name: llmgateway + ports: + - name: http + port: 8080 + targetPort: http +--- +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: llmgateway +spec: + minAvailable: 1 + selector: + matchLabels: + app.kubernetes.io/name: llmgateway diff --git a/examples/standalone/kustomization.yaml b/examples/standalone/kustomization.yaml new file mode 100644 index 0000000..78b22ca --- /dev/null +++ b/examples/standalone/kustomization.yaml @@ -0,0 +1,22 @@ +# Standalone LLM Gateway on Kubernetes: the compiled binary (cmd/gateway) +# as its own Deployment, behind any reverse proxy. Apply with: +# +# kubectl apply -k examples/standalone +# +# config.yaml holds the gateway configuration: the same block a plugin +# Middleware carries under spec.plugin.llmgateway, hoisted to the top +# level. configMapGenerator gives the ConfigMap a content hash, so editing +# config.yaml rolls the pods. The binary also hot-reloads the file in place +# (-reload-interval), and users.json is reloaded by the gateway itself. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: llmgateway +resources: + - namespace.yaml + - secrets.yaml + - deployment.yaml + - traefik.yaml +configMapGenerator: + - name: llmgateway-config + files: + - config.yaml diff --git a/examples/standalone/namespace.yaml b/examples/standalone/namespace.yaml new file mode 100644 index 0000000..7dbcf75 --- /dev/null +++ b/examples/standalone/namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: llmgateway diff --git a/examples/standalone/secrets.yaml b/examples/standalone/secrets.yaml new file mode 100644 index 0000000..ca977d0 --- /dev/null +++ b/examples/standalone/secrets.yaml @@ -0,0 +1,25 @@ +# Placeholders only. In a real cluster create these from your secret store +# (External Secrets, sealed secrets, sops) and delete this file from the +# kustomization. +apiVersion: v1 +kind: Secret +metadata: + name: llmgateway-provider-keys +type: Opaque +stringData: + OPENAI_API_KEY: sk-CHANGE-ME +--- +apiVersion: v1 +kind: Secret +metadata: + name: llmgateway-users +type: Opaque +stringData: + # Shape: {"users":[{"name","group","apiKey","admin","limits"}]}. + users.json: | + { + "users": [ + {"name": "admin", "group": "engineering", "admin": true, "apiKey": "sk-llmgw-admin-CHANGE-ME"}, + {"name": "alice", "group": "general", "apiKey": "sk-llmgw-alice-CHANGE-ME"} + ] + } diff --git a/examples/standalone/traefik.yaml b/examples/standalone/traefik.yaml new file mode 100644 index 0000000..e4e8dcd --- /dev/null +++ b/examples/standalone/traefik.yaml @@ -0,0 +1,29 @@ +# Optional: Traefik in front. Any reverse proxy works; keep its response +# timeout above your longest non-streaming generation. Remove this file +# from the kustomization if you use another ingress. +apiVersion: traefik.io/v1alpha1 +kind: ServersTransport +metadata: + name: llmgateway +spec: + forwardingTimeouts: + dialTimeout: 30s + # Set explicitly: a short global responseHeaderTimeout (for example 30s) + # would cut off slow generations, which can take minutes. + responseHeaderTimeout: 20m +--- +apiVersion: traefik.io/v1alpha1 +kind: IngressRoute +metadata: + name: llmgateway +spec: + entryPoints: + - websecure + routes: + - match: Host(`llm.example.com`) + kind: Rule + services: + - name: llmgateway + port: 8080 + serversTransport: llmgateway + tls: {} diff --git a/routes_unified_test.go b/routes_unified_test.go index 3a311ff..2b0dfae 100644 --- a/routes_unified_test.go +++ b/routes_unified_test.go @@ -2498,7 +2498,8 @@ func (b *readTrackingBody) Close() error { return nil } func TestHandleChat_RequestLimitExceeded_BodyNeverRead(t *testing.T) { cfg := CreateConfig() cfg.Providers = map[string]*ProviderConfig{ - "openai": {Type: "openai", APIKey: "k", Models: []string{"gpt-test"}}, + // An unreachable local upstream: the first request must not leave the test process. + "openai": {Type: "openai", APIKey: "k", BaseURL: "http://127.0.0.1:1", Models: []string{"gpt-test"}}, } cfg.Groups = map[string]*GroupConfig{"default": {}} cfg.Users = &UsersConfig{Inline: []*UserConfig{ @@ -2509,6 +2510,9 @@ func TestHandleChat_RequestLimitExceeded_BodyNeverRead(t *testing.T) { if err != nil { t.Fatalf("New: %v", err) } + // Both requests must share one minute window; at a minute boundary the second one got a fresh budget. + fixed := time.Date(2026, 1, 1, 12, 0, 30, 0, time.UTC) + h.(*Gateway).limiter.nowFn = func() time.Time { return fixed } // First request consumes the one-per-minute budget; its body is a // real, valid body so the request completes normally end to end