【问题标题】:Deploying Client and Server to the same VM将客户端和服务器部署到同一个虚拟机
【发布时间】:2020-09-26 14:18:45
【问题描述】:

我有一个具有React 前端和Python Flask 后端的应用程序。前端与服务器通信以执行特定操作,服务器 api 应仅供客户端使用。

我已将整个应用程序(客户端和服务器)部署到 Ubuntu 虚拟机。该机器仅具有向公众开放的特定端口(5000、443、22)。我已经设置了Nginx 配置,并且可以通过http://<ip:address>:5000 从我的浏览器访问前端。服务器在不同的端口 4000 上本地运行,按照设计,公众无法访问该端口。

问题是当我访问客户端应用程序并从 react 应用程序导航到通过 http://127.0.0.1:4000 与服务器通信的页面时,我收到一条错误消息,提示连接被拒绝。 GET http://127.0.0.1:4000/ net::ERR_CONNECTION_REFUSED 在我的浏览器上。

当我 ssh 进入 vm 并通过 curl curl http://127.0.0.1:4000/ 运行相同的命令时,我得到了响应并且一切正常。

有没有一种方法可以将服务器部署在同一个虚拟机中,这样当我从浏览器访问客户端 React App 时,React App 可以毫无问题地访问服务器?

【问题讨论】:

    标签: reactjs ubuntu nginx web-applications client-server


    【解决方案1】:

    所以在修改后,我找到了使用 Nginx 的解决方案。总结是您在本地运行服务器并使用不同的端口,例如 4000(未公开),然后在本例中为 5000 的公开端口上公开您的反应应用程序。

    然后在您的 Nginx 配置中使用代理,将任何以 api 开头的调用重定向到正在运行的本地主机服务器。见下面的配置

    server {
       #Exposed port and servername ipaddress
       listen 5000;
       server_name 1.2.3.4 mydomain.com;
    
       #SSL
       ssl on;
       ssl_certificate /etc/nginx/ssl/nginx.crt;
       ssl_certificate_key /etc/nginx/ssl/nginx.key;
       ssl_protocols TLSv1.2;
    
       #Link to the react build   
       root /var/www/html/build;
       index index.html index.htm;
    
       #Error and access logs for debugging
       access_log /var/log/nginx/access.log;
       error_log /var/log/nginx/error.log;
    
       location / {
           try_files $uri /index.html =404;
       }
    
       #Redirect any traffic beginning with /api to the flask server
       location /api {
        include proxy_params;
        proxy_pass http://localhost:4000;
       }
    }
    

    现在这意味着您需要让所有服务器端点以/api/... 开头,并且用户还可以通过http://<ip:address>:5000/api/endpoint 从浏览器访问端点

    您可以通过让您的客户端向服务器发送令牌来缓解这种情况,如果没有该令牌/授权,服务器将不会运行任何命令。

    我在这里找到了解决方案并在此处对其进行了修改以满足我的特定需求 Part two of solution

    解决方案中的其他系列可以找到Part one of solutionPart three of solution

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-26
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多