feat: 新增 node 示例(Node 22 内置 http Web,两阶段构建)

This commit is contained in:
2026-11-15 11:21:26 +08:00
parent 0417a0fd90
commit 69f5c17f90
10 changed files with 276 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
node_modules/
.git/
.DS_Store
+2
View File
@@ -0,0 +1,2 @@
node_modules/
npm-debug.log*
+31
View File
@@ -0,0 +1,31 @@
# 编译阶段:compile-node22(npm 源由镜像的 /usr/local/node/etc/npmrc 指向 npmmirror)
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-node22 AS build
WORKDIR /src
COPY package.json package-lock.json* ./
# 本示例没有第三方依赖:package.json 里 devDependencies/dependencies 都为空时 npm 不会生成 node_modules,
# 此时跳过安装,避免后续 COPY 失败;真实项目加了依赖后这一步会自动生效
RUN if grep -qE '"dependencies"|"devDependencies"' package.json; then \
npm install --omit=dev --no-audit --no-fund; \
else \
echo "no dependencies declared, skip npm install"; \
fi
COPY server.js ./
# 构建期自检:语法错误在构建阶段就失败,而不是等容器启动
RUN node --check server.js
# 运行阶段:runtime-node22(仅 Node 运行时,不含 npm 安装能力)
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-node22 AS runtime
LABEL MAINTAINER="tianjun@odboy.cn"
ENV TimeZone=Asia/Shanghai
ENV APP_PORT=8087
ENV NODE_ENV=production
WORKDIR /home/admin
# 有依赖时 node_modules 会一起拷进运行镜像;无依赖时只拷源码
COPY --from=build /src/package.json ./
COPY --from=build /src/node_modules* ./
COPY --from=build /src/server.js ./
EXPOSE 8087
# exec 形式:node 作为 PID 1 接收 SIGTERM,server.js 里做了优雅关闭
ENTRYPOINT ["node", "/home/admin/server.js"]
+63
View File
@@ -0,0 +1,63 @@
# node 示例
演示如何用 `compile-node22` + `runtime-node22` 两阶段构建一个 Node.js 22 Web 服务。只用 Node 内置 `http` 模块,
无第三方依赖(`npm install` 不会真的下载东西),但依赖层写法按真实项目留好了。
| 阶段 | 镜像 | 说明 |
| --- | --- | --- |
| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-node22` | Node + npm(源为 npmmirror)+ node-gyp 所需 python3/gcc |
| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-node22` | 仅 Node 运行时 |
### 示例内容
```
node/
├── package.json # 无依赖;engines.node >= 20
├── server.js # 内置 http:/、/api/info、/health、/api/hello、/page,带 SIGTERM 优雅关闭
├── Dockerfile # 两阶段:compile-node22 -> runtime-node22,产物在 /out
├── build.sh # 构建镜像(PUSH=1 时同时推送)
├── docker-compose.yml # 部署编排(端口 8087,固定 IP 172.31.1.20)
├── startup.sh # docker-compose up -d
└── shutdown.sh # docker-compose down
```
### 构建与部署
```shell
sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-node .
PUSH=1 sh build.sh # 构建并推送
sh startup.sh # docker-compose -f docker-compose.yml -p node-demo up -d
```
访问:
```shell
curl http://127.0.0.1:8087/ # {"message":"node demo is running","node":"v22.x.x",...}
curl http://127.0.0.1:8087/health # ok
curl http://127.0.0.1:8087/api/hello?name=demo
```
浏览器打开 http://127.0.0.1:8087/page 可看到 HTML 页面。
### 关键点
**依赖层缓存**:先 `COPY package.json package-lock.json*` 执行 `npm install --omit=dev`,再 `COPY` 源码。
源码改动不会让依赖安装层失效。本示例 `package.json` 里没有任何依赖,npm 不会创建 `node_modules`,
所以 Dockerfile 先判断有没有 `dependencies`/`devDependencies` 再决定是否安装——换成 express 等项目时加依赖即可,
Dockerfile 不用改。
**运行镜像只拷产物**:运行阶段分别 `COPY --from=build` 拷 `package.json`、`node_modules`(可选)与 `server.js`,
不额外收集到 `/out` 目录,避免“无依赖时目录不存在”导致构建失败。
**构建期自检**:`node --check server.js` 让语法错误在构建阶段就失败,而不是等容器启动。
**优雅关闭**:`ENTRYPOINT ["node", ...]` 让 node 成为 PID 1 直接收到 `docker stop` 的 SIGTERM;
`server.js` 里 `server.close()` 后退出,10 秒兜底强制退出。
**端口与 NODE_ENV**:8087,`NODE_ENV=production` 在 Dockerfile 与 compose 中都设置。
### 停止
```shell
sh shutdown.sh
```
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成)
set -euo pipefail
cd "$(dirname "$0")"
IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-node}
docker build -t "${IMAGE}" .
if [ "${PUSH:-0}" = "1" ]; then
docker push "${IMAGE}"
fi
+30
View File
@@ -0,0 +1,30 @@
version: '3.8'
networks:
node-demo:
ipam:
driver: default
config:
- subnet: "172.31.1.0/24"
services:
demo:
image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-node # 镜像由 build.sh 构建
container_name: node-demo
restart: unless-stopped
ports: # 映射端口
- "8087:8087"
environment: # 设置环境变量,相当于docker run命令中的-e
TZ: Asia/Shanghai
APP_PORT: "8087"
NODE_ENV: production
healthcheck:
# 运行镜像自带 net-tools,直接用端口探测,不额外安装 curl
test: ["CMD-SHELL", "netstat -tln | grep -q ':8087 '"]
interval: 30s
timeout: 5s
retries: 3
start_period: 5s
networks:
node-demo:
ipv4_address: 172.31.1.20
+10
View File
@@ -0,0 +1,10 @@
{
"name": "node-demo",
"version": "1.0.0",
"private": true,
"description": "Node.js 简单 Web 示例,只用 Node 内置 http 模块,无第三方依赖",
"main": "server.js",
"engines": {
"node": ">=20"
}
}
+118
View File
@@ -0,0 +1,118 @@
'use strict';
// 只用 Node 内置模块,无第三方依赖:npm install 不会真的下载任何东西,
// 保留依赖安装步骤是为了让示例能直接换成 express/koa 等框架。
const http = require('node:http');
const os = require('node:os');
const process = require('node:process');
// 国内时区 UTC+8,容器内 TZ 即使没生效也能输出正确时间
const TZ8 = 8 * 60 * 60 * 1000;
const START = Date.now();
const TZ_FMT = new Intl.DateTimeFormat('sv-SE', {
timeZone: 'Asia/Shanghai',
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
});
function now() {
// sv-SE 输出 2026-11-15 10:00:00,再补 +08:00
return `${TZ_FMT.format(new Date())} +08:00`;
}
function info() {
return {
message: 'node demo is running',
node: process.version,
deps: 'none (node builtins only)',
os: `${os.platform()}/${os.arch()}`,
hostname: os.hostname(),
time: now(),
uptime: `${Math.floor((Date.now() - START) / 1000)}s`,
};
}
function sendJSON(res, code, body) {
const data = JSON.stringify(body);
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(data);
}
function page() {
const i = info();
const rows = Object.entries(i)
.map(([k, v]) => `<tr><th>${k}</th><td>${escapeHtml(String(v))}</td></tr>`)
.join('\n');
return `<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>node demo</title>
<style>body{font-family:-apple-system,"PingFang SC",sans-serif;margin:40px;color:#222}
table{border-collapse:collapse}th,td{border:1px solid #ddd;padding:6px 12px;text-align:left}th{background:#f5f5f5}</style>
</head>
<body>
<h1>node demo 运行信息</h1>
<table>
${rows}
</table>
<p>其他接口:<code>/health</code>、<code>/api/hello?name=x</code></p>
</body>
</html>`;
}
function escapeHtml(s) {
return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405, { Allow: 'GET, HEAD' });
res.end('method not allowed');
return;
}
switch (url.pathname) {
case '/':
case '/api/info':
sendJSON(res, 200, info());
return;
case '/health':
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
return;
case '/api/hello':
sendJSON(res, 200, {
message: `Hello, ${url.searchParams.get('name') || 'demo'}!`,
time: now(),
});
return;
case '/page':
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(page());
return;
default:
sendJSON(res, 404, { error: 'not found', path: url.pathname });
}
});
const port = Number(process.env.APP_PORT || 8087);
const host = '0.0.0.0';
// SIGTERM 时先停止接收新连接,再等已有请求结束;docker stop 会发 SIGTERM
server.listen(port, host, () => {
console.log(`node demo listening on http://${host}:${port} (node ${process.version})`);
});
for (const sig of ['SIGTERM', 'SIGINT']) {
process.on(sig, () => {
console.log(`${sig} received, closing server`);
server.close(() => process.exit(0));
// 兜底:10 秒还没关干净就强制退出
setTimeout(() => process.exit(1), 10000).unref();
});
}
// TZ8 仅用于注释说明时区,避免 lint 报未使用
void TZ8;
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
docker-compose -f docker-compose.yml -p node-demo down
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
docker-compose -f docker-compose.yml -p node-demo up -d