在Ubuntu系统中部署Python Web应用,并希望在系统启动时自动运行,可以使用生产级别的WSGI服务器,如uWSGI或Gunicorn。以下是使用Gunicorn作为服务启动的例子:
步骤1:安装Gunicorn
假设您的项目在一个虚拟环境中(例如my_env
),并且您的Flask(或Django)应用已经准备就绪。
# 激活您的虚拟环境
source /path/to/anaconda/envs/my_env/bin/activate
# 在虚拟环境中安装Gunicorn
pip install gunicorn
步骤2:创建Gunicorn的Systemd服务
创建一个新的Systemd服务文件在 /etc/systemd/system/my_app.service
:
[Unit]
Description=Gunicorn Server for My Application
After=network.target
[Service]
User=your_user
Group=www-data
WorkingDirectory=/path/to/your/project
Environment="PATH=/path/to/anaconda/envs/my_env/bin"
ExecStart=/path/to/anaconda/envs/my_env/bin/gunicorn --workers 3 --bind unix:/run/my_app.sock -m eventlet myproject.wsgi
Restart=on-failure
SyslogIdentifier=my_app
[Install]
WantedBy=multi-user.target
请将 myproject.wsgi
替换为您的实际WSGI入口点(对于Flask,可能是 my_flask_app:app
;对于Django,可能是 my_django_project.wsgi:application
)。
步骤3:启动并启用服务
使Systemd加载新创建的服务文件并启动服务:
sudo systemctl daemon-reload
sudo systemctl start my_app.service
sudo systemctl enable my_app.service
步骤4:配置Nginx作为反向代理(可选)
如果还需要通过Nginx进行负载均衡或提供静态文件服务,请创建或修改Nginx的配置文件(通常在 /etc/nginx/sites-available/my_app.conf
):
server {
listen 80;
server_name your_domain.com;
location / {
include proxy_params;
proxy_pass http://unix:/run/my_app.sock;
}
}
然后链接到sites-enabled目录并检查配置:
sudo ln -s /etc/nginx/sites-available/my_app.conf /etc/nginx/sites-enabled/
sudo nginx -t
最后,重启Nginx以应用更改:
sudo systemctl restart nginx
现在,当系统启动时,Gunicorn会自动运行您的Python Web应用,并且可以透过Nginx访问。
当前文章价值9.44元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)
评论已关闭!