Ubuntu 20.04でuWSGIとNginxを使用してFlaskアプリケーションをデプロイする方法
Flaskは、アルミン・ロンカーシャーによって開発されたPythonで書かれたマイクロウェブフレームワークです。マイクロフレームワークと呼ばれるのは、特別なツールやライブラリを必要としないからです。FlaskはPythonモジュールで、ウェブアプリケーションを簡単に開発するための小さく、拡張が容易なコアを持っています。
このチュートリアルでは、Ubuntu 20.04でUwsgiとNginxを使用してFlaskアプリケーションをデプロイする方法を学びます。
前提条件
- Ubuntu 20.04を実行しているサーバー。
- サーバーIPにポイントされた有効なドメイン名。
- サーバーにルートパスワードが設定されています。
始めに
最初に、システムパッケージを最新バージョンに更新することをお勧めします。次のコマンドを実行することで更新できます。
apt-get update -yすべてのパッケージが更新されたら、次のステップに進むことができます。
必要な依存関係をインストールする
次に、Flaskアプリケーションをデプロイするために必要な依存関係をインストールする必要があります。以下のコマンドでそれらすべてをインストールできます:
apt-get install nginx python3-pip python3-dev python3-venv build-essential libssl-dev libffi-dev python3-setuptools -yすべてのパッケージがインストールされると、次のステップに進むことができます。
仮想環境を作成する
次に、Flaskアプリケーションのために仮想環境を作成する必要があります。仮想環境は、孤立したPython環境を作成するために使用される非常に便利なツールです。これにより、プロジェクトに特定のバージョンのPythonをインストールすることができます。
まず、次のコマンドを使ってFlaskアプリケーションのディレクトリを作成します:
mkdir /var/www/html/myapp次に、ディレクトリをmyappに変更し、以下のコマンドで新しいPython仮想環境を作成します:
cd /var/www/html/myapp
python3.8 -m venv myappenv次に、以下のコマンドで仮想環境をアクティブにします:
source myappenv/bin/activateFlaskアプリケーションをセットアップする
この時点で、Pythonの仮想環境はFlaskアプリケーションの展開の準備が整っています。次に、仮想環境内にFlaskアプリをセットアップする必要があります。
まず、次のコマンドでFlaskとuWSGIをインストールします:
pip install uwsgi flask次に、以下のコマンドで myapp.py というサンプルアプリケーションを作成します:
nano /var/www/html/myapp/myapp.py次の行を追加してください:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "<h1 style='color:blue'>Hi This is My Flask Application</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0')
作業が終わったら、ファイルを保存して閉じてください。次に、以下のコマンドでFlaskアプリケーションを実行します:
python /var/www/html/myapp/myapp.py次の出力が表示されるはずです:
* Serving Flask app "myapp" (lazy loading)
* Environment: production
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
今、ウェブブラウザを開き、URL http://your-server-ip:5000 を使用してFlaskアプリケーションにアクセスしてください。次の画面が表示されるはずです:
さて、Flaskアプリケーションを停止するには、ターミナルでCTRL + Cを押してください。
uWSGIを設定する
まず、uWSGIサーバーがどのように対話するかを指示するWSGIエントリーポイントを作成します。
nano /var/www/html/myapp/wsgi.pyアプリケーションからFlaskインスタンスをインポートするために、次の行を追加してください。
from myapp import app
if __name__ == "__main__":
app.run()
作業が終わったらファイルを保存して閉じ、その後に以下のコマンドを使用してuWSGIがアプリケーションを提供できるかテストします:
uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi:app今、URL http://your-server-ip:5000 を使用してアプリケーションに再度アクセスしてください。次の画面が表示されるはずです:
今、CTRL + Cを押してアプリケーションを停止してください。
次に、仮想環境から退出するために以下のコマンドを実行します:
deactivateuWSGIを設定する
この時点で、uWSGIはあなたのアプリケーションを提供できる状態です。次に、以下のコマンドでuWSGIの設定ファイルを作成してください:
nano /var/www/html/myapp/myapp.ini次の行を追加してください:
[uwsgi]
module = wsgi:app
master = true
processes = 5
socket = myapp.sock
chmod-socket = 660
vacuum = true
die-on-term = true
作業が完了したら、ファイルを保存して閉じてください。
Systemdサービスファイルを作成する
次に、uWSGIサービスを管理するためのsystemdサービスファイルを作成する必要があります。以下のコマンドで作成できます:
nano /etc/systemd/system/myapp.service次の行を追加してください:
[Unit]
Description=uWSGI instance to serve myapp
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/html/myapp
Environment="PATH=/var/www/html/myapp/myappenv/bin"
ExecStart=/var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
[Install]
WantedBy=multi-user.target
作業が完了したらファイルを保存して閉じ、その後以下のコマンドでsystemdデーモンを再読み込みします:
systemctl daemon-reload次に、アプリケーションの所有権をwww-dataに変更し、次のコマンドで適切な権限を設定します:
chown -R www-data:www-data /var/www/html/myapp
chmod -R 775 /var/www/html/myapp次に、アプリケーションを起動し、次のコマンドを使ってシステム再起動時に自動起動するように設定します:
systemctl start myapp
systemctl enable myapp次のコマンドでアプリケーションのステータスを確認することもできます:
systemctl status myapp次の出力を得るべきです:
? myapp.service - uWSGI instance to serve myapp
Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: enabled)
Active: active (running) since Sun 2020-09-13 08:38:08 UTC; 1min 53s ago
Main PID: 662796 (uwsgi)
Tasks: 6 (limit: 4691)
Memory: 21.8M
CGroup: /system.slice/myapp.service
??662796 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662808 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662809 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662810 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662811 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662812 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
Sep 13 08:38:08 ubunt4 uwsgi[662796]: WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x55e207e7a510 pid: 662796 (default app)
Sep 13 08:38:08 ubunt4 uwsgi[662796]: *** uWSGI is running in multiple interpreter mode ***
Sep 13 08:38:08 ubunt4 uwsgi[662796]: spawned uWSGI master process (pid: 662796)
Sep 13 08:38:08 ubunt4 uwsgi[662796]: spawned uWSGI worker 1 (pid: 662808, cores: 1)
Sep 13 08:38:08 ubunt4 uwsgi[662796]: spawned uWSGI worker 2 (pid: 662809, cores: 1)
Sep 13 08:38:08 ubunt4 uwsgi[662796]: spawned uWSGI worker 3 (pid: 662810, cores: 1)
Sep 13 08:38:08 ubunt4 uwsgi[662796]: spawned uWSGI worker 4 (pid: 662811, cores: 1)
Sep 13 08:38:08 ubunt4 uwsgi[662796]: spawned uWSGI worker 5 (pid: 662812, cores: 1)
Nginxをリバースプロキシとして設定する
次に、Flaskアプリケーションを提供するためにNginxをリバースプロキシとして設定する必要があります。次のコマンドを使用して実行できます:
nano /etc/nginx/sites-available/flask.conf次の行を追加してください:
server {
listen 80;
server_name flask.example.com;
location / {
include uwsgi_params;
uwsgi_pass unix:/var/www/html/myapp/myapp.sock;
}
}
作業が完了したら、ファイルを保存して閉じてください。次に、次のコマンドを使用してNginxの構文エラーを確認します:
nginx -t次の出力が表示されるはずです:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
次に、次のコマンドを使用してNginxの仮想ホストを有効にします:
ln -s /etc/nginx/sites-available/flask.conf /etc/nginx/sites-enabled/最後に、変更を適用するためにNginxサービスを再起動します:
systemctl restart nginxこの時点で、NginxはあなたのFlaskアプリケーションを提供するように設定されています。
Let's Encrypt SSLを使用してFlaskアプリケーションをセキュアにする
次に、Let's Encrypt の無料 SSL でアプリケーションを保護することをお勧めします。まず、SSL 証明書をインストールして管理するために Certbot クライアントをインストールする必要があります。次のコマンドでインストールできます:
apt-get install python3-certbot-nginx -yインストールが完了したら、次のコマンドを実行してLet's Encrypt SSLでウェブサイトを保護してください。
certbot --nginx -d flask.example.com有効なメールアドレスを提供し、以下に示す利用規約に同意するよう求められます。
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): [email
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for flask.example.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/flask.conf
次に、以下のようにHTTPトラフィックをHTTPSにリダイレクトするかどうかを選択してください:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
2を入力してEnterキーを押してインストールを完了してください。以下の出力が表示されるはずです:
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/flask.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://flask.example.com
You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=flask.example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/flask.example.com/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/flask.example.com/privkey.pem
Your cert will expire on 2020-10-30. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. To non-interactively renew *all* of
your certificates, run "certbot renew"
- Your account credentials have been saved in your Certbot
configuration directory at /etc/letsencrypt. You should make a
secure backup of this folder now. This configuration directory will
also contain certificates and private keys obtained by Certbot so
making regular backups of this folder is ideal.
- If you like Certbot, please consider supporting our work by:
Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le
- We were unable to subscribe you the EFF mailing list because your
e-mail address appears to be invalid. You can try again later by
visiting https://act.eff.org.
今、あなたのFlaskウェブサイトはLet's Encrypt SSLで保護されています。URL https://flask.example.com を使用してFlaskアプリケーションにアクセスできます。
結論
おめでとうございます!FlaskアプリケーションをuWSGIとNginxを使って正常にデプロイし、Let's Encrypt SSLで安全にしました。これで、Flaskを使ってPythonアプリを簡単に開発・デプロイできます。質問があれば気軽にお尋ねください。
