NginxPython(Django)项目部署详细说明以及案例
2025-03-09
11
Nginx + Python(Django)项目部署详细说明
1. 环境准备
操作系统: Ubuntu 20.04 LTS
Python: 3.8
Django: 3.2
Nginx: 1.18.0
Gunicorn: 20.1.0
2. 安装依赖
sudo apt update sudo apt install python3-pip python3-dev libpq-dev nginx pip3 install django gunicorn psycopg2-binary
3. 创建Django项目
django-admin startproject myproject cd myproject
4. 配置Gunicorn
创建Gunicorn服务文件:
sudo nano /etc/systemd/system/gunicorn.service
添加以下内容:
[Unit] Description=gunicorn daemon After=network.target [Service] User=yourusername Group=www-data WorkingDirectory=/path/to/your/project ExecStart=/usr/bin/gunicorn --workers 3 --bind unix:/path/to/your/project/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target
启动并启用Gunicorn服务:
sudo systemctl start gunicorn sudo systemctl enable gunicorn
5. 配置Nginx
创建Nginx配置文件:
sudo nano /etc/nginx/sites-available/myproject
添加以下内容:
server { listen 80; server_name yourdomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/your/project; } location / { include proxy_params; proxy_pass http://unix:/path/to/your/project/myproject.sock; } }
启用配置文件并重启Nginx:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl restart nginx
6. 配置静态文件
在
settings.py
中设置STATIC_ROOT
:
STATIC_ROOT = '/path/to/your/project/static/'
收集静态文件:
python3 manage.py collectstatic
7. 配置数据库(可选)
如果需要使用PostgreSQL,安装并配置:
sudo apt install postgresql postgresql-contrib sudo -u postgres psql CREATE DATABASE myprojectdb; CREATE USER myprojectuser WITH PASSWORD 'mypassword'; ALTER ROLE myprojectuser SET client_encoding TO 'utf8'; ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed'; ALTER ROLE myprojectuser SET timezone TO 'UTC'; GRANT ALL PRIVILEGES ON DATABASE myprojectdb TO myprojectuser; \q
在
settings.py
中配置数据库:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myprojectdb', 'USER': 'myprojectuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '', } }
8. 测试部署
访问
http://yourdomain.com
,确保Django项目正常运行。
案例
假设项目名为myproject
,域名为example.com
,项目路径为/home/username/myproject
。
Gunicorn服务文件:
[Unit] Description=gunicorn daemon After=network.target [Service] User=username Group=www-data WorkingDirectory=/home/username/myproject ExecStart=/usr/bin/gunicorn --workers 3 --bind unix:/home/username/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target
Nginx配置文件:
server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/username/myproject/myproject.sock; } }
静态文件配置:
STATIC_ROOT = '/home
本篇文章内容来源于:NginxPython(Django)项目部署详细说明以及案例
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。