备份项目
检查依赖
pip freeze > requirements.txt
# 使用scp命令传输文件(从本地到服务器)
scp -r /本地/项目路径 username@服务器IP:/目标路径
# 或者使用git克隆(如果项目在git仓库)
git clone 项目仓库地址
# 安装Python和pip(以Ubuntu为例)
sudo apt update
sudo apt install python3 python3-pip python3-venv
# 创建虚拟环境
python3 -m venv myenv
source myenv/bin/activate
# 进入项目目录
cd /项目路径
# 安装依赖
pip install -r requirements.txt
# 安装数据库服务(以MySQL为例)
sudo apt install mysql-server
# 创建数据库和用户
sudo mysql -u root
CREATE DATABASE dbname;
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'localhost';
FLUSH PRIVILEGES;
exit
# 修改Django settings.py中的数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbname',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
}
}
# 迁移数据库
python manage.py migrate
# 修改settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# 运行收集命令
python manage.py collectstatic
# 修改settings.py
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com', '服务器IP']
# 安装Gunicorn
pip install gunicorn
# 测试运行
gunicorn --bind 0.0.0.0:8000 项目名.wsgi:application
# 安装Nginx
sudo apt install nginx
# 配置Nginx(创建/etc/nginx/sites-available/yourproject)
server {
listen 80;
server_name yourdomain.com;
location /static/ {
alias /项目路径/staticfiles/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# 启用配置
sudo ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx
# 安装Apache和mod_wsgi
sudo apt install apache2 libapache2-mod-wsgi-py3
# 配置Apache(创建/etc/apache2/sites-available/yourproject.conf)
<VirtualHost *:80>
ServerName yourdomain.com
Alias /static /项目路径/staticfiles
<Directory /项目路径/staticfiles>
Require all granted
</Directory>
<Directory /项目路径/项目名>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess yourproject python-path=/项目路径 python-home=/项目路径/myenv
WSGIProcessGroup yourproject
WSGIScriptAlias / /项目路径/项目名/wsgi.py
</VirtualHost>
# 启用配置
sudo a2ensite yourproject.conf
sudo systemctl restart apache2
# 创建systemd服务文件(/etc/systemd/system/gunicorn.service)
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=username
Group=www-data
WorkingDirectory=/项目路径
ExecStart=/项目路径/myenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/项目路径/项目名.sock 项目名.wsgi:application
[Install]
WantedBy=multi-user.target
# 启动服务
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
权限问题
sudo chown -R www-data:www-data /项目路径
sudo chmod -R 755 /项目路径
静态文件404错误
collectstatic
命令数据库连接问题
端口冲突
sudo netstat -tulnp | grep :80
sudo kill <PID>
完成以上步骤后,你的Django项目应该已经在Linux系统上成功运行。记得定期备份数据库和项目文件。