背景

内网里有一个 GPU 服务器,因为比较昂贵,不能在公网开放任何端口,只有开启了 VPN 才可以在内网访问它的所有端口。但是又希望这个主机上部署的大模型向外提供服务,因此设置了一个低配置的外网中转服务器,内外网两个服务器做了 ip 映射,外网中转服务器开放了网站的前后端两个端口仅此而已。此时,访问外网的端口,等同于通过 VPN 访问了内网服务器对应端口。这种情况下内网中的 nginx 应该怎么配置呢,监听的 ip 是写内网还是外网的 ip?

原则

  1. 只有内网需要配置 nginx,外网不需要任何操作
  2. 内网的 nginx 配置文件(/etc/nginx/nginx.conf)中只可以出现内网 ip,绝对不可以出现外网 ip。这种情况需要当外网不存在,直接配置内网即可。
  3. 因为外网也不能开 80 端口,于是前端只能挂在 10001 端口。但是又希望用户可以不输入端口号直接访问网站,于是就需要把访问 80 端口的转发到访问 10001 端口上。

参考的配置文件:

# nginx 的默认用户 www-data
user www-data;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
include /etc/nginx/modules-enabled/*.conf;

events {
	worker_connections 768;
}

http {
	sendfile on;
	tcp_nopush on;
	types_hash_max_size 2048;

	include /etc/nginx/mime.types;
	default_type application/octet-stream;

	ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
	ssl_prefer_server_ciphers on;

	access_log /var/log/nginx/access.log;

	gzip on;

	server {
		listen	10001;【监听前端端口号】
		server_name 172.16.0.xxx;【内网 ip】
		location / {
			root /usr/share/nginx/html/dist;【dist 路径】
			index index.html;【dist 的入口】
			add_header Access-Control-Allow-Private-Network true;【允许跨域】
		}
	}

	server {
   		 listen 80;
		 server_name 172.16.0.225;
   		 location / {
       		 proxy_pass http://127.0.0.1:10001;  # 转发到本机10001端口
        	 proxy_set_header Host $host;
        	 proxy_set_header X-Real-IP $remote_addr;
       		 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   		 }
	}		
}

原因位置的奇怪情形及解决办法

问题

在外网访问后端端口,但是却得到 nginx 显示显示的 404 Not Found。明明是访问后端,而且 nginx 也没有监听 9898 端口,为什么访问 9898 却是由 nginx 拒绝。

解决办法

在监听前端 10001 端口的时候注意看是否有根路径为 /api 的链接来 10001 端口,如果有就把它转发到 9898 端口。

server {
    listen 10001;
    server_name localhost; 
    # 1. 网页前端(保持不变)
    location / {
        root /usr/share/nginx/html/dist;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    # 【新增部分】
    location /api/ {
        # 意思是:Nginx 收到请求后,转手交给隔壁的 Python
        proxy_pass http://127.0.0.1:9898; 
        
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐