部署基于Django框架的項目可以通過多種方式實現,以下是幾種常見的方法:
Gunicorn是一個Python WSGI HTTP服務器,適合用于生產環境。Nginx則是一個高性能的HTTP和反向代理服務器,可以作為Gunicorn的前端代理。
安裝Gunicorn和Nginx:
pip install gunicorn
sudo apt-get install nginx
配置Gunicorn:
創建一個Gunicorn配置文件,例如/etc/systemd/system/myproject.service
:
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=yourusername
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/usr/local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/path/to/your/project/myproject.sock myproject.wsgi:application
[Install]
WantedBy=multi-user.target
啟動并啟用Gunicorn服務:
sudo systemctl start myproject
sudo systemctl enable myproject
配置Nginx:
編輯Nginx配置文件,例如/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;
}
}
創建符號鏈接以啟用該配置:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
測試Nginx配置并重啟Nginx:
sudo nginx -t
sudo systemctl restart nginx
uWSGI是另一個流行的WSGI服務器,支持多種配置方式。
安裝uWSGI和Nginx:
pip install uwsgi
sudo apt-get install nginx
配置uWSGI:
創建一個uWSGI配置文件,例如/etc/uwsgi/sites/myproject
:
[uwsgi]
chdir = /path/to/your/project
module = myproject.wsgi:application
master = true
processes = 5
socket = /path/to/your/project/myproject.sock
chmod-socket = 660
vacuum = true
配置Nginx:
編輯Nginx配置文件,例如/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;
}
}
創建符號鏈接以啟用該配置:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
測試Nginx配置并重啟Nginx:
sudo nginx -t
sudo systemctl restart nginx
Docker是一個容器化平臺,可以方便地將Django項目部署到容器中。
創建Dockerfile:
在項目根目錄下創建一個Dockerfile
:
FROM python:3.8-slim
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "--bind", "unix:/app/myproject.sock", "myproject.wsgi:application"]
創建Docker Compose文件(可選):
創建一個docker-compose.yml
文件:
version: '3'
services:
web:
build: .
command: gunicorn --bind unix:/app/myproject.sock myproject.wsgi:application
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
db:
image: postgres
environment:
POSTGRES_DB: myproject
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword
構建和運行Docker容器:
docker-compose up --build
配置Nginx反向代理(可選): 編輯Nginx配置文件,添加一個新的server塊指向Docker容器的端口:
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:/app/myproject.sock;
}
}
重啟Nginx:
sudo systemctl restart nginx
以上是幾種常見的Django項目部署方法。選擇哪種方法取決于你的具體需求和偏好。