You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Linode中更改默认Django项目目录并切换监听项目

解决Linode服务器切换监听自定义Django项目的步骤

假设你的Linode服务器采用Nginx + Gunicorn(Linode默认Django部署的主流组合),按以下步骤操作即可切换到自定义项目:

1. 确认自定义Django项目的基础配置

  • 进入你的项目目录(例如/var/www/YourCustomProject),编辑settings.py:
    • 设置ALLOWED_HOSTS = ['你的服务器IP/域名'],避免访问时出现403错误
    • 配置静态文件收集路径:STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles'),然后执行python manage.py collectstatic收集静态资源
    • 先本地测试项目可用性:python manage.py runserver 0.0.0.0:8000,访问服务器IP:8000确认项目能正常运行

2. 修改Gunicorn服务配置

Linode默认将Gunicorn注册为systemd服务,配置文件通常在/etc/systemd/system/gunicorn.service:

  • 编辑该文件:sudo nano /etc/systemd/system/gunicorn.service
  • 修改ExecStart行,指向自定义项目的wsgi入口:
    ExecStart=/usr/bin/python3 /var/www/YourCustomProject/manage.py run_gunicorn --workers 3 --bind unix:/var/www/YourCustomProject/YourCustomProject.sock
    
    (替换YourCustomProject为你的实际项目名,确保Python解释器路径和项目路径正确)
  • 重载systemd并重启Gunicorn:
    sudo systemctl daemon-reload
    sudo systemctl restart gunicorn
    
  • 检查服务状态:sudo systemctl status gunicorn,确保服务处于active (running)状态

3. 修改Nginx反向代理配置

Nginx的站点配置文件通常在/etc/nginx/sites-available/django(或类似命名):

  • 编辑配置文件:sudo nano /etc/nginx/sites-available/django
  • 更新server块中的关键配置:
    • 替换反向代理的socket路径:
      location / {
          proxy_pass http://unix:/var/www/YourCustomProject/YourCustomProject.sock;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
      }
      
    • 修改静态文件的根目录:
      location /static/ {
          root /var/www/YourCustomProject;
      }
      
  • 验证Nginx配置合法性:sudo nginx -t,无报错再重启服务:sudo systemctl restart nginx

4. 验证结果

访问你的服务器IP或域名,确认页面加载的是你的自定义Django项目。若出现502错误,检查Gunicorn服务状态或socket文件权限;若静态文件不显示,确认collectstatic已执行且Nginx配置的路径正确。

补充:若使用uWSGI而非Gunicorn

  • 找到uWSGI配置文件(例如/etc/uwsgi/sites/django.ini)
  • 修改chdir和module字段:
    chdir = /var/www/YourCustomProject
    module = YourCustomProject.wsgi:application
    
  • 重启uWSGI服务:sudo systemctl restart uwsgi

内容的提问来源于stack exchange,提问作者Khal Shaphat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:00:47