2017年5月22日月曜日

Node.jsを使ってみる

最近急にMastodonが流行り始めました。
Mastodon自体の説明については他に譲るとして、
Mastodonではウェブサーバ(ストリーミング用)に
Node.jsを利用しているようです。
Node.jsはウェブのフロントエンドで育まれたJavaScriptを
サーバでも使おうという発想で生まれたウェブサーバではありますが、
私が愛用するApacheウェブサーバとの同居が面倒なため
これまで避けておりました。
しかしMastodonという動機付けでもって
この度Node.jsを使ってみる気になりました。

さて今回Node.jsをセットアップするのはServersMan@VPSで
借りているUbuntu 14.04ベースのリモートサーバです。
以下を実行します。
$ su -
# apt-get update
# apt-get install nodejs npm
# npm cache clean
# npm install n -g
# n stable
# exit
ここで適当なディレクトリにファイル"helloworld.js"を
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(8031,"<ホスト名>");
console.log('running helloworld.js');
の内容で作成します。
ちなみにポート番号を8031にしているのは、
ポート番号一覧で8030~8040あたりが空いているからで、
それ以上の意味はありません。
そして
$ node helloworld.js
を実行し、ウェブブラウザで"http://<ホスト名>:8031"を開きます。
なおホスト名は先のファイルで指定したそのものでなくてもよく、
DNSサーバ上で付けている別名でも構いません。
結果、ブラウザには
Hello World
とだけ表示されます。
Node.jsの動作確認ができました。

ところで"helloworld.js"を
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World 8031\n');
}).listen(8031,"<ホスト名>");

var http1 = require('http');
http1.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World 8032\n');
}).listen(8032,"<ホスト名>");

console.log('running helloworld.js');
のようにすると8031番ポートと8032番ポートで別コンテンツを
同時に公開できます。
ただし、この中の
}).listen(8032,"<ホスト名>");
}).listen(8031,"<別のホスト名>");
にしてもバーチャルホストは実現できません。
ポート番号の重なりでエラーが出るだけです。

SSLについても対応可能です。
先の"helloworld.js"の第2段落を
var https = require('https');
var fs = require('fs');
var ssl = {
    cert: fs.readFileSync('cert.pem'),
    key: fs.readFileSync('privkey.pem')
};
https.createServer(ssl, function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('ssl\n');
}).listen(8032,"<ホスト名>");
に変更し、それと同一ディレクトリに
証明書情報の"cert.pem"と"privkey.pem"を置いて、
パーミッションをきちんと設定すれば完了です。
証明書情報は、もしLet's Encryptから
Linux上のApache向けに発行を受けているのなら、
"/etc/apache2/ssl/letsencrypt/live/<ホスト名>/"ディレクトリ下に
同名のファイルで存在するので、そのままコピーします。
ただしパーミッションには注意が必要です。

最後にデーモン化について。
$ node helloworld.js
では[Ctrl]+[c]やログアウトで終了してしまうので、
# npm install forever -g
で"forever"コマンドをインストールして
$ forever start helloworld.js
でウェブサーバを起動するようにします。
$ forever stop helloworld.js
を実行すれば止められます。

0 件のコメント:

コメントを投稿