LoginSignup
14
18

More than 5 years have passed since last update.

EC2でnode.js + nginx + pm2 + express4のnodeアプリを稼働させる

Posted at

node.js server on EC2

まずは、node.jsの環境を整えます。
今回、利用するバーションは、v0.10.36です。
利用するnode.jsのコードはgitリモートレポジトリ上にあるものとします。

$ sudo yum update -y
$ sudo yum install git gcc-c++ make openssl-devel -y
$ git clone git://github.com/creationix/nvm.git .nvm
$ source ~/.nvm/nvm.sh
$ nvm install v0.10.36
$ nvm alias default v0.10.36
$ vim ~/.bash_profile
if [[ -f ~/.nvm/nvm.sh ]]; then
  source ~/.nvm/nvm.sh
    _nodejs_use_version="v0.10.36"
    if nvm ls | grep -F -e "${_nodejs_use_version}" >/dev/null 2>&1 ;then
      nvm use "${_nodejs_use_version}" >/dev/null
      export NODE_PATH=${NVM_PATH}_modules${NODE_PATH:+:}${NODE_PATH}
    fi
    unset _nodejs_use_version
fi

Setup nginx

$ sudo yum install nginx -y
$ nginx -v
$ sudo chkconfig nginx on
$ sudo service nginx start
$ sudo vim /etc/nginx/conf.d/node-app.conf
upstream node-app {
    server localhost:3000;
}

server {
    listen       80;
    server_name  10.211.55.2;
    proxy_redirect                          off;
    proxy_set_header Host                   $host;
    proxy_set_header X-Real-IP              $remote_addr;
    proxy_set_header X-Forwarded-Host       $host;
    proxy_set_header X-Forwarded-Server     $host;
    proxy_set_header X-Forwarded-For        $proxy_add_x_forwarded_for;
    location / {
        proxy_pass http://node-app/;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {  
    root   /usr/share/nginx/html;
    }
}

$ sudo service nginx restart

アプリケーションのセットアップ

$ git pull origin master nodeapp
$ cd nodeapp
$ npm install

node daemon use pm2

最後にnodeアプリをデーモンとして動かすための設定です。
今回は、express4を利用しているので、サーバーとして起動させるには、./bin/www.jsのようにする必要があります。(元々は、./bin/wwwというファイルになっているので、コピーしてください。)

$ npm install -g pm2
$ pm2 start ./bin/www.js -i max
14
18
0

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
14
18