Ubuntu 22.04環(huán)境準備
在開始安裝Django之前,確保您的Ubuntu 22.04系統(tǒng)已更新到最新版本。運行以下命令更新系統(tǒng):
sudo apt update && sudo apt upgrade -y
安裝Python和虛擬環(huán)境
Django是基于Python的框架,因此需要安裝Python。Ubuntu 22.04默認已安裝Python 3。創(chuàng)建虛擬環(huán)境以隔離項目依賴:
sudo apt install python3-venv
python3 -m venv django_env
source django_env/bin/activate
安裝Django
激活虛擬環(huán)境后,使用pip安裝Django:
pip install django
創(chuàng)建Django項目
使用Django的命令行工具創(chuàng)建新項目:
django-admin startproject myproject
cd myproject
配置數(shù)據(jù)庫
Django默認使用SQLite數(shù)據(jù)庫。如需使用PostgreSQL,安裝必要的包:
sudo apt install postgresql postgresql-contrib
pip install psycopg2-binary
修改settings.py
編輯myproject/settings.py文件,更新數(shù)據(jù)庫配置和允許的主機:
ALLOWED_HOSTS = ['your_server_ip', 'your_domain.com']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_db_name',
'USER': 'your_db_user',
'PASSWORD': 'your_db_password',
'HOST': 'localhost',
'PORT': '',
}
}
運行數(shù)據(jù)庫遷移
應用數(shù)據(jù)庫遷移:
python manage.py makemigrations
python manage.py migrate
創(chuàng)建超級用戶
為Django管理界面創(chuàng)建超級用戶:
python manage.py createsuperuser
配置靜態(tài)文件
在settings.py中添加靜態(tài)文件配置:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
安裝Gunicorn
Gunicorn是推薦的生產(chǎn)環(huán)境WSGI服務器:
pip install gunicorn
配置Nginx
安裝和配置Nginx作為反向代理:
sudo apt install nginx
sudo nano /etc/nginx/sites-available/myproject
添加以下配置:
server {
listen 80;
server_name your_domain.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:/run/gunicorn.sock;
}
}
啟動Gunicorn和Nginx
創(chuàng)建系統(tǒng)服務以管理Gunicorn:
sudo nano /etc/systemd/system/gunicorn.service
添加服務配置:
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=your_user
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/your/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application
[Install]
WantedBy=multi-user.target
啟動服務:
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
sudo systemctl restart nginx
安全性配置
配置防火墻,只允許必要的端口:
sudo ufw allow 'Nginx Full'
sudo ufw enable
結語
完成以上步驟后,您的Django應用將在Ubuntu 22.04服務器上成功部署。定期更新系統(tǒng)和依賴包,確保應用的安全性和性能。通過這種配置,您的Django應用能夠高效、安全地運行在生產(chǎn)環(huán)境中。