ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

在K8s集群中部署Traefik并验证Python HTTP服务:TaoToken统一Key接入Ingress路由配置实战

在K8s集群中部署Traefik并验证Python HTTP服务:TaoToken统一Key接入Ingress路由配置实战 1. 为什么要在 K8s 里折腾 Traefik 和 Python HTTP 服务如果你正在学 Kubernetes大概率会遇到这样一个尴尬场景Pod 跑起来了Service 也建好了但集群外的人根本访问不到。这时候你需要一个 Ingress Controller 来当门卫而 Traefik 就是那个配置直观、自带 Dashboard、对新手相对友好的选择。它能把外部请求按域名和路径转发到集群内的 Service还能自动感知 Pod 变化不用你手动改配置。这篇要做的是一条完整链路在 K8s 集群里部署 Traefik 作为 Ingress Controller再跑一个 Python HTTP 服务最后通过 Ingress 路由把请求打进去用 curl 验证整条路真的通了。适合已经会kubectl get pods、知道 Deployment 和 Service 是什么、但还没亲手配过 Ingress 的同学。热词里提到的 HAProxy 传统方案我也会拿来对比——它做四层负载均衡很稳但七层路由和动态服务发现这块Traefik 在 K8s 场景下省心不少。过程中我会用 TaoToken 的统一 Key 通道来辅助生成和校对 YAML 配置这样你不用在多个 AI 工具之间来回切一个 Key 就能把配置骨架、排错思路一起搞定。下面从环境准备开始一步步来。2. TaoToken 前置准备统一 Key 接入 AI 辅助配置在动手写 YAML 之前先把 AI 辅助这条线搭好。TaoToken 的作用是提供一个统一的 API 通道你拿一个 Key 就能调用多种模型来帮你生成 Traefik 的 IngressRoute、检查 Python 服务代码、甚至解释报错。对于这种配置密集型任务有个能随时问的助手会快很多。第一步是拿到 API Key。打开官网 https://taotoken.net/?utm_sourcetaotoken_aicg_blog_endutm_mediumcsdnutm_campaignrewriteutm_content 注册后在控制台里创建 Key。控制台地址是 https://taotoken.net/console?utm_sourcetaotoken_aicg_blog_endutm_contentconsoleutm_campaignrewrite 进去之后左侧菜单能找到 API Keys 入口https://taotoken.net/api-keys?utm_sourcetaotoken_aicg_blog_endutm_contentapi-keysutm_campaignrewrite 。创建完记得复制保存页面刷新后就看不到了。拿到 Key 之后API 的基础地址是 https://taotoken.net/api 注意这个地址不带 UTM 参数直接填就行。如果你用的是 OpenAI 兼容的客户端把 base_url 指向它Key 填进去就能用。想先试试模型通不通可以去模型对话页面 https://taotoken.net/model-chat?utm_sourcetaotoken_aicg_blog_endutm_contentmodel-chatutm_campaignrewrite 发一句话验证。注意Key 属于敏感凭证不要写进 YAML 提交到 Git也不要在文章或截图里暴露完整字符串。建议用环境变量或者 K8s Secret 管理。如果你打算长期用 AI 辅助写 K8s 配置和代码可以看看 Coding Planhttps://taotoken.net/coding-plan?utm_sourcetaotoken_aicg_blog_endutm_contentcoding-planutm_campaignrewrite 它更适合高频的编码和 Agent 场景。接入文档在 https://taotoken.net/doc?utm_sourcetaotoken_aicg_blog_endutm_contentdocutm_campaignrewrite 遇到参数问题可以查。3. 可复制配置Traefik 部署与 Python 服务骨架3.1 集群与节点准备假设你有一个 3 节点的集群节点名分别是 ubuntu-111、ubuntu-112、ubuntu-113。我们让 Traefik 只跑在前两个节点上用节点标签来控制调度。先给节点打标签kubectl label nodes ubuntu-111 traefik-worktrue kubectl label nodes ubuntu-112 traefik-worktrue kubectl get nodes ubuntu-111 ubuntu-112 --show-labels | grep traefik-work预期输出里能看到两个节点都带上了traefik-worktrue。这一步的意义是后面用 nodeAffinity 把 Traefik 钉在这两个节点避免它跑到 ubuntu-113 上。3.2 Traefik 的 values.yaml用 Helm 装 Traefik 最省事。先加仓库helm repo add traefik https://traefik.github.io/charts helm repo update然后写一个traefik-values.yaml核心是节点亲和性、Pod 反亲和性、hostNetwork 和端口绑定affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: traefik-work operator: In values: - true podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchLabels: app.kubernetes.io/name: traefik topologyKey: kubernetes.io/hostname hostNetwork: true deployment: replicas: 2 pod: securityContext: capabilities: add: - NET_BIND_SERVICE runAsUser: 0 ports: web: port: 80 hostPort: 80 websecure: port: 443 hostPort: 443这里几个点值得说清楚。nodeAffinity保证 Traefik 只落在打了标签的节点podAntiAffinity用topologyKey: kubernetes.io/hostname保证同一个节点上不会跑两个 Traefik 副本hostNetwork: true让 Pod 直接用节点网络配合hostPort把 80/443 绑到节点上。NET_BIND_SERVICE能力是为了允许绑定 1024 以下的端口。安装命令helm install traefik traefik/traefik \ --namespace kube-system \ --create-namespace \ --version 39.1.0-ea.2 \ -f traefik-values.yaml装完检查调度结果kubectl get pods -n kube-system -l app.kubernetes.io/nametraefik -o wide你应该看到两个 Pod分别落在 ubuntu-111 和 ubuntu-112 上。3.3 Python HTTP 服务代码写一个最简单的 HTTP 服务返回 Pod 名和节点名方便验证路由到底打到了哪个副本from http.server import BaseHTTPRequestHandler, HTTPServer import os, socket, json class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(Content-type, text/html; charsetutf-8) self.end_headers() pod_name os.getenv(POD_NAME, socket.gethostname()) node_name os.getenv(NODE_NAME, unknown-node) app_info { app: python-http-server, container: os.getenv(CONTAINER_NAME, python-http-server) } response f h1Python HTTP Server/h1 pPod: {pod_name}/p pNode: {node_name}/p pApp Info: {json.dumps(app_info, indent2)}/p self.wfile.write(response.encode(utf-8)) def run(port8080): server_address (0.0.0.0, port) httpd HTTPServer(server_address, Handler) print(fPython HTTP 服务启动: 0.0.0.0:{port}) try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close() if __name__ __main__: run()打成镜像推到你的私有仓库比如192.168.56.102/library/python-http-server:v1。3.4 Deployment、Service 与 IngressRouteTraefik 3.x 推荐用 IngressRoute 这种 CRD比原生 Ingress 表达力更强。先建 Deployment 和 ServiceapiVersion: apps/v1 kind: Deployment metadata: name: python-http-server namespace: default spec: replicas: 2 selector: matchLabels: app: python-http-server template: metadata: labels: app: python-http-server spec: containers: - name: python-http-server image: 192.168.56.102/library/python-http-server:v1 ports: - containerPort: 8080 name: http env: - name: NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: CONTAINER_NAME value: python-http-server --- apiVersion: v1 kind: Service metadata: name: python-http-server namespace: default spec: selector: app: python-http-server ports: - port: 80 targetPort: 8080 protocol: TCP name: http type: ClusterIP然后是 IngressRoute这是 Traefik 自己的 CRDapiVersion: traefik.io/v1alpha1 kind: IngressRoute metadata: name: python-http-ingressroute namespace: default spec: entryPoints: - web routes: - match: Host(python-http.example.com) kind: Rule services: - name: python-http-server port: 80entryPoints: web对应 Traefik 的 80 端口入口match用 Host 规则匹配域名services指向刚才的 Service。应用这些资源kubectl apply -f python-http-deploy.yaml kubectl apply -f python-http-ingressroute.yaml kubectl get pods -l apppython-http-server kubectl get ingressroute4. 验证请求curl 打通整条路由配置都上了现在验证。先确认 Traefik 的 Pod 状态kubectl get pods -n kube-system -l app.kubernetes.io/nametraefik -o wide两个 Pod 都 Running且分布在 ubuntu-111 和 ubuntu-112。接着在本地配 hosts把域名指到 Traefik 所在节点假设你通过其中一个节点访问echo 192.168.56.111 python-http.example.com | sudo tee -a /etc/hosts然后 curlcurl http://python-http.example.com预期输出是一段 HTML里面能看到Pod:和Node:字段。多请求几次你会发现 Pod 名在变说明 Service 在做负载均衡for i in $(seq 1 6); do curl -s http://python-http.example.com | grep -o Pod: [^]*; done如果 Traefik 前面还挂了 HAProxy 做四层代理HAProxy 的配置里可以加 TCP 健康检查探测 Traefik 的/ping接口backend traefik-http-backend mode tcp balance roundrobin option tcp-check tcp-check connect port 80 tcp-check send GET /ping HTTP/1.1\r\nHost: localhost\r\n\r\n tcp-check expect string 200 OK server traefik-node-111 192.168.56.111:80 check inter 2000 fall 3 rise 2 server traefik-node-112 192.168.56.112:80 check inter 2000 fall 3 rise 2这样 HAProxy 负责四层转发和节点级健康检查Traefik 负责七层路由分工明确。想看 HAProxy 后端状态echo show stat | socat /run/haproxy/admin.sock stdio | grep traefikSTATUS 列显示 UP 就说明健康检查通过。5. 本篇常见错排查5.1 IngressRoute 不生效curl 返回 404最常见的原因是 entryPoints 名字对不上。Traefik 默认的入口点叫web和websecure如果你在 values.yaml 里改过名字IngressRoute 里也要跟着改。用kubectl get ingressroute -o yaml检查 match 规则再确认 Traefik 的 Dashboard 或日志里有没有加载到这条路由kubectl logs -n kube-system -l app.kubernetes.io/nametraefik --tail505.2 Pod 一直 Pending调度不上去多半是 nodeAffinity 的标签没打对或者 values 里values: - true写成了布尔值true。K8s 的标签值必须是字符串写成true不带引号在某些解析器里会报错。用kubectl describe pod看 Events会明确告诉你哪个节点不满足亲和性。5.3 hostNetwork 下端口冲突如果节点上已经有服务占了 80 或 443Traefik 的 Pod 会起不来报address already in use。检查节点端口占用sudo ss -tlnp | grep -E :80|:443要么停掉冲突服务要么改用 NodePort 模式把 hostPort 去掉让 Service 用 30000 以上的端口暴露。5.4 Python 服务返回 502Traefik 能路由到 Service但连不上后端 Pod。先确认 Service 的 targetPort 和容器 containerPort 一致都是 8080。再进 Pod 里自测kubectl exec -it pod-name -- curl localhost:8080如果 Pod 内能通、外面不通问题在 Service selector 或 IngressRoute 的 service port 上。Service 的 port 是 80IngressRoute 里写的也应该是 80不是 8080。5.5 用 AI 辅助排错遇到报错信息看不懂可以把日志贴到模型对话里让它解释https://taotoken.net/model-chat?utm_sourcetaotoken_aicg_blog_endutm_contentmodel-chatutm_campaignrewrite 。比如 Traefik 的no available server或者 HAProxy 的503 Service Unavailable让模型帮你定位是健康检查失败还是后端没注册。长期做 K8s 运维和配置生成的话Coding Plan 会更顺手https://taotoken.net/coding-plan?utm_sourcetaotoken_aicg_blog_endutm_contentcoding-planutm_campaignrewrite 。6. 继续接入把 AI 通道用起来整条链路跑通之后你会发现 Traefik 的配置其实不复杂难的是排错和版本差异。Traefik 2.x 和 3.x 的 CRD apiVersion 就不一样2.x 是traefik.containo.us/v1alpha13.x 变成了traefik.io/v1alpha1写错就是 404。这种细节用 AI 辅助核对能省不少时间。如果你还没拿 Key从 API Keys 页面创建https://taotoken.net/api-keys?utm_sourcetaotoken_aicg_blog_endutm_contentapi-keysutm_campaignrewrite 。接入方式参考文档https://taotoken.net/doc?utm_sourcetaotoken_aicg_blog_endutm_contentdocutm_campaignrewrite 。API 地址统一用 https://taotoken.net/api 一个 Key 走通模型对话、配置生成和排错。最后留一个实操建议把 Traefik 的 Dashboard 通过 IngressRoute 暴露出来用Host加PathPrefix限制访问这样你能直观看到路由规则有没有加载、后端服务健康不健康。Dashboard 默认在 Traefik Pod 的 8080 端口加一条 IngressRoute 指向它就行。配好之后每次改完 YAML 刷新一下 Dashboard比翻日志快得多。
返回列表