Files
Deploy-Laboratory/docs/04-10-nodejs-Ingress与Traefik.md
2026-03-21 04:36:06 +08:00

72 lines
3.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 04-10-nodejs-Ingress与Traefik
> 在 K3s 默认 **Traefik** 下,为 `nodejs-demo` 调整 **路径、主机名、入口点**;并了解标准 `Ingress` 与 **IngressRoute**CRD的差异入口。
## 前置条件
- 已部署 `04-01` 中的 `Ingress`;可选:`03-01-k3s-traefik-dashboard.md` 观察路由。
## 清单路径(唯一真源)
| 本篇完整清单(含 Ingress `host` + `/api` | [`ansible/files/nodejs-demo/04-10-nodejs-demo.yaml`](../ansible/files/nodejs-demo/04-10-nodejs-demo.yaml) |
| 应用 | `kubectl apply -f ansible/files/nodejs-demo/04-10-nodejs-demo.yaml` |
`host` / `path` 可按环境修改清单;`curl` 用 IP 访问时需带 **`Host`** 头。
## 场景说明(白话)
- **Ingress**:告诉 Traefik「哪个域名、哪条 URL 转到哪个 Service」。
- **`router.entrypoints: web`**:走集群里 Traefik 的 **HTTP 入口**(名字一般是 `web`)。
- **和 HTTPS 的关系**:要上证书、走 443通常改用 **`websecure`**,见 [`04-12-nodejs-TLS与证书.md`](04-12-nodejs-TLS与证书.md)。
## 04-01 对照
- 注解 `traefik.ingress.kubernetes.io/router.entrypoints: web` 将路由绑定到 **HTTP** 入口(常见名 `web`)。
- HTTPS 入口通常为 **`websecure`**,与 TLS 配合见 `04-12`
### 相对 `04-09` 的变更(原文 → 新文)
| 位置 | 原文(`04-09` | 新文(`04-10` |
|------|-----------------|-----------------|
| Ingress `spec.rules` | 仅 `http.paths`,无 `host`path `/node` | `host: app.example.local`path **`/api`** |
**注意**:这与 `04-01` **只有 path、没有 host** 的写法不同;用 IP 访问必须带 **`Host: app.example.local`**。
## pathType 说明
- `Prefix`:前缀匹配(常用)。
- `ImplementationSpecific`由控制器解释Traefik 有特定行为时需查官方文档。
## IngressRouteCRD
Traefik 原生 CRD 可做中间件、多规则组合等;集群需已安装对应 CRD。与标准 `Ingress` 二选一或并存时注意不要 **重复暴露同一路径** 导致冲突。
## 部署与验证
```bash
kubectl apply -f ansible/files/nodejs-demo/04-10-nodejs-demo.yaml
kubectl describe ing nodejs-demo -n default
# --- 情况 A仍是 04-01 的 Ingress无 rules.hostpath=/node---
# 用节点 IP 直接访问即可,一般不需要 Host 头:
curl -s -o /dev/null -w "%{http_code}\n" --max-time 3 http://<节点IP>/node/
# --- 情况 B已换成上文示例有 host=app.example.localpath=/api---
# 用 IP 访问时必须带 Host且路径改为 /api与 path 一致):
curl -s -o /dev/null -w "%{http_code}\n" --max-time 3 \
-H "Host: app.example.local" \
"http://<节点IP>/api/"
```
## 失败排查
- **404**:路径/host 与规则不一致Traefik 未加载该 Ingressnamespace、ingressClass
- **502**Service 无 Endpoints`04-04``04-06`)。
- `06-01-k3s-networkpolicy-故障排查.md`
- 集群级 Traefik`03-01``03-02`
## 相关文档
- [`04-12-nodejs-TLS与证书.md`](04-12-nodejs-TLS与证书.md)
- [`04-04-nodejs-端口与Service.md`](04-04-nodejs-端口与Service.md)