19
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NGINX Unitでpython wsgiサーバーを動かす

Last updated at Posted at 2017-09-08

NGINX Unitが公開されて、Python用のWSGIを動かすアプリケーションサーバーとして使っていけるかなぁという感じです。とりあえずHello Worldを動かしてみました。

ためした環境

  • vagrant
  • ubuntu/xenial64
  • python3.5

NGINX Unitのインストール

こちらを参考にubuntuパッケージ版をインストール。
https://github.com/nginx/unit#ubuntu-packages

そして起動

$ sudo service unitd start

pythonアプリケーションの作成

pythonアプリケーションはwsgiで作成する。指定したパスにwsgi.pyというファイルを配置して、あとはwsgiの流儀に従うだけ。wsgiで作ればいいのでフレームワークなんかは自由。

wsgi.py
def application(environ, start_response):
	start_response('200 OK', [('Content-Type', 'text/plain')])
	return ['Hello World\n'.encode('utf-8')]

設定ファイルの記述

配置してあるファイルを変更するのではなく、APIで設定を通知するという感じの使い方になるので、設定ファイルを記述してそれをアップロードして設定を反映させる。

start.json
{
	"applications": {
		"hello": {
			"type": "python",
			"workers": 2,
			"path": "/home/ubuntu",
			"module": "wsgi"
		}
	},

	"listeners": {
		"*:8400": {
			"application": "hello"
		}
	}
}

設定の反映

制御のAPIはunixソケットでAPIを叩く。
参照: https://github.com/nginx/unit#configuration

記述した設定ファイルをcurlでアップロードして反映させる。

$ sudo curl -X PUT -d @start.json --unix-socket /var/run/control.unit.sock http://localhost/

もしくは、ubuntuのパッケージインストールではそれをしてくれるスクリプトが用意されているので、それを使うと楽。

$ sudo service unitd restoreconfig start.json

GETでリクエストすれば、設定が取得できる。

$ sudo curl --unix-socket /var/run/control.unit.sock http://localhost/
{
	"applications": {
		"hello": {
			"type": "python",
			"workers": 2,
			"path": "/home/ubuntu",
			"module": "wsgi"
		}
	},

	"listeners": {
		"*:8400": {
			"application": "hello"
		}
	}
}

unitdが設定ファイルを持ったりしてないので、再起動するたびに反映させる必要がある。

動作の確認

8400ポートでアプリケーションが動くように設定したので、そこにcurlでHTTPリクエストをなげると結果が得られた。

$ curl http://localhost:8400/
Hello World              

uWSGIなどと比べると機能が圧倒的にすくないけど、これから多機能になっていくかもしれませんね。
virtualenv/venv で使うのは今後でてくるでしょうか。

19
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?