サーバーに Node.js と Nginx をセットアップしました。これから使用したいのですが、始める前に 2 つの質問があります。
- 彼らはどのように連携すればよいでしょうか? リクエストにはどのように対処すればよいでしょうか?
Node.js サーバーには 2 つのコンセプトがありますが、どちらが優れているでしょうか。
a. 必要な Web サイトごとに個別の HTTP サーバーを作成します。次に、プログラムの開始時にすべての JavaScript コードをロードして、コードが 1 回解釈されるようにします。
b. すべての Node.js リクエストを処理する単一の Node.js サーバーを作成します。これは、要求されたファイルを読み取り、その内容を評価します。したがって、ファイルはリクエストごとに解釈されますが、サーバーのロジックははるかに単純になります。
Node.js を正しく使用する方法がわかりません。
ベストアンサー1
Nginx はフロントエンド サーバーとして機能し、この場合はリクエストを node.js サーバーにプロキシします。そのため、node 用の Nginx 構成ファイルを設定する必要があります。
これは私が Ubuntu ボックスで行ったことです:
yourdomain.example
次の場所にファイルを作成します/etc/nginx/sites-available/
:
vim /etc/nginx/sites-available/yourdomain.example
そこには次のような内容が含まれているはずです:
# the IP(s) on which your node server is running. I chose port 3000.
upstream app_yourdomain {
server 127.0.0.1:3000;
keepalive 8;
}
# the nginx server instance
server {
listen 80;
listen [::]:80;
server_name yourdomain.example www.yourdomain.example;
access_log /var/log/nginx/yourdomain.example.log;
# pass the request to the node.js server with the correct headers
# and much more can be added, see nginx config options
location / {
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_pass http://app_yourdomain/;
proxy_redirect off;
}
}
Nginx (>= 1.3.13) で websocket リクエストも処理する場合は、location /
セクションに次の行を追加します。
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
この設定が完了したら、上記の設定ファイルで定義されているサイトを有効にする必要があります。
cd /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/yourdomain.example yourdomain.example
ノードサーバーアプリをここで作成し/var/www/yourdomain/app.js
、ここで実行します。localhost:3000
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
構文エラーをテストします。
nginx -t
Nginxを再起動します。
sudo /etc/init.d/nginx restart
最後にノード サーバーを起動します。
cd /var/www/yourdomain/ && node app.js
これで「Hello World」が表示されるはずです。yourdomain.example
ノードサーバを起動する際の最後の注意点:ノードデーモンには何らかの監視システムを使用する必要があります。素晴らしいupstart と monit を使用したノードのチュートリアル。