如何使用Nginx,Capistrano和Passenger部署React前端+ Rails api后端

问题描述 投票:1回答:2

我正在部署一个具有React前端的应用程序,该前端使用create-react-app和Rails API作为后端创建。 我对配置Web服务器和代理不是很了解,因此我不确定如何使它在生产环境中正常工作。 我正在将应用程序部署到Amazon EC2实例上的Ubuntu。 Nginx是Web服务器。 我需要对其进行配置,以便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;
       }
}

我想念什么? 如何使Rails应用程序在端口3001上运行,并向/api所有请求? 在此配置中是否需要一个单独的server块?

ruby-on-rails reactjs nginx deployment http-proxy
2个回答
2
投票

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

我正在将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;
}

因此,相比之下,我认为您的问题可能会通过添加指向rails api公共目录的根指令来解决

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


0
投票

这是我工作的nginx配置

  map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
server {
  listen 80 default_server;
  root /home/deploy/www/sublime/current/public;
  index index.html;
  server_name domain.com;
  access_log /home/deploy/www/sublime/logs/access.log;
  error_log /home/deploy/www/sublime/logs/errors.log;
  server_name localhost;
  passenger_enabled on;
  passenger_app_env production;
location ~* ^.+\.(jpeg|gif|png|jpg) {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
  }
  location /api {
            # Insert your public app path
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_buffering off;
  }
  location / {
              # First attempt to serve request as file, then
              # as directory, then fall back to displaying a 404.
              try_files $uri /index.html;
  }
}

您可以使用此存储库查看Rails配置https://github.com/Eth3rnit3/rails-react

© www.soinside.com 2019 - 2024. All rights reserved.