nginx unit nodejs 模組試用
阿新 • • 發佈:2018-11-08
unit 對於nodejs 的支援是在10.25 釋出的,基本能用,但是依然有好多問題,當前在測試的時候就發現,請求之後會block ,
相關的issue 已經有人反饋了,最好使用原始碼編譯,方便測試,當前使用yum 的安裝包會有點問題(block)
使用的作業系統是centos7
環境準備
- 配置yum源
/etc/yum.repos.d/unit.repo [unit] name=unit repo baseurl=https://packages.nginx.org/unit/centos/$releasever/$basearch/ gpgcheck=0 enabled=1
- 安裝unit 以及需要的語言支援
yum install unit-php unit-python unit-go unit-perl unit-devel unit
- 安裝nodejs
yum install -y nodejs
升級node 版本
npm insatll -g n
n 8.11.4
- 安裝node-addon 構建依賴
yum install gcc-c++
基本專案
- nodejs 專案結構(為了測試集成了php),目錄/opt/nodejs
├── app.js ├── blogs │ └── index.php ├── package.json └── unit.json
- 程式碼說明
package.json { "name": "nodejs", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": { "express": "^4.16.4", "unit-http": "^1.5.1" } } app.js: 使用unit 的http 模組託管管理http server #!/usr/bin/env node const { createServer, IncomingMessage, ServerResponse, } = require('unit-http') require('http').ServerResponse = ServerResponse require('http').IncomingMessage = IncomingMessage const express = require('express') const app = express() app.get('/', (req, res) => { res.set('X-Unit-Type', 'Absolute') res.send('Hello, Unit!') }) createServer(app).listen() index.php <?php echo "php demo website" ?> unit.json unit 服務配置檔案 { "listeners": { "*:8080": { "application": "hello-unit" }, "*:8300": { "application": "blogs" } }, "applications": { "hello-unit": { "type": "external", "working_directory": "/opt/nodejs", "executable": "app.js", "processes":5 }, "blogs": { "type": "php", "processes": 5, "root": "/opt/nodejs/blogs", "index": "index.php" } } }
服務啟動&&測試
- 啟動服務(使用systemd 管理修改了啟動controller 訪問地址)
cat /etc/sysconfig/unit
UNITD_OPTIONS="--log /var/log/unit.log --pid /run/unit.pid --control 0.0.0.0:9000"
systemctl restart unit
- 註冊服務
curl -X PUT -d @$PWD/start.json http://localhost:9000/config
- 檢視結果
說明
現在的版本已經挺不錯了,支援狀態管理,預設在/var/lib/unit/conf.json,重啟之後服務可以自動註冊。
目前測試nodejs 模組是有點問題的,請求之後會block https://github.com/nginx/unit/issues/175
格式如下:
{"listeners":{"*:8080":{"application":"hello-unit"},"*:8300":{"application":"blogs"}},"applications":{"hello-unit":{"type":"external","working_directory":"/opt/nodejs","executable":"app.js","processes":5},"blogs":{"type":"php","processes":5,"root":"/opt/nodejs/blogs","index":"index.php"}}}
參考資料
https://github.com/nginx/unit/issues/175
https://unit.nginx.org/installation/#node-js-package
https://unit.nginx.org/configuration/
https://medium.com/house-organ/what-an-absolute-unit-a36851e72554