Linux (CentOS) に Django で作成したアプリをデプロイする【AWS】

DjangoAWS,CentOS,Django,Linux,Python

Django で作成したアプリを Linux (CentOS) で公開する手順を解説していきます。

本項の例では AWS の Amazon Linux 2 を使用しています。

Git のインストール

まずはサーバーに Git をインストールしましょう。

依存関係のあるライブラリをインストール

sudo yum -y install gcc curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-ExtUtils-MakeMaker autoconf

wget をインストール

sudo yum -y install wget

Git Releases から最新の Gittar.gz のリンクをコピー

wget https://github.com/git/git/archive/v2.28.0.tar.gz

展開

 tar -zxf v2.28.0.tar.gz

展開後は圧縮ファイルは不要なので削除する

 rm v2.28.0.tar.gz

展開したディレクトリに移動

cd git-2.28.0/

インストール

sudo make prefix=/usr/local all
sudo make prefix=/usr/local install

確認

以下のコマンドで Git のバージョンを確認し、Git のバージョンが表示されれば完了

git --version

pyenv のインストール

依存関係のあるライブラリをインストール

sudo yum install gcc gcc-c++ make git openssl-devel bzip2-devel zlib-devel readline-devel sqlite-devel

pyenv のダウンロード

git clone https://github.com/yyuu/pyenv.git ~/.pyenv

pyenv にパスを通す

echo 'export PYENV_ROOT="${HOME}/.pyenv"' >> ~/.bashrc
echo 'if [ -d "${PYENV_ROOT}" ]; then' >> ~/.bashrc
echo 'export PATH=${PYENV_ROOT}/bin:$PATH' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
echo 'fi' >> ~/.bashrc

.bashrc ファイルを読み込む

source ~/.bashrc

pyenv のインストール可能なバージョンは以下のコマンドで確認できる

pyenv install --list

最新版の python をインストールしてみる

pyenv install 3.9.5

python のバージョンを切り替える

pyenv global 3.9.5

ディレクトリごとに python のバージョンを変えたい場合は適用したいディレクトリで以下のコマンドを実行すればよい。該当のディレクトリ以下全てに適用される。

pyenv local 3.9.5

確認

python -V

MySQL のインストール

MySQL のインストールについては以下のリンクから

Amazon Linux 2 に MySQL をインストールする

uwsgi のインストール

pip install uwsgi

ここでエラーが出た場合は以下のページを参照

pip install xxxx で Command errored out with exit status 1 … のエラーが出たとき

上記ページの操作後に再度 uwsgi のインストールを実行

Django 等のインストール

pip3 install django

確認

python -m django --version

Django Filter のインストール

pip install django-filter

Django Restframework のインストール

pip install djangorestframework

Django Restframework JWT のインストール

pip install djangorestframework-jwt

wheel のインストール

pip install wheel

Nginx のインストール

sudo amazon-linux-extras install nginx1

Nginx 起動

sudo systemctl start nginx

デプロイの準備

プロジェクトを Git から clone

git clone https://github.com/~~~~~~

ここでエラーが出た場合は以下のページを参照

Git 接続でエラーが出たときの手順

一旦確認

python manage.py runserver 0.0.0.0:8000

上記のコマンドを実行後、ブラウザで [サーバーのIPアドレス]:8000 にアクセスしてみる
この時点でタイムアウトになる場合はファイアーウォールでポート8000を通すように設定する。
AWS ではセキュリティグループインバウンドルールの設定を変更する

uwsgi_params を準備する

cd /etc/nginx
cp uwsgi_params <path>/<to>/<django>/<project>(manage.py がおいてある場所)

もし /etc/nginx/ 下に uwsgi_params がなければファイルを作成し、以下のコードを張り付けてください

sudo vim <path>/<to>/<django>/<project>/uwsgi_params
uwsgi_param  QUERY_STRING       $query_string;
uwsgi_param  REQUEST_METHOD     $request_method;
uwsgi_param  CONTENT_TYPE       $content_type;
uwsgi_param  CONTENT_LENGTH     $content_length;

uwsgi_param  REQUEST_URI        $request_uri;
uwsgi_param  PATH_INFO          $document_uri;
uwsgi_param  DOCUMENT_ROOT      $document_root;
uwsgi_param  SERVER_PROTOCOL    $server_protocol;
uwsgi_param  REQUEST_SCHEME     $scheme;
uwsgi_param  HTTPS              $https if_not_empty;

uwsgi_param  REMOTE_ADDR        $remote_addr;
uwsgi_param  REMOTE_PORT        $remote_port;
uwsgi_param  SERVER_PORT        $server_port;
uwsgi_param  SERVER_NAME        $server_name;

conf の設定

sites-available, sites-enabled ディレクトリを作成

sudo mkdir /etc/nginx/sites-available
sudo mkdir /etc/nginx/sites-enabled

conf ファイルを作成して、以下の記述を追加する
各所、書き換える必要のある部分は適宜変更してください

sudo vim /etc/nginx/sites-available/<任意の名前>.conf
# the upstream component nginx needs to connect to
upstream django {
    # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
    server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      8000;
    # the domain name it will serve for
    server_name <IP アドレス または FQDN>;
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /<path>/<to>/<django>/<project>/media;  # Django プロジェクトの media ディレクトリ
    }

    location /static {
        alias /<path>/<to>/<django>/<project>/static; # Django プロジェクトの static ディレクトリ
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /<path>/<to>/<django>/<project>/uwsgi_params; # uwsgi_params のパス
    }
}

この conf ファイルを Django プロジェクトのルートディレクトリにコピーし、そこから sites-enabled へシンボリックリンクを張る

cp /etc/nginx/sites/available/<conf file>.conf ~/<project 名>
sudo ln -s ~/<project 名>/<conf file>.conf /etc/nginx/sites-enabled

nginx.conf の編集

バックアップを作成しておく

/etc/nginx のディレクトリで

sudo cp nginx.conf nginx.conf.org

nginx.conf を編集

sudo vim nginx.conf
~~~

    server {
        charset      utf-8;
#       root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

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

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

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*; // この記述があることを確認。なければ追加
~~~

collectstatic を実行する

manage.py のあるディレクトリで以下のコマンドを実行します

uwsgi でつないでみる

uwsgi --http :8000 --module <project名>.wsgi

ブラウザで [サーバーのIPアドレス]:8000 にアクセス

uwsgi をマニュアルで起動

uwsgi --plugin http,python --socket /path/to/project/uwsgi.sock --module <django_project>.wsgi --chmod-socket=666

ブラウザで http:[サーバーのIPアドレス] を開いてみる → 確認成功

ini ファイルを作成

manage.py があるフォルダで

sudo vim django.ini

ファイルの中に以下の記述を追加し、保存
<project名> 等の部分は適宜変更してください

[uwsgi]
chdir           =  /home/ec2-user/<project名>/
module          =  <project名>.wsgi:application
master          =  True
pidfile         =  django.uwsgi.pid
enable-threads  =  True
#http            =  :8001
socket          =  /home/ec2-user/<project名>/<任意の名前>.sock
processes       =  5
harakiri        =  50
max-requests    =  5000
vacuum          =  True
#home            =  vdjango
daemonize       =  django.uwsgi.log
wsgi-file       =  <project名>.wsgi

uwsgi の起動

uwsgi --ini /path/to/django.ini

Nginx の再起動

sudo systemctl restart nginx

スタイルが効いていないとき

スタイルが正常にあたっていないときは /home/ec2-user/ に実行権限を与える必要があります

sudo chmod o+x /home/ec2-user/