CentOS6.3にnode+nginxの環境を構築する

Twitter ツイート Hatena Bookmark ブックマーク

CentOS6.3にnode+nginxの環境を用意しようと思ったのでその見聞録です。

まずはnodeのインストール

1
$ sudo yum install nodejs

今回はyumを使ってインストールするので、上記のコマンドだけで大丈夫です。

npmのインストール

1
$ sudo curl https://npmjs.org/install.sh | sh

npmはyumでインストールではなく、直接install用のシェルを実行するようにします。

ちゃんとインストールされているか確認する

1
2
3
4
5
$ type node
node is /usr/bin/node

$ type npm
npm is /usr/bin/npm

これでちゃんと入っている事が確認できますね。

nginxのインストールためのリポジトリの準備

1
2
3
4
5
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=1

nginxをインストール

1
$ sudo yum install nginx

nginxのconfigファイルのへの変更

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$ sudo cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/hoge.polidog.jp.conf
$ sudo vim /etc/nginx/conf.d/hoge.polidog.jp.conf

upstream backend_node {
    ip_hash;
    server 127.0.0.1:3000;
}

server {
    listen       80;
    server_name  hoge.polidog.jp;
    root /path/to/hoge

    #charset koi8-r;
    charset utf-8;
    access_log /var/log/nginx/access_hoge.poidog.jp.log main;
    error_log /var/log/nginx/errror_hoge.polidog.jp.log;

    location / {
        if (-f $request_filename) {
            break;
        }


        if ( !-f $request_filename ) {
            proxy_pass http://backend_node;
            break;
        }
    }

}

これでやっとnginxの設定ができました。

nginx再起動

1
$ sudo /etc/init.d/nginx restart

ただこれだと問題がありまして。。。リダイレクトがうまく行かないと。。。
proxy_set_headerとかproxy_redirectをoffにすれば解決するので、ということで、以下のようにnginxの設定を書き換えます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
$ sudo vim /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;

    keepalive_timeout  65;

    gzip    on;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_redirect off;

    include /etc/nginx/conf.d/*.conf;


}

これでリダイレクト自体も問題ないかと思います。
さてさて、次はいよいよ、nodejsのデーモン化していこうと思います。

nodejsのデーモン化

nodejsのデーモン化するツールですが、node-demonとかforeverとかあるいっぽいのでとりあえずforeverを入れましょう

1
2
3
$ sudo npm install -g forever
$ cd /path/to/hoge
$ sudo forever start app.js

nodeが無事起動出来たらnginxを再起動

1
$ sudo /etc/init.d/nginx restart

これで無事nginx経由でnodejsが実行できますよー

comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。