【Copilotの答えの始め】

 

VPSにGunicornとNginxを導入し、SSLを設定する手順を以下にまとめました:

1. VPSの準備

まず、VPSにSSHで接続します。

1
ssh username@server_ip_address

2. 必要なパッケージのインストール

サーバーを最新の状態に更新し、Nginxをインストールします。

1
2
3
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install nginx

Gunicornをインストールします。

1
pip install flask gunicorn

3. Gunicornの設定

Gunicornを使ってFlaskアプリケーションを実行します。まず、wsgi.pyというファイルを作成し、Flaskアプリケーションをインポートします。

1
2
3
4
5
# wsgi.py
from myflaskapp import app

if __name__ == "__main__":
    app.run()

次に、Gunicornを使用してアプリケーションを起動します。

1
gunicorn --bind 0.0.0.0:8000 wsgi:app

4. Nginxの設定

Nginxの設定ファイルを編集します。

1
sudo nano /etc/nginx/sites-available/myflaskapp

以下の設定を追加します:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
server {
    listen 80;
    server_name your_domain_or_IP;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name your_domain_or_IP;

    ssl_certificate /etc/letsencrypt/live/your_domain_or_IP/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/your_domain_or_IP/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /static/ {
        alias /path/to/your/static/files;
    }
}

設定ファイルを有効にし、Nginxを再起動します。

1
2
sudo ln -s /etc/nginx/sites-available/myflaskapp /etc/nginx/sites-enabled
sudo systemctl restart nginx

5. SSLの設定

Let's Encryptを使用してSSL証明書を取得し、Nginxに設定します。

1
2
sudo apt-get install certbot python3-certbot-nginx
sudo certbot --nginx -d your_domain_or_IP

証明書の自動更新を設定します。
 

1
sudo certbot renew --dry-run

これで、VPS上でGunicornとNginxを使用し、SSLで保護されたFlaskアプリケーションが動作するようになります。

 

【Copilotの答えの終わり】

 

 

 

 

花のひら流し去る夜の瀬音雨