Files
Deploy-Laboratory/docs/04-03-nodejs-镜像与运行命令.md
2026-03-27 16:58:41 +08:00

82 lines
3.5 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-03-nodejs-镜像与运行命令
> 在 [`04-01-k3s-nodejs-高级部署.md`](04-01-k3s-nodejs-高级部署.md) 的 `nodejs-demo` 基线上,调整**镜像**与**进程启动方式**。
## TL;DR
- **自动化验收**`./scripts/verify.sh run 04-03`
- **关键前置**:按本文「前置条件」准备环境变量/Secret/入口 IP
- **成功判据**:达到本文「预期」且 playbook 断言通过
- **排障**:见本文「排障」
## 前置条件
- 已按 `04-01` 部署并验证 `curl` 可达。
## 清单路径(唯一真源)
| 项 | 路径 / 命令 |
|----|-------------|
| 本篇完整清单(累积至 04-03 | [`ansible/files/04-01/04-03-nodejs-demo.yaml`](../ansible/files/04-01/04-03-nodejs-demo.yaml) |
| 手工应用 | `kubectl apply -f ansible/files/04-01/04-03-nodejs-demo.yaml` |
| Ansible | `ansible-playbook -i ansible/inventory.ini ansible/playbooks/verify/04-01.yml -e nodejs_demo_manifest=04-03-nodejs-demo.yaml` |
若你更喜欢命令行换镜像,文末也给了 **`kubectl set image`**,可不改仓库清单。
## 场景说明(白话)
- **换镜像版本**:就像本地 `docker pull node:18.20-alpine`K8s 里改 `image:` 一行即可;写死版本号比总写 `latest` 更容易排查「昨天还能跑今天不行」。
- **何时拉镜像imagePullPolicy**:节点上还没有这个镜像时肯定要拉;若 CI 总往同一个 tag 里覆盖推送,一般要 **`Always`**,否则会用到旧层。
- **改启动命令**:镜像自带的入口不满足时,用 `command` / `args` 告诉 K8s「用哪条命令起 Node」和 Docker 里覆盖 `ENTRYPOINT`/`CMD` 一个意思。
- **NODE_OPTIONS 等**:适合放在环境变量里,见 [`04-04-nodejs-环境变量与配置注入.md`](04-04-nodejs-环境变量与配置注入.md)。
### 相对 `04-02` 的变更(原文 → 新文)
| 位置 | 原文(`04-02` | 新文(`04-03` |
|------|-----------------|-----------------|
| `containers[].image` | `node:18-alpine` | `node:18.20-alpine` |
| `containers[].imagePullPolicy` | (默认) | `IfNotPresent` |
| `containers[].command` / `args` | 单行 `["node","-e","...listen(8080)"]` | `command: ["node"]` + `args` 两段,`listen(8080)``res.end('Hello from pinned image')` |
应用:
```bash
kubectl apply -f ansible/files/04-01/04-03-nodejs-demo.yaml
# 或仅打补丁(示意)
kubectl set image deployment/nodejs-demo nodejs-demo=node:18.20-alpine -n default
```
## 验证
```bash
kubectl describe pod -l app=nodejs-demo -n default | sed -n '/Image:/,/Port:/p'
kubectl get pod -l app=nodejs-demo -n default
curl -s --max-time 3 http://<节点IP>/node/
```
预期Pod 为 Running响应体与当前 `command`/`args` 一致。
## 删除 / 回滚
```bash
kubectl rollout undo deployment/nodejs-demo -n default
# 或恢复 04-01 原始 YAML 后 kubectl apply -f nodejs-demo.yaml
```
## 失败排查
- **ImagePullBackOff**:镜像名/tag 错误、私有仓库未配置 `imagePullSecrets`、节点无法访问 registry。
- 统一网络与策略:`06-01-k3s-networkpolicy-故障排查.md`
## 相关文档
- [`04-04-nodejs-环境变量与配置注入.md`](04-04-nodejs-环境变量与配置注入.md)
- [`04-08-nodejs-资源请求与限制.md`](04-08-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`