1. 项目背景与核心挑战
这个在线教育平台项目基于Django+Xadmin架构,需要部署到CentOS 6.5生产环境。作为2013年发布的操作系统,CentOS 6.5默认只提供Python 2.6.6,而我们的Django项目需要Python 3.5.1环境。这种新旧技术栈的碰撞带来了几个关键挑战:
- 系统兼容性问题:CentOS 6.5的glibc版本(2.12)较老,直接编译安装Python 3.5.1会遇到各种依赖缺失
- 服务隔离需求:生产环境需要与系统Python环境完全隔离,避免影响其他服务
- 性能优化要求:线上环境需要配置Gunicorn+Nginx的高性能组合
- 安全加固标准:需要按照企业级安全规范配置防火墙、SELinux等
2. 环境准备与依赖解决
2.1 系统基础配置
首先更新系统并安装基础开发工具:
yum -y update yum groupinstall -y "Development tools" yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel注意:CentOS 6.5的默认yum源可能已失效,需要先备份并更新repo配置:
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo yum clean all yum makecache2.2 Python 3.5.1源码编译
下载并编译Python 3.5.1:
cd /usr/local/src wget https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz tar xzf Python-3.5.1.tgz cd Python-3.5.1配置编译参数时需特别注意:
./configure --prefix=/usr/local/python3.5 \ --enable-optimizations \ --with-ensurepip=install \ --enable-shared关键参数说明:
--enable-shared:生成动态链接库,供其他程序调用--with-ensurepip:自动安装pip包管理工具--enable-optimizations:启用PGO优化,提升运行时性能
编译安装:
make -j $(nproc) make altinstall避坑指南:如果遇到"Could not build the ssl module"错误,需要先安装openssl-devel:
yum install -y openssl-devel rm -rf Python-3.5.1 tar xzf Python-3.5.1.tgz cd Python-3.5.13. 虚拟环境与项目部署
3.1 创建隔离环境
为避免污染系统环境,使用virtualenv创建独立空间:
/usr/local/python3.5/bin/pip3 install virtualenv /usr/local/python3.5/bin/virtualenv /opt/edu_platform source /opt/edu_platform/bin/activate3.2 项目依赖安装
在虚拟环境中安装项目依赖:
pip install --upgrade pip pip install django==1.11.29 xadmin==0.6.1 mysqlclient gunicorn gevent版本选择考量:
- Django 1.11是最后一个支持Python 3.5的LTS版本
- xadmin 0.6.1与Django 1.11兼容性最佳
- 使用gevent worker提升Gunicorn并发能力
3.3 数据库配置
MySQL环境准备:
yum install -y mysql-server mysql-devel service mysqld start chkconfig mysqld on mysql_secure_installation创建项目数据库:
CREATE DATABASE edu_platform CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; GRANT ALL PRIVILEGES ON edu_platform.* TO 'edu_user'@'localhost' IDENTIFIED BY 'StrongPassword123!'; FLUSH PRIVILEGES;4. 生产环境服务配置
4.1 Gunicorn服务化
创建systemd服务文件/etc/systemd/system/gunicorn.service:
[Unit] Description=Gunicorn for Edu Platform After=network.target [Service] User=www Group=www WorkingDirectory=/opt/edu_platform/project Environment="PATH=/opt/edu_platform/bin" ExecStart=/opt/edu_platform/bin/gunicorn --workers 3 --bind unix:/opt/edu_platform/project.sock edu_platform.wsgi:application [Install] WantedBy=multi-user.target关键参数优化:
- 使用3个worker进程(建议CPU核心数×2+1)
- 采用Unix socket通信,比TCP更快
- 专用www用户运行,提升安全性
4.2 Nginx反向代理
配置/etc/nginx/conf.d/edu_platform.conf:
server { listen 80; server_name edu.example.com; location / { proxy_set_header Host $http_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; proxy_pass http://unix:/opt/edu_platform/project.sock; } location /static/ { alias /opt/edu_platform/project/static/; expires 30d; } location /media/ { alias /opt/edu_platform/project/media/; expires 30d; } }4.3 安全加固措施
- 防火墙配置:
iptables -A INPUT -p tcp --dport 80 -j ACCEPT iptables -A INPUT -p tcp --dport 443 -j ACCEPT iptables-save > /etc/sysconfig/iptables- SELinux策略调整:
setsebool -P httpd_can_network_connect 1 semanage port -a -t http_port_t -p tcp 8000- 定期日志轮转: 配置
/etc/logrotate.d/gunicorn:
/opt/edu_platform/logs/*.log { daily missingok rotate 30 compress delaycompress notifempty create 640 www www sharedscripts postrotate systemctl reload gunicorn endscript }5. 运维监控与故障排查
5.1 基础监控方案
安装基础监控工具:
yum install -y sysstat sar -u 1 3 # CPU使用率监控 iostat -x 1 3 # 磁盘IO监控5.2 Django特定监控
- 安装django-prometheus:
pip install django-prometheus- 在settings.py中添加:
INSTALLED_APPS += ['django_prometheus'] MIDDLEWARE = ['django_prometheus.middleware.PrometheusBeforeMiddleware'] + \ MIDDLEWARE + \ ['django_prometheus.middleware.PrometheusAfterMiddleware']- 配置Prometheus监控端点:
urlpatterns += [ path('metrics/', include('django_prometheus.urls')), ]5.3 常见问题排查指南
| 问题现象 | 可能原因 | 解决方案 |
|---|---|---|
| 502 Bad Gateway | Gunicorn未运行或权限问题 | 检查socket文件权限(www用户可读写) |
| 静态文件404 | Nginx配置路径错误 | 确认alias路径末尾有/ |
| 数据库连接失败 | MySQL未授权或SELinux阻止 | grant权限后执行setsebool -P httpd_can_network_connect_db 1 |
| 上传文件失败 | 媒体目录权限不足 | chown -R www:www /opt/edu_platform/project/media |
6. 性能优化实践
6.1 数据库优化
- 添加索引示例:
class Course(models.Model): title = models.CharField(max_length=100, db_index=True) # 其他字段... class Meta: indexes = [ models.Index(fields=['category', 'status']), ]- 使用select_related/prefetch_related:
courses = Course.objects.select_related('teacher').prefetch_related('students').all()6.2 缓存策略
配置Redis缓存:
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }视图缓存示例:
from django.views.decorators.cache import cache_page @cache_page(60 * 15) def course_list(request): # 视图逻辑6.3 异步任务处理
配置Celery:
# settings.py CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'定义异步任务:
@app.task(bind=True) def send_course_notification(self, user_ids): # 发送通知逻辑7. 持续部署方案
7.1 简易部署脚本
创建deploy.sh:
#!/bin/bash source /opt/edu_platform/bin/activate cd /opt/edu_platform/project git pull origin master pip install -r requirements.txt python manage.py migrate python manage.py collectstatic --noinput systemctl restart gunicorn7.2 备份策略
数据库每日备份:
mysqldump -u edu_user -p'StrongPassword123!' edu_platform | gzip > /backups/edu_platform_$(date +%Y%m%d).sql.gz项目代码备份:
tar czf /backups/edu_platform_code_$(date +%Y%m%d).tar.gz /opt/edu_platform7.3 日志分析技巧
使用awk分析Nginx日志:
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -20实时监控错误日志:
tail -f /var/log/nginx/error.log | grep -E '50[0-9]'