nginx unit nodejs 模块试用
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