nginx unit nodejs 模块试用(续)

最新(应该是18 年了)nginx unit 发布了新的版本,对于nodejs 的支持有很大的改进,上次测试过,问题还是
比较多,这次使用新版本在测试下对于nodejs 的支持,以及以前block 的问题。
备注: 测试系统centos 7

环境准备

  • 配置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",
      "user":"root",
      "group":"root",
      "working_directory": "/opt/nodejs",
      "executable": "app.js",
      "processes":5
    },
    "blogs": {
            "type": "php",
            "processes": 5,
            "user":"root",
           "group":"root",
            "root": "/opt/nodejs/blogs",
            "index": "index.php"
     }
  }
}

服务启动&&测试

  • 启动服务(使用systemd 管理修改了启动controller 访问地址),注意app.js 可能需要添加执行权限
chmod +x app.js  实际参考提示的信息
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/unit.json http://localhost:9000/config
  • 查看结果


说明

现在的版本已经挺不错了,支持状态管理,默认在/var/lib/unit/conf.json,重启之后服务可以自动注册。
通过测试,以前版本block 的问题,以及解决了,还是很不错的,但是实际对于其他框架支持的程度
还是需要测试的。
格式如下:

{"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

猜你喜欢

转载自www.cnblogs.com/rongfengliang/p/10357027.html