LoginSignup
23
39

More than 5 years have passed since last update.

Pythonサーバーの設定(nginx + Gunicorn)

Last updated at Posted at 2015-03-30

2014年に調べて、個人的にこれだっていう、PythonのAPIサーバーの設定。

nginxをフロントに立てて、アプリケーションサーバーにgunicornを使って、リバースプロキシする。

ちょっと古いけど、instagramを参考にしてこれに決めた。INSTAGRAM ENGINEERING

AWS EC2に設定した時のメモ。

gunicornのインストール

virtualenv上でpipを使ってインストール。
virtualenvは、OSのPythonをいじるとyumが動かなくなっちゃたりするのが嫌なのと、Pythonのバージョンをあげたかったりするんで使用。

gunicornを起動時に立ち上げるようにする

あんまり詳しくないけど、upstartに登録。

以下の設定ファイルを記述。

/etc/init/myapp.conf
description "[APP NAME] API Server"

start on runlevel [2345]
stop on runlevel [016]

respawn

script
su - www
/home/www/[APP NAME]/virtualenv/bin/gunicorn -b 127.0.0.1:8000 -w 4 -u www --chdir /home/www/[APP NAME]/server/python --log-file /home/www/[APP NAME]/logs/error_log --pythonpath /home/www/[APP NAME]/server/python server:application
end script

centos7の時は、upstartが入ってないんで、systemctlに設定する。
設定ファイルも含めて、Gunicornのサイトに載ってる。

参考:Deploying Gunicorn - Gunicorn 19.3.0 documentation

nginxのインストール

yumでインストール。

nginxの設定ファイル。

/etc/nginx/nginx.conf
user  www;
worker_processes  1;

error_log  /var/log/nginx/error.log;

pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    sendfile        on;

    keepalive_timeout  65;

    include /etc/nginx/conf.d/*.conf;

    index   index.html;

    upstream app_server {
        server 127.0.0.1:8000 fail_timeout=0;
    }

    server {
        listen       80;
        server_name  [DOMAIN];
        root         /home/www/[APP NAME]/server/html;

        access_log  /var/log/nginx/[APP NAME].access.log  main;

        location / {
            try_files $uri @proxy_to_app;
        }

        location @proxy_to_app {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass   http://app_server;
        }

        error_page  404              /404.html;
        location = /40x.html {
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
        }

    }

}

主な設定内容は、以下の2つ。

  • nginx用のユーザー(www)を作って、そのユーザーでnginxを動かすようにする。
  • 物理ファイルがないとき、全部のリクエストをgunicorn(127.0.0.1:8000) にリバースプロキシ。
23
39
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
23
39