LoginSignup
64

More than 5 years have passed since last update.

さくらのVPSにnginxとNode.jsの環境を構築したメモ

Last updated at Posted at 2016-08-10

サーバ:さくらのVPS 1G HDDプラン
OS:標準OS(CentOS 6 x86_64)

OSのインストール、サーバの起動と初期設定は完了しているものとして。あと、80番ポートをiptablesで開けておく。

nginxのインストール

command
# rpm -ivh http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
# yum -y install nginx

nginxを起動する

command
# /etc/init.d/nginx start

「http://<配布されたグローバルIP>」 にアクセスして、ブラウザの中央に以下のようなものが表示されていればOK。

WS000005.jpg

Node.jsとnpmのインストール

command
# curl -L https://www.npmjs.com/install.sh | sh
# npm update -g npm
# npm cache clean
# npm install -g n
# n stable
# node -v
# npm -v

expressとpm2のインストール

command
# npm install -g express
# npm install -g express-generator
# npm install -g pm2

適当な場所にexpressのプロジェクトを作成する

command
# express sample_app

pm2を利用してexpressのプロジェクトを起動する

command
# cd sample_app
# pm2 start bin/www

動作確認

command
# curl http://localhost:3000

わざわざポートを開けて、あれこれするのが面倒だったため、curlで内部から動作確認するのみで。HTMLのタグが表示され、さらに「Express」と書かれている部分があればOK。

nginxの設定ファイルを修正する

command
# cd /etc/nginx/conf.d
# vi default.conf
/etc/nginx/conf.d/default.conf
upstream node-backend {
    server localhost:3000;
}

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;
    charset utf-8;
    access_log /var/log/nginx/default.access.log main;
    error_log /var/log/nginx/default.error.log;

    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 / {
        #root   /usr/share/nginx/html;
        #index  index.html index.htm;
        proxy_pass http://node-backend;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    #(以下略)
}

nginxを再起動する。

command
# /etc/init.d/nginx restart

先ほどのページに再度アクセスし、ブラウザの左側に以下のような表示がされれば、全て終了。お疲れさまでした。

WS000006.jpg

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
64