NGINX Unitを試してみたお話。

なんか、NGINXが「nginx Unit」ってのを発表してたので、何だこいつは?という感覚で触ってみました。

NGINX Unitとは?

NGINX Unit is a dynamic web and application server, designed to run applications in multiple languages. Unit is lightweight, polyglot, and dynamically configured via API. The design of the server allows reconfiguration of specific application parameters as needed by the engineering or operations.

複数の言語で書かれたアプリケーションの構成をAPIを通じて動的に変更できるウェブ・アプリケーションサーバという感じですかね。

特徴

  • Fully dynamic reconfiguration using RESTful JSON API
  • Multiple application languages and versions can run simultaneously
  • Dynamic application processes management (coming soon)
  • TLS support (coming soon)
  • TCP, HTTP, HTTPS, HTTP/2 routing and proxying (coming soon)

REST API経由で、動的に構成を再設定できたり、複数の言語で書かれたアプリケーションを同時に動かすことができる、といった感じです。将来的には、プロセス数の管理?、TLCTCP, HTTP, HTTPS, HTTP/2のルーティングやプロキシができるようにしたいらしい(今は、あるポートにアプリケーションを結びつけるだけ)。

http://unit.nginx.org/

インストール手順

検証では、ubuntuで行いました。また、phpもインストールしました。

$ wget https://nginx.org/keys/nginx_signing.key
$ sudo apt-key add nginx_signing.key
$ sudo echo 'deb https://packages.nginx.org/unit/ubuntu/ xenial unit' >> /etc/apt/sources.list.d/unit.list
$ sudo echo 'deb-src https://packages.nginx.org/unit/ubuntu/ xenial unit' >> /etc/apt/sources.list.d/unit.list
$ sudo apt update
$ sudo apt install unit
$ sudo apt install php unit-php

Installation — NGINX Unit

試してみる

1. ファイルを用意する

$ mkdir {php,php2}
$ echo '<?php echo "Hello world!";' >> php/index.php
$ echo '<?php echo "Hello world 2!";' >> php2/index.php

この状態で、unitdを起動させます。

$ sudo unitd
2018/04/17 22:56:10 [info] 1326#1326 unit started

ここから、設定を追加していきたいと思います。

$ sudo curl -X PUT -d '{"listeners":{"*:8300":{"application":"php"}},"applications":{"php":{"type":"php","root":"/home/user/php","index":"index.php"}}}' --unix-socket /var/run/control.unit.sock http://localhost
{
    "success": "Reconfiguration done."
}

JSONで送るので、シェルでぽんってやるものじゃないですし、絶対にラッパーが直ぐにできると思うのですが、こんなコンフィグを入れると、設定ができます。

$ curl localhost:8300
Hello world!
$ curl localhost:8400
curl: (7) Failed to connect to localhost port 8400: Connection refused

ここから、動的に設定を追加したいと思います。

$ sudo curl -X PUT -d '{"type":"php","root":"/home/user/php2","index":"index.php"}' --unix-socket /var/run/control.unit.sock http://localhost/applications/php2
$ sudo curl -X PUT -d '{"application":"php"}' --unix-socket /var/run/control.unit.sock 'http://localhost/listeners/*:8400'

これで、localhost:8400にアクセスすると、

$ curl localhost:8300
Hello world!
$ curl localhost:8400
Hello world 2!

そして、

$ sudo curl -X DELETE --unix-socket /var/run/control.unit.sock 'http://localhost/listeners/*:8300'

とすると、

$ curl localhost:8300
curl: (7) Failed to connect to localhost port 8300: Connection refused
$ curl localhost:8400
Hello world 2!

まだ把握しきれてない部分

  • 設定を永続化する方法(/var/lib/unitにconf.jsonがあるが、そこに永続化されているっぽい?)
  • REST APIへの送信の仕方(ちょくちょくメソッドだったり、URLを迷ったりする)

感想

割と簡単に動的に構成を変更できるアプリケーションサーバをいじることができたので、機会があれば使ってみたいと思います。