公网访问本地服务
约 735 字大约 2 分钟
内网穿透公网访问ngrok
2026-04-15
概述
公网访问工具将本地服务暴露到公网,方便他人预览或对接第三方回调。
ngrok
安装
# macOS
brew install ngrok
# Windows (choco)
choco install ngrok
# 或下载二进制文件
# https://ngrok.com/download基本使用
# 登录 (需要注册账号获取 token)
ngrok config add-authtoken <YOUR_TOKEN>
# 启动 HTTP 隧道
ngrok http 3000
# 启动带子域名的隧道
ngrok http --domain=your-subdomain.ngrok.io 3000
# 查看隧道信息
ngrok http 3000 --region=ap
# 查看所有活跃隧道
ngrok api /api/inctunnels配置 YAML
# ~/.ngrok2/ngrok.yml
authtoken: <YOUR_TOKEN>
region: ap
tunnels:
web:
proto: http
addr: 3000
subdomain: myapp
api:
proto: http
addr: 8080
auth: user:password
ssh:
proto: tcp
addr: 22
remote_addr: 1.tcp.ngrok.io:12345常用参数
ngrok http 3000 \
--host-header=rewrite \ # 重写 Host 头
--basic-auth="user:pass" \ # 基本认证
--log=stdout \ # 日志输出
--region=ap # 亚太区域frp
简介
frp 是一个高性能的内网穿透工具,支持多种协议。
服务端配置
# frps.ini
[common]
bind_port = 7000
vhost_http_port = 8080
dashboard_port = 7500
dashboard_user = admin
dashboard_pwd = admin
token = your_token客户端配置
# frpc.ini
[common]
server_addr = your_server_ip
server_port = 7000
token = your_token
[web]
type = http
local_port = 3000
custom_domains = your-domain.com
[ssh]
type = tcp
local_port = 22
remote_port = 6000启动
# 服务端
./frps -c ./frps.ini
# 客户端
./frpc -c ./frpc.inilocaltunnel
安装使用
# npm 安装
npm install -g localtunnel
# 启动
lt --port 3000
# 或指定子域
lt --port 3000 --subdomain myapp特点
- 简单易用,无需注册
- 共享式,可能不稳定
- 适合临时测试
Cloudflare Tunnel
安装
# macOS
brew install cloudflare/cloudflare/cloudflared
# 登录
cloudflared tunnel login使用
# 创建隧道
cloudflared tunnel create my-tunnel
# 配置 DNS
cloudflared tunnel route dns my-tunnel myapp.example.com
# 运行
cloudflared tunnel run my-tunnel
# 或连接本地服务
cloudflared tunnel --url http://localhost:3000工具对比
| 工具 | 配置难度 | 稳定性 | 费用 | 特点 |
|---|---|---|---|---|
| ngrok | 简单 | 高 | 免费有限制 | 官方服务,简单易用 |
| frp | 中等 | 高 | 自架服务器 | 完全自控,功能强大 |
| localtunnel | 简单 | 中 | 免费 | 无需账号,最简单 |
| Cloudflare Tunnel | 简单 | 高 | 免费 | 需要 Cloudflare 账号 |
| 花生壳 | 简单 | 中 | 付费 | 国内服务,需注册 |
应用场景
1. 第三方回调测试
# 启动本地服务
ngrok http 3000
# 将 ngrok 提供的 URL 配置到第三方平台
# 例如微信支付回调、OAuth 回调等2. 向客户演示
# 临时演示链接
ngrok http --region=ap 3000
# 关闭-basic-auth方便访问
lt --port 30003.Webhook 开发
# 配合 GitHub Webhook
ngrok http 3000
# GitHub 配置 webhook URL 为 ngrok 提供的地址安全注意事项
- 敏感操作: 完成后及时关闭隧道
- 访问控制: 使用认证保护
- HTTPS: 生产环境使用 HTTPS
- 日志审计: 记录访问日志
- Token 安全: 不要公开分享 Token
常见问题
| 问题 | 解决方案 |
|---|---|
| ngrok 401 无效 Token | 登录 ngrok 官网获取正确 Token |
| 连接不稳定 | 尝试不同区域 (us/eu/ap) |
| 微信无法访问 | 需要配置正确的 Referer |
| HTTPS 证书问题 | 使用 cloudflared 等支持真实证书的工具 |
