Snake's Home

Nginx+Passenger+Rails

当网站做好了之后,需要部署,部署的方法有很多,这里就简单介绍在 Mac 下用 Nginx + Passenger 部署 Rails 的运行环境。

假设已经配置好了ruby,rails等环境。

1.安装Passenger + Nginx

1
2
3
4
5
6
$ gem install passenger
$ passenger-install-nginx-module

Whichever you choose, if you already have an existing Nginx configuration file,
then it will be preserved.
Enter your choice (1 or 2) or press Ctrl-C to abort:

这里建议选择1

1
Please specify a prefix directory [/opt/nginx]: /usr/local/nginx

当询问nginx的安装路径的时候,个人建议安装到/usr/local/nginx下

当安装完成后,会在console中提示如何配置Nginx
Passenger会自动帮你将下面两行添加到Nginx的配置文件中/usr/local/nginx/conf/nginx.conf(很人性化)

1
2
3
4
5
6
7
8
9
10
11
12
13
http {
...
passenger_root /Users/Daniel/.rvm/gems/ruby-1.9.2-p290/gems/passenger-3.0.10;
passenger_ruby /Users/Daniel/.rvm/wrappers/ruby-1.9.2-p290/ruby;
...
}

server {
listen 80;
server_name www.yourhost.com;
root /somewhere/public; # <--- be sure to point to 'public'!
passenger_enabled on;
}

2.配置Nginx + Passenger + Rails
修改hosts文件,给你的项目一个本地域名, 比如awesome_project.local

1
2
$ sudo vim /etc/hosts
127.0.0.1 awesome_project.local

测试hosts

1
2
$ ping awesome_project.local
PING awesome_project.local (127.0.0.1): 56 data bytes

继续配置Nginx, 这里我给出一个最小可运行的Nginx配置文件

1
$ vim /usr/local/nginx/conf/nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
worker_processes  1;
events {
worker_connections 1024;
}
http {
passenger_root /Users/Daniel/.rvm/gems/ruby-1.9.2-p290/gems/passenger-3.0.10;
passenger_ruby /Users/Daniel/.rvm/wrappers/ruby-1.9.2-p290/ruby;
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name awesome_project.local;
root /Users/Daniel/awesome_project/public;
passenger_enabled on;
rails_env development;
}
}

测试Nginx的配置文件语法是否正确

1
2
3
$ sudo nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

启动Nginx

1
$ sudo nginx

如何在修改Nginx的配置文件后,让Nginx载入新配置

1
$ sudo nginx -s reload

如何停止Nginx

1
$ sudo nginx -s stop

如何在不停Nginx的情况下,重新启动Passenger

1
2
$ cd path/to/your/awesome/project
$ touch tmp/restart.txt

好了,这个时候你可以打开浏览器,访问你的awesome_project网站了

1
http://awesome_project.local

有时候,需要到 /usr/local/nginx/sbin/
执行:

1
Sudo ./nginx

问题来了,启动后一直显示”welcome to nginx”
解决方案:在conf文件里注释掉

1
2
3
4
# location / {
# root html;
# index index.html index.htm;
# }

参考:

通过Nginx在一台服务器上部署两个Rails项目

如何在 Mac 下用 Nginx + Passenger 部署 Rails 的运行环境

Ruby专题