如何使用nginx、capistrano和passenger部署React前端+Rails api后端

Joh*_*ess 2 deployment ruby-on-rails nginx http-proxy reactjs

我正在部署一个应用程序,其中使用 React 前端创建create-react-app,并使用 Rails API 作为后端。我对配置网络服务器和代理不太了解,所以我不确定如何让它在生产中工作。我正在将应用程序部署到 Amazon EC2 实例上的 Ubuntu。Nginx 是网络服务器。我需要配置它,以便 Nginx 提供目录中的静态文件client/build,然后发送任何请求/api到端口 3001 上运行的 Rails 应用程序。现在 Nginx 正在提供 index.html 并且 Javascript 运行正常,但请求/api是没有去正确的地方。关于如何配置 Nginx 来做到这一点有什么想法吗?这是我的/etc/nginx/sites-enabled/default文件:

server {
       listen 80 default_server;
       listen [::]:80 default_server;
       server_name mydomain.com;
       passenger_enabled on;
       rails_env    staging;
       root         /home/ubuntu/app-name/current/client/build;
       index index.html;

       location /api {
          proxy_pass http://127.0.0.1:3001;
       }
}
Run Code Online (Sandbox Code Playgroud)

我缺少什么?如何让 Rails 应用程序在端口 3001 上运行并使所有请求都发送到/api该端口?我需要server在此配置中使用单独的块吗?

Fer*_*ila 5

我不知道您是否已经解决了您的问题,以及该解决方案是否适用于您,但我认为它可能对其搜索此问题的其他人有用。

我使用 Puma 作为应用程序服务器来运行我的 Rails 5 api。

这是我的开发环境的配置文件:

upstream app {
# Path to Puma SOCK file, here is where you make the connection to your application server
server unix:/path/to/your/puma.sock fail_timeout=0;
}
server {
listen 80;
server_name mydomain.com;

# this is where my react-app is located
root /var/www/development/ram/public/;
index index.html index.htm;

# Serve the static content (React app)
location / {
    try_files $uri /index.html =404;
}

location /api {
    # Insert your public app path
    root /your/rails-app/path/public;
    proxy_pass http://app;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
}

error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}
Run Code Online (Sandbox Code Playgroud)

所以比较,我认为你的问题可以通过添加一个指向你的rails api公共目录的根指令来解决

我希望这可以给您一些有关如何配置的提示