基本框架

This commit is contained in:
2026-03-21 04:36:06 +08:00
commit de1be1dbe5
125 changed files with 10302 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
# 04-03-nodejs-环境变量与配置注入
> 在 [`04-01-k3s-nodejs-高级部署.md`](04-01-k3s-nodejs-高级部署.md) 基线上,用 **ConfigMap / Secret** 与 **`env` / `envFrom`** 注入配置,避免把敏感信息写进镜像或 Deployment 明文。
## 前置条件
- 已部署 `nodejs-demo``04-01`)。
## 清单路径(唯一真源)
| 项 | 路径 / 命令 |
|----|-------------|
| 本篇完整清单(累积至 04-03含 ConfigMap + Deployment + Service + Ingress | [`ansible/files/nodejs-demo/04-03-nodejs-demo.yaml`](../ansible/files/nodejs-demo/04-03-nodejs-demo.yaml) |
| Secret 示例(勿提交真密钥) | [`ansible/files/nodejs-demo/nodejs-demo-secret.example.yaml`](../ansible/files/nodejs-demo/nodejs-demo-secret.example.yaml) |
| 手工应用 | `kubectl apply -f ansible/files/nodejs-demo/04-03-nodejs-demo.yaml` |
| Ansible | `ansible-playbook ... -e nodejs_demo_manifest=04-03-nodejs-demo.yaml` |
## 场景说明(白话)
- **普通配置**(提示文案、开关、非密钥连接串):用 **ConfigMap**;改完 `kubectl apply`Pod 滚动后生效(是否自动重启取决于你怎么挂载/引用)。
- **密钥类**:用 **Secret**;内容和 ConfigMap 类似,但要更严格管控权限与存储位置。
- **在 Node 里怎么用**:和在本机设环境变量一样,例如 `NODE_ENV``PORT``NODE_OPTIONS`;启动命令怎么写见 [`04-02-nodejs-镜像与运行命令.md`](04-02-nodejs-镜像与运行命令.md)。
### 相对 `04-02` 的变更(原文 → 新文)
| 位置 | 原文(`04-02` | 新文(`04-03` |
|------|-----------------|-----------------|
| 新增资源 | (无) | `ConfigMap` `nodejs-demo-config``APP_MSG` |
| `containers[].env` | (无) | `APP_MSG` 来自 `configMapKeyRef` |
| `containers[].command` | `["node"]` + `args` 单行脚本 | `node` + 多行 `-e` 脚本,读 `process.env.APP_MSG`,仍监听 **3000** |
应用:
```bash
kubectl apply -f ansible/files/nodejs-demo/04-03-nodejs-demo.yaml
```
## 验证
```bash
kubectl get cm nodejs-demo-config -n default -o yaml
kubectl exec deploy/nodejs-demo -n default -- printenv APP_MSG
curl -s --max-time 3 http://<节点IP>/node/
```
## Secret 示例(仅示意)
**说明**:示例文件为 [`nodejs-demo-secret.example.yaml`](../ansible/files/nodejs-demo/nodejs-demo-secret.example.yaml);也可 `kubectl create secret generic ...`。在 Pod 中用 `env.valueFrom.secretKeyRef` 引用;验证 `printenv API_TOKEN`(注意日志勿打印密钥)。
## 删除
```bash
kubectl delete configmap nodejs-demo-config -n default --ignore-not-found
kubectl delete secret nodejs-demo-secret -n default --ignore-not-found
```
## 失败排查
- **CreateContainerConfigError**:引用的 ConfigMap/Secret 不存在或 key 名错误。
- `06-01-k3s-networkpolicy-故障排查.md`
## 相关文档
- [`04-09-nodejs-存储与卷.md`](04-09-nodejs-存储与卷.md)(文件挂载另一种注入方式)
- [`04-12-nodejs-TLS与证书.md`](04-12-nodejs-TLS与证书.md)