Skip to content

Node.js 部署

适合直接由 Node.js 应用提供 HTTPS,或由 Node.js 结合 PM2 管理服务。

如果前面有 Nginx、Apache、LiteSpeed 或负载均衡,推荐在前置 Web Server 上部署证书,再反向代理到 Node.js。

1. 设置变量

bash
export DOMAIN="example.com"
export EMAIL="[email protected]"
export WEBROOT="/var/www/example.com/public"
export ACME_SERVER="你的 Server URL"
export EAB_KID="你的 EAB MAC ID"
export EAB_HMAC_KEY="你的 EAB MAC key"
export CERT_DIR="/etc/ssl/12ssl/$DOMAIN"

WEBROOT 需要能通过公网 HTTP 访问,用于 ACME 验证。

2. 安装并注册 acme.sh

bash
curl https://get.acme.sh | sh
source ~/.bashrc 2>/dev/null || source ~/.zshrc 2>/dev/null || true

~/.acme.sh/acme.sh --register-account \
  --server "$ACME_SERVER" \
  --eab-kid "$EAB_KID" \
  --eab-hmac-key "$EAB_HMAC_KEY" \
  --accountemail "$EMAIL"

3. 签发证书

bash
~/.acme.sh/acme.sh --issue \
  -d "$DOMAIN" \
  -w "$WEBROOT" \
  --server "$ACME_SERVER"

4. 安装证书

bash
sudo mkdir -p "$CERT_DIR"

sudo ~/.acme.sh/acme.sh --install-cert -d "$DOMAIN" \
  --key-file "$CERT_DIR/privkey.pem" \
  --fullchain-file "$CERT_DIR/fullchain.pem" \
  --reloadcmd "pm2 reload all || systemctl restart node-app"

5. Node.js HTTPS 示例

js
import fs from 'node:fs'
import https from 'node:https'
import app from './app.js'

const options = {
  key: fs.readFileSync('/etc/ssl/12ssl/example.com/privkey.pem'),
  cert: fs.readFileSync('/etc/ssl/12ssl/example.com/fullchain.pem')
}

https.createServer(options, app).listen(443)

6. 验证

bash
curl -I "https://$DOMAIN"
~/.acme.sh/acme.sh --cron --home ~/.acme.sh

Released under internal 12SSL documentation guidelines.