内网映射到外网环境 ngrok/nginx两种方式

ngrok内网映射到外网环境

1、 下载ngrok,网址:https://ngrok.com/download

2、注册ngrok,地址:https://dashboard.ngrok.com/user/signup

    如果你已经有ngrok账号,登陆ngrok,如图找到你的authtoken

    3、将下载好的ngrok解压到本地,进入ngrok所在的目录

  

4、将authtoken(如40u6g....)添加到本地(只需要第一次执行添加,以后不需要再添加。笔者是Mac环境)

./ngrok authtoken 4ou6g....
5、启动ng rok,映射的端口是8080

./ngrok http 8080
    执行上面的启动命令,Session Status=online 即代表成功,可根据自动生成的域名进行访问,如笔者生成的域名是:http://48b1c3e2.ngrok.io

  

注:因为ngrok免费版,域名是不固定的,如果想要稳定的域名,需要付费,不再叙说。

     下面讲述一个通过nginx进行外网映射,固定域名,免费版,前提是你得有一个公网IP

  nginx 映射外网环境

1、需要安装nginx,如果还未安装nginx,Mac环境下如何安装nginx可参考该博文,

  http://blog.csdn.net/lanqibaoer/article/details/72853056

 如果已经安装了nginx,但是不清楚nginx安装目录,可执行以下命令进行查询:

ps -ef | grep nginx
/usr/sbin/nginx -t
[root/]# ps -ef | grep nginx
root      9730     1  0  2017 ?        00:00:00 nginx: master process /usr/sbin/nginx
root     14290 14218  0 09:34 pts/5    00:00:00 grep --color=auto nginx
nginx    32480  9730  0  2017 ?        00:01:46 nginx: worker process
nginx    32481  9730  0  2017 ?        00:02:20 nginx: worker process
[root/]# /usr/sbin/nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root/]# 
“  the configuration file /etc/nginx/nginx.conf syntax is ok  ”这里的 /etc/nginx/nginx.conf  就是你服务器中安装nginx配置文件的地址。

2、有一台公网服务器,在公网服务器的nginx.conf中添加以下内容

upstream tunnel {
  server 127.0.0.1:7689;
}

server {
  listen 80;
  server_name dev.ninghao.net;
  
  location / {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    
    proxy_pass http://tunnel;
  }
}
上面用 NGINX 创建了一个代理,如果有人访问 dev.ninghao.net,NGINX 会把请求转给 tunnel,这个 tunnel 指的就是这台公网服务器,端口号是 7689,一会儿我们要用到这个端口跟内网环境电脑进行通信。

 注:1)upstream 和 server 可以配置多个,每个upstream和server都是平级的;

     2)server listen不可相同(此处需要商榷),如果listen 端口是80,默认域名访问的端口是80,无需显性标示,如果listen端口是80以外的端口,比如,8088,则访问域名还要再其后加8088,如 http://dev.ninghao.net:8088/

3、打开你内网环境的服务器

我们要在本地电脑与公网服务器之间,使用 SSH 打开一个通道。在内网环境服务器中要执行的命令像这样: 

ssh -vnNT -R 服务器端口:localhost:本地端口 服务器用户名@服务器 IP 地址
示例:
ssh -vnNT -R 7689:localhost:3000 [email protected]
在上面这个例子里,7689 指的是公网服务器的端口,localhost 后面的 3000 是本地电脑用的端口。

root 是登录到公网服务器的用户,42.120.40.68 是公网服务器的 IP 地址。

因为我们配置了公网服务器的 NGINX,访问 dev.ninghao.net ,把请求转到服务器上的 7689 端口,

这个端口跟我们的内网环境电脑上的 3000 端口是连接到一块儿的。

所以,你在内网开发环境上搭建的服务器,应该使用 3000 这个端口提供服务。

也就是,当有人访问 dev.ninghao.net 这个地址的时候,用户得到的响应是你的内网开发环境上的服务器提供的。

参考文档:

https://ngrok.com/docs

http://blog.csdn.net/liuxiyangyang/article/details/22922265/

https://ninghao.net/blog/4452

猜你喜欢

转载自blog.csdn.net/lanqibaoer/article/details/79149149