Flask+uWSGI+NginxでAPIを実装する方法まとめ

Flask + uWSGI + Nginx で API を実装する方法をまとめました。

スポンサーリンク

Nginx インストール

まずは Nginx をインストールして問題なく動くことを確認します。

$ sudo apt install -y nginx
$ sudo systemctl start nginx
$ curl http://localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

Nginx 設定ファイル編集

/etc/nginx.nginx.conf に include /etc/nginx/conf.d/*.conf; と書かれているので /etc/nginx/conf.d/ に uWSGI 用の設定ファイルを作成します。

$ sudo vi /etc/nginx/conf.d/api.conf
server {
    listen       80;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:///tmp/uwsgi.sock;
    }
}

Nginx のデフォルトサイト無効化

/etc/nginx/sites-enabled/default にデフォルトサイトの設定があり、nginx.conf で include しているのでコメントアウトします。

$ sudo vi /etc/nginx/nginx.conf
- include /etc/nginx/sites-enabled/*;
+ #include /etc/nginx/sites-enabled/*;

uWSGI 起動

uWSGI + Flask は下記記事で既に実装済みとします。

$ uwsgi --socket=/tmp/uwsgi.sock --wsgi-file=app.py --callable=app --chmod-socket=666
$ curl http://localhost/hello
{'message': 'Hello world!'}

これで Flask + uWSGI + Nginx で API を実行出来るようになりました。

uWSGI 設定

引数を ini にまとめるとすっきりします。

$ vi uwsgi.ini
$ uwsgi uwsgi.ini
[uwsgi]

wsgi-file=app.py
callable=app
http=0.0.0.0:8000
socket=/tmp/uwsgi.sock
chmod-socket=666

タイトルとURLをコピーしました