开发调试中会遇到这样的问题,服务运行在本地机器上,想让外网访问本地机器的服务,就要提供公网地址。但大多数情况下,本地机器在内网,还需要穿透NAT网络和防火墙。ngork 正好解决了这个痛点,可以提供临时的URL,让外网访问到本地机器上的web服务。
原理:
本地起一个服务ngrok-local,和官方服务ngrok-server建立了一个tcp连接,ngrok-server将随机二级域名 http://xxxxxxxxxxx.ngrok.io 下的流量转发到ngrok-local,ngrok-local 再将流量代理到本地服务。
ngrok 使用例子
-
到 官网 下载ngrok的二进制静态文件
-
配置账号,只需要配置一个token,该 token 在官网首页可以找到
./ngrok authtoken xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- 启动http隧道,代理到本地端口80080
./ngrok http 8080
ngrok by @inconshreveable (Ctrl+C to quit)
Session Status online
Account John (Plan: Free)
Version 2.3.40
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding http://xxxxxxxxxxx.ngrok.io -> http://localhost:8080
Forwarding https://xxxxxxxx.ngrok.io -> http://localhost:8080
Connections ttl opn rt1 rt5 p50 p90
3 0 0.00 0.00 0.00 0.00
HTTP Requests
-------------
GET /doc/ 200 OK
GET /favicon.ico 404 File not found
GET / 200 OK
外网访问 http://xxxxxxxxxxx.ngrok.io 的请求,会被转发到本地地址 http://localhost:8080。 http://localhost:4040 地址可以查看具体的请求。