目的
- Nginx を利用し 80 ポートで受けたリクエストを 3000 ポートで起動した Rails アプリに渡す。
前提
- EC2 の OS は Ubuntu
- EC2 の Security Group はポート 80, 3000 を許可
- rails がインストール済み
- nginx がインストール済み
Nginx の動作確認
$ sudo service nginx status
nginx is running
- EC2 の Public DNS でブラウザからアクセス
- ec2-xx-xxx-xxx-xx.ap-northeast-1.compute.amazonaws.com
- Welcome to Nginx! のページが表示される
Rails アプリ動作確認
- サンプルアプリ作成
$ rails new TestApp
- アプリ起動
$ rails s
- ブラウザからアクセス
- ec2-xx-xxx-xxx-xx.ap-northeast-1.compute.amazonaws.com:3000
- Welcome aboard のページが表示される
Nginx の設定ファイル編集
- 設定ファイルを下記のように編集
/etc/nginx/nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
# デフォルトで読み込む設定ファイルを読まないようにする
# include /etc/nginx/conf.d/*.conf;
server {
# リクエストを受けるポート
listen 80;
server_name localhost;
location / {
# 80 ポートで受けたリクエストを 3000 ポートに中継する
proxy_pass http://127.0.0.1:3000;
}
}
}
- 設定ファイルの再読み込み
$ sudo service nginx reload
- Nginx の再起動
$ sudo service nginx restart
- 80 ポートでブラウザからアクセス
- ec2-xx-xxx-xxx-xx.ap-northeast-1.compute.amazonaws.com
- Welcome aboard のページが表示される