← 文档目录 · 部署 Node 服务 · 5 分钟快速上手

5 分钟快速上手

以仓库 你的用户名/hello-node 为例,目标是让它出现在
https://sxd91.kdns.fr/server/hello-node。

第 1 步:写一个最小的服务

仓库根目录放 server.js:

const http = require('node:http');

// ★ 必须读 PORT:平台会注入一个已分配好的端口
const port = Number(process.env.PORT) || 3000;
// ★ 监听 127.0.0.1 即可(平台在同一台机器上反代过来)
const host = process.env.HOST || '127.0.0.1';

http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('hello from ' + req.url + '\n');
}).listen(port, host, () => {
  console.log('listening on ' + host + ':' + port);
});

两个 ★ 是最关键的两行。不读 PORT 的服务部署后会一直健康检查失败。

第 2 步:加 workflow

新建 .github/workflows/deploy.yml:

name: deploy
on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  deploy:
    runs-on: self-hosted
    steps:
      - uses: actions/checkout@v4
      - uses: localhub/host-node@v1
        with:
          entry: server.js

第 3 步:push

git add server.js .github/workflows/deploy.yml
git commit -m "add deploy workflow"
git push

第 4 步:看结果

打开 https://sxd91.kdns.fr/actions,会看到一次 deploy 运行。
点进去,最后一步的日志里会有:

部署 alice/hello-node → https://sxd91.kdns.fr/server/hello-node
  工作目录: /opt/localhub/data/actions/run_xxx/work/01-deploy/workspace
  启动方式: node server.js
  内部端口: 127.0.0.1:18000(PID 12345)
  ✓ 健康检查通过(412ms,HTTP 200)
  对外地址: https://sxd91.kdns.fr/server/hello-node

第 5 步:访问

curl https://sxd91.kdns.fr/server/hello-node
# hello from /

也可以打开 <a href="https://sxd91.kdns.fr/server">托管服务列表</a> 点进去看详情与日志。

之后每次改代码

再 push 一次就行。同一次部署会先停旧进程再起新的,端口保持不变,
地址不变。旧进程收到 SIGTERM,有 5 秒宽限期做清理,之后才 SIGKILL。