自托管 Ngrok 替代方案,200 行 Node.js 实现
发布: (2026年2月2日 GMT+8 12:13)
3 分钟阅读
原文: Dev.to
Source: Dev.to
Problem
需要为多个本地服务创建隧道,但 Ngrok 免费套餐只能提供单一隧道。
Solution
一个约 200 行 Node.js 编写的自托管隧道。只需一条命令即可创建多个公共 URL。
liptunnel http 3000,8080,5000 --multi
此命令会在你的域名上生成三个公共 URL,流量路径如下:
用户 → yourdomain.com → VPS → WebSocket → 你的电脑 → localhost
Core concept
Server (forward HTTP via WebSocket)
// server.js (Express middleware)
app.use((req, res) => {
const subdomain = req.headers.host.split('.')[0];
tunnels[subdomain].ws.send(JSON.stringify(req));
// Wait for response, then send it back to the client
});
Client (receive, proxy, respond)
// client.js
ws.on('message', (data) => {
const request = JSON.parse(data);
const proxy = http.request(
{
hostname: 'localhost',
port: request.port,
path: request.path,
method: request.method,
headers: request.headers,
},
(response) => {
let body = '';
response.on('data', (chunk) => (body += chunk));
response.on('end', () => {
ws.send(
JSON.stringify({
statusCode: response.statusCode,
headers: response.headers,
body,
})
);
});
}
);
proxy.end(request.body);
});
其余实现负责错误处理、连接管理以及清理工作。
Features
- Privacy – 流量永不离开你的基础设施。
- Cost – 只需支付 VPS 费用(其余免费)。
- Branding – 使用自己的域名作为隧道 URL。
- Control – 完全自定义路由和处理方式。
Performance
- 内存:每个隧道约 25 MB
- 延迟:约 5 ms 开销
- 吞吐量:100+ 请求/秒
Use cases
- 快速搭建本地微服务
- 在不部署的情况下测试 webhook(Stripe、GitHub 等)
- 使用带有客户品牌的 URL 进行演示
- 合规性要求高的环境(医疗、金融),禁止使用第三方服务
Setup
# Clone the repository
git clone https://github.com/ibrahimpelumi6142/liptunnel
cd liptunnel
# Install dependencies
npm install
# Run the server on your VPS
node server/server.js # <-- 在远程机器上启动
# Start a tunnel from your local machine
liptunnel http 3000 # <-- 将 3000 替换为你想要暴露的端口
Technology stack
- Node.js – 运行时
- WebSocket – 隧道传输层
- Express – 可选的仪表盘(不依赖重量级框架)
所有代码均集中在一个约 200 行的项目中。
Roadmap (coming soon)
- 通过 Let’s Encrypt 支持 HTTPS
- 固定子域名
- 隧道访问的身份验证令牌
- 请求检查器 UI
Contributing
如果你觉得项目有用,请在 GitHub 上为它加星:
欢迎提交 Issue 或 Pull Request 来改进项目。