Files
Deploy-Laboratory/docs/04-02-nodejs-端口与Service.md
2026-03-29 09:08:01 +08:00

84 lines
3.5 KiB
Markdown
Raw Permalink 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-02-nodejs-端口与Service
> 理清 **容器监听端口**、**Service 端口** 与 **Ingress backend 端口** 三者对应关系;在 `04-01` 基线上做最小调整。
## TL;DR
- **手动练习**:复制本课目录 `ansible/files/04-02/` 下清单到目标路径,按需改字段后按本文 `kubectl`/bash 操作(学习路径可不使用 verify
- **自动化验收**`./ansible/bin/verify.sh run 04-02`
- **关键前置**:按本文「前置条件」准备环境变量/Secret/入口 IP
- **成功判据**:达到本文「预期」且 playbook 断言通过
- **排障**:见本文「排障」
## 前置条件
- 已部署 `nodejs-demo``04-01`)。
## 清单路径(本课分目录)
| 项 | 路径 |
|----|------|
| 本篇完整清单(累积至 04-02 | [`ansible/files/04-02/04-02-nodejs-demo.yaml`](../ansible/files/04-02/04-02-nodejs-demo.yaml) |
| 应用 | `kubectl apply -f ansible/files/04-02/04-02-nodejs-demo.yaml` |
**本篇04-02** 起,累积清单中应用监听 **8080**(与 `04-01` 文档中的 3000 不同,便于与后续探针、分项对齐)。
## 场景说明(白话)
可以把流量想成「访客 → Ingress → Service → 容器端口」:
| 位置 | 字段 | 04-01 里大概是啥 |
|------|------|------------------|
| 容器 | `containerPort` | 应用**实际监听**的端口,例:`3000` |
| Service | `port` / `targetPort` | 集群内访问 Service 的 **`port`**,转发到 Pod 的 **`targetPort`** |
| Ingress | `backend.service.port.number` | 填 Service 的 **`port`**(数字),**不是** `targetPort` 这个名字 |
**改应用监听端口时**:容器监听、`containerPort``targetPort` 要一致Ingress 只要还指向 Service 的 `port: 80`,通常不用动。
### 相对 `04-01` 的变更(原文 → 新文)
| 位置 | 原文(`04-01` | 新文(`04-02` |
|------|-----------------|-----------------|
| 容器内监听 | `.listen(3000)` | `.listen(8080)` |
| `containerPort` | `3000` | `8080` |
| Service `targetPort` | `3000` | `8080` |
| Ingress `backend.service.port.number` | `80` | `80`(不变,仍指 Service 的 `port` |
## 多端口(示意)
**YAML 怎么接**:仍在 **`nodejs-demo.yaml`** 里改——容器多写几个 `containerPort`Service 多写几条 `port`/`targetPort`Ingress 一般只指向**对外那一个** Service 端口即可。
若同一 Pod 既要对外 HTTP又要对内调试端口就属于这种「多端口」场景。
## 部署与验证
```bash
kubectl apply -f ansible/files/04-02/04-02-nodejs-demo.yaml
kubectl get svc nodejs-demo -n default -o wide
kubectl get endpoints nodejs-demo -n default
curl -s --max-time 3 http://<节点IP>/node/
```
预期:`endpoints` 有 Pod IP:targetPortcurl 正常。
## NodePort可选
`Service``type: NodePort` 可在节点上暴露高位端口调试;生产通常仍走 Ingress。K3s ServiceLB 行为见工作节点文档。
## 失败排查
- **502 / 无 endpoints**`targetPort` 与进程监听不一致selector 与 Pod 标签不一致。
- `06-01-k3s-networkpolicy-故障排查.md`
## 相关文档
- [`04-07-nodejs-Ingress与Traefik.md`](04-07-nodejs-Ingress与Traefik.md)
- [`04-01-k3s-nodejs-高级部署.md`](04-01-k3s-nodejs-高级部署.md)
## 排障
- **先看 playbook 输出**:失败时先定位是 deploy/wait/http_check 哪一步。
- **集群侧总览**`kubectl get nodes -o wide``kubectl -n kube-system get pods -o wide`
- **事件与日志**`kubectl -n <ns> describe ...``kubectl -n <ns> logs ... --tail=200`