一、介绍
Django是一个免费的开源 Python Web 框架。本文提供了在 Debian 11 服务器上使用 Nginx、Gunicorn 和免费的 Let’s Encrypt TLS 证书设置 Django 项目的分步指南。
二、准备工作
- 在 Vultr 部署新的Debain 11 服务器
- 创建 sudo 用户。示例用户是
django_user - 更新服务器
- 将域名指向服务器。让我们加密 SSL/TLS 证书需要域名。本指南使用顶级域example.com和完全限定域名mydjango.example.com,并假定为这两个名称分配了相同的 IP 地址。
三. 安装依赖项
- 通过 SSH 使用非 root sudo 用户登录到服务器。
$ ssh django_user@mydjango.example.com - 安装,,并使用 apt 包管理器。
UFWVimNginx$ sudo apt -y install ufw vim nginx - 允许所有出站流量。
$ sudo ufw default allow outgoing - 阻止除 SSH(端口 22)、HTTP(端口 80)和 HTTPS(端口 443)之外的所有入站流量。
$ sudo ufw default deny incoming $ sudo ufw allow ssh $ sudo ufw allow http $ sudo ufw allow https - 启用并重新加载。
UFW$ sudo ufw enable $ sudo ufw reload
四、安装 PostgresSQL
- 使用 apt 包管理器安装 PostgreSQL,在安装过程中会创建一个 postgres 用户。
$ sudo apt install -y postgresql postgresql-contrib - 切换到 postgres 用户。
$ sudo su - postgres - 登录到PostgresSQL。
$ psql - 为 Django 项目创建一个 PostgresSQL 数据库角色。
postgres=# CREATE ROLE dbuser WITH LOGIN; - 为角色设置密码。
dbuserpostgres=# \password dbuser - 塞滕编码到。
dbuserUTF-8postgres=# ALTER ROLE dbuser SET client_encoding TO 'utf8'; - 将默认事务隔离设置为读取提交。
dbuserpostgres=# ALTER ROLE dbuser SET default_transaction_isolation TO 'read committed'; - 将时区设置为。
dbuserUTCpostgres=# ALTER ROLE dbuser SET timezone TO 'UTC'; - 创建 Django 项目数据库。
postgres=# CREATE DATABASE appdb; - 授予所有权限。
dbuserappdbpostgres=# GRANT ALL PRIVILEGES ON DATABASE appdb TO dbuser; - 退出 postgres 客户端。
postgres=# \q - 出口到须藤
exit - 重新启动 PostgresSQL 服务器。
$ sudo systemctl restart postgresql
五、 设置 Python 环境
部署 Python Web 应用程序时应使用 Python 虚拟环境。
- 安装蟒蛇。
venv$ sudo apt -y install python3-venv - 创建应用程序目录、虚拟环境所在的位置以及应用程序文件。例。切换到主目录。
app_dir$ cd ~创建目录。
$ mkdir app_dir - 更改为并创建虚拟环境。
app dir$ cd app_dir $ python3 -m venv venv - 激活虚拟环境。
$ source venv/bin/activate - 安装 Python PostgresSQL 库而不是,因为在安装过程中需要构建。
psycopg2-binarypsycopg2psycopg2$ pip install psycopg2-binary - 安装 Django 和 Gunicorn。
$ pip install django gunicorn
六、 上传或创建 Django 项目
- 项目源码需要用 git 或者 scp 上传到 app 目录下,对于本文,创建一个名为的示例项目。
app_direxample_app$ django-admin startproject example_app . - 检查文件夹结构。
app_dir$ ls example_app manage.py venv - 创建一个文件夹来将 Django 项目的静态文件保存在应用程序文件夹中。
$ mkdir static - 打开 inwith以配置项目。
settings.pyexample_appVim$ vim example_app/settings.py - 配置域的允许主机。
ALLOWED_HOSTS = ['mydjango.example.com'] - 使用创建自的详细信息配置变量。
DATABASESsection 2DATABASES = { "default" : { "ENGINE" : "django.db.backends.postgresql", "NAME" : "appdb", "USER" : "dbuser", "PASSWORD" : "dbpassword", "HOST" : "127.0.0.1", "PORT" : "5432", } } - 设置静态文件夹路径。在它下面寻找添加。
STATIC_URLSTATIC_ROOTSTATIC_ROOT = "/home/django_user/app_dir/static" - 保存并关闭文件。
settings.py - 创建项目迁移。
$ python manage.py makemigrations - 运行迁移。
$ python manage.py migrate - 将项目的所有静态文件复制到静态文件夹。类型出现提示时。
yes$ python manage.py collectstatic - 为项目创建管理员用户。
$ python manage.py createsuperuser - 允许波顿。
8000UFW$ sudo ufw allow 8000 - 测试项目以确保其运行没有错误。
$ python manage.py runserver 0.0.0.0:8000 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 16, 2022 - 21:19:26 Django version 4.1.3, using settings 'example_app.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C.
七、配置独角兽
将创建一个 Gunicorn 服务来为项目提供服务,并在服务器重新启动时启动项目。
- 测试Gunicorn,看看它是否可以毫无错误地为项目服务。
$ gunicorn --bind 0.0.0.0:8000 example_app.wsgi - 按+停止它。CTRLC
- 停用虚拟环境
$ deactivate - 编辑文件。
settings.pyVim$ vim example_app/settings.py - 禁用调试。查找变量并将其设置为。
DEBUGFalseDEBUG = False - 保存并关闭文件。
settings.py - 拒绝端口 8000 的传入流量。
UFW$ sudo ufw deny 8000 - 在目录中创建一个文件。
django_app.service/etc/systemd/system$ sudo vim /etc/systemd/system/django_app.service - 将以下内容写入文件。
[Unit] Description=Gunicorn for the Django project After=network.target [Service] User=django_user Group=www-data WorkingDirectory=/home/django_user/app_dir Environment="PATH=/home/django_user/app_dir/venv/bin" ExecStart=/home/django_user/app_dir/venv/bin/gunicorn --workers 2 --bind unix:django_app.sock example_app.wsgi [Install] WantedBy=multi-user.target- 下,设置服务的用户,并将服务的组设置为 Nginx 组。
[Service]USER=django_userGroup=www-data WorkingDirectory=/home/django_user/app_dir将服务工作目录设置为“项目”文件夹。Environment="PATH=/home/django_user/app_dir/venv/bin"设置服务应使用的虚拟环境。ExecStart=/home/django_user/app_dir/venv/bin/gunicorn --workers 2 --bind unix:django_app.sock example_app.wsgi为项目运行 Gunicorn worker 服务,并将它们绑定到 Unix 套接字,以便更快地交换 Nginx 代理服务器的数据。
- 下,设置服务的用户,并将服务的组设置为 Nginx 组。
- 保存并关闭文件。
- 使服务能够在启动时启动。
$ sudo systemctl enable django_app - 启动服务。
$ sudo systemctl start django_app
八、配置云
需要一个Nginx代理服务器来为生产中的Django应用程序提供服务并处理SSL证书。
- 通过创建文件在 Nginx 中配置服务器块。
django_app/etc/nginx/sites-available$ sudo vim /etc/nginx/sites-available/django_app - 将以下内容写入文件。
server { # listen to port 80 (HTTP) listen 80; # listen to the domain name server_name example.com mydjango.example.com; location /static/ { alias /home/django_user/app_dir/static/; expires max; } location / { include proxy_params; # pass the request to the project service sock proxy_pass http://unix:/home/django_user/app_dir/django_app.sock; } } - 保存并关闭文件。
- 为Nginx创建一个链接。
django_appsites-enabled$ sudo ln -s /etc/nginx/sites-available/django_app /etc/nginx/sites-enabled - 检查 Nginx 配置是否有任何错误。
$ sudo nginx -t - 重新启动 Nginx 服务器。
$ sudo systemctl reload nginx
九、(可选)使用加密添加 HTTPS
如果您在开始时配置了域,则可以使用Let’s Encrypt添加SSL / TLS证书以提供HTTPS支持。
- 使用插件安装。
CertbotNginx$ sudo apt install certbot python3-certbot-nginx - 配置方式。
CertbotNginx$ sudo certbot --nginx -d example.com -d mydjango.example.com首次运行 Certbot 时,将请求证书的管理员电子邮件。Certbot还将配置Nginx,并通过配置服务器块将所有HTTP请求重定向到HTTPS。
Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Enter email address (used for urgent renewal and security notices) (Enter 'c' to cancel): me@example.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Please read the Terms of Service at https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf. You must agree in order to register with the ACME server. Do you agree? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (Y)es/(N)o: y - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Would you be willing, once your first certificate is successfully issued, to share your email address with the Electronic Frontier Foundation, a founding partner of the Let's Encrypt project and the non-profit organization that develops Certbot? We'd like to send you email about our work encrypting the web, EFF news, campaigns, and ways to support digital freedom. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (Y)es/(N)o: y Account registered. Requesting a certificate for example.com and mydjango.example.com Performing the following challenges: http-01 challenge for example.com http-01 challenge for mydjango.example.com Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/django_app Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/django_app Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/django_app Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/django_app - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations! You have successfully enabled https://example.com and https://mydjango.example.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Subscribe to the EFF mailing list (email: me@example.com). IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/example.com/privkey.pem Your certificate will expire on 2023-02-15. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le - 重新启动。
Nginx$ sudo systemctl reload nginx
- 在浏览器中访问服务器的域。
mydjango.example.com/admin
你现在在 Debian 11 上有一个可以工作的 Django 站点。

主机百科












