跳转至

🔥AI副业赚钱星球

点击下面图片查看

郭震AI

生产环境中部署 Flask 应用程序

为了在生产环境中部署 Flask 应用程序,建议使用 WSGI 服务器,如 Gunicorn、uWSGI 或 mod_wsgi。以下是使用 Gunicorn 的步骤:

1. 安装 Gunicorn

首先,确保您已经安装了 Gunicorn。您可以使用 pip 进行安装:

pip install gunicorn

2. 配置 Gunicorn 启动脚本

创建一个 Gunicorn 启动脚本,例如 run_gunicorn.sh

#!/bin/bash

source ~/miniconda3/etc/profile.d/conda.sh
conda activate mend
exec gunicorn -b 0.0.0.0:5000 runapp:app

确保 app:app 指向您的 Flask 应用。

image-20240703181650704

我的 runapp.py内容如下:

from app import create_app

app = create_app()

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

📢 注意1:

Gunicorn 使用的 Python 环境可能与 pip list 中显示的环境不同。确保你的 Gunicorn 使用的是正确的虚拟环境。

在这里我的虚拟环境是conda管理下的 mend.

📢 注意2:

若gunicorn的安装路径为如下:

/home/bitnami/.local/bin/gunicorn

需要调整run_gunicorn.sh脚本为:

#!/bin/bash

source ~/miniconda3/etc/profile.d/conda.sh
conda activate mend
exec /home/bitnami/miniconda3/envs/mend2word/bin/gunicorn -b 0.0.0.0:5000 runapp:app

/home/bitnami/miniconda3/envs/mend/bin/gunicorn 必须要和当前虚拟环境同一路径,目前都位于mend虚拟环境下。

📢 注意3:

runapp.py模块的名字不要起名为 app.py,会有问题。

3. 使脚本可执行

确保脚本具有可执行权限:

chmod +x run_gunicorn.sh

4. 修改 Apache 配置文件

将您的 Apache 配置文件 chat-ex.com.conf 修改为使用 Gunicorn。假设 Gunicorn 在端口 5000 上运行,配置文件如下:

<VirtualHost *:80>
    ServerName chat-ex.com

    ProxyPreserveHost On
    ProxyPass / http://localhost:5000/
    ProxyPassReverse / http://localhost:5000/

    ErrorLog ${APACHE_LOG_DIR}/chat-ex.com_error.log
    CustomLog ${APACHE_LOG_DIR}/chat-ex.com_access.log combined

    # Redirect all HTTP requests to HTTPS
    Redirect permanent / https://chat-ex.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName chat-ex.com

    ProxyPreserveHost On
    ProxyPass / http://localhost:5000/
    ProxyPassReverse / http://localhost:5000/

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/chat-ex.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/chat-ex.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf

    ErrorLog ${APACHE_LOG_DIR}/chat-ex.com_error.log
    CustomLog ${APACHE_LOG_DIR}/chat-ex.com_access.log combined
</VirtualHost>

5. 启动 Gunicorn

在后台启动 Gunicorn:

nohup ./run_gunicorn.sh > gunicorn.log 2>&1 &

6. 重启 Apache

最后,重启 Apache 服务器以应用配置更改:

sudo systemctl restart apache2

通过这些步骤,您的 Flask 应用程序将通过 Gunicorn 在生产环境中运行,并且可以通过 HTTPS 访问。

以上全文,欢迎继续阅读学习

大家在看

京ICP备20031037号-1 | AI之家 | AI资讯 | Python200 | 数据分析