将客户端和服务器部署到同一台VM

时间:2020-09-25 20:55:48

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

我有一个具有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在我的浏览器上。

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

是否可以在同一个虚拟机中部署服务器,以便从浏览器访问客户端React App时,React App可以毫无问题地访问服务器?

1 个答案:

答案 0 :(得分:0)

因此,在进行了修改之后,我找到了使用Nginx的解决方案。摘要是您在本地运行服务器,并使用另一个端口(例如4000)(不公开),然后在这种情况下将您的react应用程序暴露在公开的端口上。

然后在您的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