CentOS配置mod_wsgi实现Python应用部署
环境准备与依赖安装
执行以下命令安装Apache与开发工具包:
sudo yum install httpd httpd-devel
sudo yum groupinstall "Development Tools"
安装Python开发库(以Python 3为例):
sudo yum install python3-devel
安装mod_wsgi模块
通过pip安装并关联Apache:
sudo pip3 install mod_wsgi
sudo mod_wsgi-express install-module
验证模块加载状态:
httpd -M | grep wsgi
Apache虚拟主机配置
创建配置文件/etc/httpd/conf.d/wsgi.conf
:
<VirtualHost *:80>
ServerName yourdomain.com
WSGIDaemonProcess myapp python-path=/var/www/myapp:/usr/lib/python3.6/site-packages
WSGIProcessGroup myapp
WSGIScriptAlias / /var/www/myapp/app.wsgi
<Directory /var/www/myapp>
Require all granted
</Directory>
</VirtualHost>
应用测试与权限设置
创建测试WSGI脚本app.wsgi
:
def application(environ, start_response):
status = '200 OK'
output = b'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
设置目录权限并重启服务:
sudo chown -R apache:apache /var/www/myapp
sudo systemctl restart httpd
故障排查与优化
- 检查Apache错误日志:
tail -f /var/log/httpd/error_log
- 确认SELinux策略:
setsebool -P httpd_enable_homedirs 1
- 验证防火墙设置:
sudo firewall-cmd --permanent --add-service=http