如何在nginx中部署ruby-on-rails应用程序?

时间:2015-01-20 07:46:07

标签: ruby-on-rails ruby ruby-on-rails-3 nginx web-deployment

我在ruby on rails部署nginx个应用程序,我的应用程序如下:

app/
    ...(omit other files)
    views/
        ...(omit other files)
        static_pages/
            ....(omit other files)
            home.html.erb
public/
    404.html
    422.html
    500.html
config/
    routes.rb
....(omit other files)

以下是routes.rb

 Rails.application.routes.draw do
     root 'static_pages#home'
 end

以下是Gemfile

source 'https://rubygems.org'
gem 'rails', '4.2.0'
gem 'bootstrap-sass', '~> 3.3.1'
gem 'sqlite3'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'bcrypt', '~> 3.1.7'
gem 'faker'
gem 'carrierwave'
gem 'mini_magick'
gem 'fog'
gem 'nokogiri'
gem 'will_paginate', '~> 3.0.6'
gem 'will_paginate-bootstrap'

group :development, :test do
  gem 'byebug'
  gem 'web-console', '~> 2.0'
  gem 'spring'
end

group :test do
  gem 'minitest-reporters'
  gem 'mini_backtrace'
  gem 'guard-minitest'
end

group :production do
  gem 'pg', '0.17.1'
  gem 'rails_12factor'
  gem 'unicorn'
end

如您所见,我的主页为app/views/static_pages/home.html.erb,只有一些错误页面位于public/

那么如何配置nginx指向我的主页?(我的应用程序位于/home/roger/blog/

server {
    listen 80 default;
    server_name example.com;
    location {
        root ?????????;
        index ?????????;
    }
}

1 个答案:

答案 0 :(得分:1)

您没有将nginx配置为指向您的主页,您将nginx配置为代理到rails应用程序的流量,rails应用程序执行其他所有操作(少数例外)。

这是一个简单的示例,假设rails应用程序正在侦听套接字/tmp/unicorn.app.sock,而应用程序根目录是/vagrant

upstream unicorn {
  server unix:/tmp/unicorn.app.sock fail_timeout=0;
}

server {
  listen 80 default deferred;
  root /vagrant/public;
  try_files $uri/index.html $uri @unicorn;

  location @unicorn {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header HOST $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 5;
}

您可以将根(在您的情况下为/home/roger/blog/public}和上游服务器更改为适合您的设置的任何内容(可能您希望将unix:/tmp/unicorn.app.sock更改为http://127.0.0.1:3000)。

以下示例应该对您有效而无需更改(假设您的应用服务器正在侦听端口3000):

upstream blog {
  server 127.0.0.1:3000;
}

server {
  listen 80 default deferred;
  root /home/blog/roger/public;
  try_files $uri/index.html $uri @blog;

  location @blog {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header HOST $http_host;
    proxy_redirect off;
    proxy_pass http://blog;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 5;
}