在京东云服务器上部署Django项目可以分为以下几个步骤,涵盖环境配置、项目部署和Web服务器设置:
1. 购买并连接京东云服务器
- 购买ECS实例:选择适合的配置(建议至少2核4G,CentOS 7+/Ubuntu 20.04 LTS)。
- 登录服务器:通过SSH连接:
ssh root@<服务器公网IP>
2. 安装必要环境
2.1 更新系统及安装依赖
# CentOS
yum update -y
yum install -y git python3 python3-devel gcc nginx mariadb-server mariadb-devel
# Ubuntu/Debian
apt update -y
apt install -y git python3 python3-pip python3-dev nginx mysql-server libmysqlclient-dev
2.2 安装Python虚拟环境
pip3 install virtualenv
mkdir /opt/django_project
cd /opt/django_project
virtualenv venv
source venv/bin/activate # 激活虚拟环境
3. 部署Django项目
3.1 上传项目代码
- 通过Git克隆或使用
scp上传本地代码:git clone <你的项目仓库> - 安装项目依赖:
pip install -r requirements.txt
3.2 配置数据库(以MySQL为例)
# 登录MySQL
mysql -u root -p
# 创建数据库和用户
CREATE DATABASE django_db;
CREATE USER 'django_user'@'localhost' IDENTIFIED BY '你的密码';
GRANT ALL PRIVILEGES ON django_db.* TO 'django_user'@'localhost';
FLUSH PRIVILEGES;
3.3 修改Django配置
- 编辑
settings.py:DEBUG = False # 生产环境关闭Debug ALLOWED_HOSTS = ['服务器公网IP', '域名'] # 允许访问的IP/域名 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER': 'django_user', 'PASSWORD': '你的密码', 'HOST': 'localhost', 'PORT': '3306', } }
3.4 迁移数据库和静态文件
python manage.py migrate
python manage.py collectstatic
4. 配置Gunicorn + Nginx
4.1 安装Gunicorn
pip install gunicorn
4.2 测试Gunicorn运行
gunicorn --bind 0.0.0.0:8000 项目名.wsgi:application
- 访问
http://服务器IP:8000确认项目是否正常。
4.3 配置Systemd服务(后台运行)
创建服务文件 /etc/systemd/system/gunicorn.service:
[Unit]
Description=Gunicorn Django Server
After=network.target
[Service]
User=root
WorkingDirectory=/opt/django_project
ExecStart=/opt/django_project/venv/bin/gunicorn --workers 3 --bind unix:/opt/django_project/gunicorn.sock 项目名.wsgi:application
[Install]
WantedBy=multi-user.target
启动服务:
systemctl start gunicorn
systemctl enable gunicorn
4.4 配置Nginx
编辑 /etc/nginx/conf.d/django.conf:
server {
listen 80;
server_name 服务器IP或域名;
location / {
proxy_pass http://unix:/opt/django_project/gunicorn.sock;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /static/ {
alias /opt/django_project/static/;
}
}
重启Nginx:
nginx -t # 测试配置
systemctl restart nginx
5. 安全配置
-
防火墙:放行HTTP/HTTPS端口:
# CentOS firewall-cmd --permanent --add-service=http firewall-cmd --permanent --add-service=https firewall-cmd --reload # Ubuntu ufw allow 80 ufw allow 443 - HTTPS:使用Let’s Encrypt免费证书:
certbot --nginx -d 你的域名
6. 验证部署
- 访问
http://服务器IP或https://域名,确认Django项目正常运行。
常见问题
- 静态文件404:确保
collectstatic已运行,且Nginx配置的alias路径正确。 - 数据库连接失败:检查MySQL用户权限和Django的
settings.py配置。 - 502 Bad Gateway:确认Gunicorn服务是否运行,
gunicorn.sock文件权限是否正确。
通过以上步骤,你的Django项目应该已在京东云服务器上成功部署!如果需要更复杂的配置(如Celery异步任务、Redis缓存等),可进一步扩展。
云服务器