LoginSignup
67
65

More than 5 years have passed since last update.

CentOSにNodeJS+nginxの環境を構築する

Posted at

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

  1. まずはnodeのインストール
$ sudo yum install nodejs

これだけでおkです。
 
2. 次にnpmのインストール

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

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

$ type node
node is /usr/bin/node

$ type npm
npm is /usr/bin/npm

これでちゃんと入っている事が確認できますね。
 
4. nginxのインストールためのリポジトリの準備

$ sudo /etc/yum.repos.d/nginx.conf

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

 
5. インストール

$ sudo yum install nginx

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

$ 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の設定ができました。
 
7. nginx再起動

$ sudo /etc/init.d/nginx restart

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

$ 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のデーモン化していこうと思います。
 
8. nodejsのデーモン化
nodejsのデーモン化するツールですが、node-demonとかforeverとかあるいっぽいのでとりあえずforeverを入れましょう

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

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

$ sudo /etc/init.d/nginx restart

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

67
65
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
67
65