如何在 Rocky Linux 9 上使用 Postgres、Nginx 和 Gunicorn 安装 Django如何在 Rocky Linux 9 上使用 Postgres、Nginx 和 Gunicorn 安装 Django如何在 Rocky Linux 9 上使用 Postgres、Nginx 和 Gunicorn 安装 Django如何在 Rocky Linux 9 上使用 Postgres、Nginx 和 Gunicorn 安装 Django
  • 文章
  • 正则表达式
    • 工具
  • 登录
找到的结果: {phrase} (显示: {results_count} 共: {results_count_total})
显示: {results_count} 共: {results_count_total}

加载更多搜索结果...

搜索范围
模糊匹配
搜索标题
搜索内容
发表 admin at 2025年2月28日
类别
  • 未分类
标签

如何在 Rocky Linux 9 上使用 Postgres、Nginx 和 Gunicorn 安装 Django

在此页

  1. 先决条件
  2. 第 1 步 - 配置防火墙
  3. 第 2 步 - 安装 PostgreSQL 和实用程序
  4. 第 3 步 - 配置 PostgreSQL
  5. 第 4 步 - 安装 Django
    1. 使用 pip 安装
    2. 安装开发版

    1. 使用 nohup 运行持久的 Django 服务器
    2. 安装 Gunicorn

    Django 是一个用于开发动态网站和应用程序的 python 框架。它遵循 MVC(模型-视图-控制器)架构。使用 Django 可以加快开发应用程序的过程,因为大部分底层任务都由它处理。

    在本教程中,您将学习如何在 Rocky Linux 9 服务器上安装 Django 框架。您还将创建一个演示项目并对其进行测试。

    先决条件

    • A server running Rocky Linux 9.

    • A non-root user with sudo privileges.

    • A fully qualified domain name (FQDN) pointing to your server. For our purposes, we will use django.example.com as the domain name.

    • Make sure everything is updated.

      $ sudo dnf update
      
    • Install basic utility packages. Some of them may already be installed.

      $ sudo dnf install wget curl nano unzip yum-utils -y
      

    • SELinux 被禁用。

    第 1 步 - 配置防火墙

    第一步是配置防火墙。 Rocky Linux 使用 Firewalld 防火墙。检查防火墙状态。

    $ sudo firewall-cmd --state
    running
    

    防火墙适用于不同的区域,公共区域是我们将使用的默认区域。列出防火墙上所有活动的服务和端口。

    $ sudo firewall-cmd --permanent --list-services
    

    它应该显示以下输出。

    cockpit dhcpv6-client ssh
    

    Django 需要 HTTP 和 HTTPS 端口才能运行。打开它们。

    $ sudo firewall-cmd --add-service=http --permanent
    $ sudo firewall-cmd --add-service=https --permanent
    

    重新加载防火墙以应用更改。

    $ sudo firewall-cmd --reload
    

    第 2 步 - 安装 PostgreSQL 和实用程序

    Rocky Linux 9 附带旧版本的 PostgreSQL。我们将为我们的教程安装 Postgres 14。

    为 PostgreSQL 安装存储库 RPM。

    $ sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
    

    安装 PostgreSQL 14 服务器。

    $ sudo dnf install -y postgresql14-server postgresql14-contrib postgresql14-devel python3-psycopg2
    

    初始化数据库。

    $ sudo /usr/pgsql-14/bin/postgresql-14-setup initdb
    

    启用并启动 PostgreSQL 服务。

    $ sudo systemctl enable postgresql-14 --now
    

    检查服务的状态。

    $ sudo systemctl status postgresql-14
    ? postgresql-14.service - PostgreSQL 14 database server
         Loaded: loaded (/usr/lib/systemd/system/postgresql-14.service; enabled; vendor preset: disabled)
         Active: active (running) since Mon 2022-09-12 01:17:24 UTC; 2s ago
           Docs: https://www.postgresql.org/docs/14/static/
        Process: 87995 ExecStartPre=/usr/pgsql-14/bin/postgresql-14-check-db-dir ${PGDATA} (code=exited, status=0/SUCCESS)
       Main PID: 88000 (postmaster)
          Tasks: 8 (limit: 5915)
         Memory: 16.5M
            CPU: 60ms
         CGroup: /system.slice/postgresql-14.service
                 ??88000 /usr/pgsql-14/bin/postmaster -D /var/lib/pgsql/14/data/
                 ??88001 "postgres: logger "
                 ??88003 "postgres: checkpointer "
                 ??88004 "postgres: background writer "
                 ??88005 "postgres: walwriter "
                 ??88006 "postgres: autovacuum launcher "
                 ??88007 "postgres: stats collector "
                 ??88008 "postgres: logical replication launcher "
    
    Sep 12 01:17:24 board.example.com systemd[1]: Starting PostgreSQL 14 database server...
    

    让我们安装一些 Django 工作所需的附加实用程序。

    $ sudo dnf install -y python3 python3-devel python3-pip gcc
    

    要解决以后有关未找到 pg_config 的任何错误,您需要将路径添加到 PostgreSQL bin 文件夹。打开 .bashrc 文件进行编辑。

    $ nano ~/.bashrc
    

    在文件末尾添加以下行。

    export PATH=$PATH:/usr/pgsql-14/bin	
    

    通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。

    第 3 步 - 配置 PostgreSQL

    登录到 PostgreSQL shell。

    $ sudo -i -u postgres psql
    

    为 Django 创建一个新的数据库。

    postgres=# CREATE DATABASE djangoapp;
    

    使用强密码创建新的数据库用户。

    postgres=# CREATE USER djangouser WITH ENCRYPTED PASSWORD 'dbpassword';
    

    授予用户使用数据库的权限。

    postgres=# GRANT ALL PRIVILEGES ON DATABASE djangoapp TO djangouser;
    

    退出 Postgres Shell。

    postgres=# \q
    

    第 4 步 - 安装 Django

    有几种安装 Django 的方法。决定哪一个最适合你取决于你想如何配置你的开发环境和你的需要。每种方法都有自己的优点和缺点。让我们来看看所有这些方法。

    使用 pip 安装

    这是安装 Django 最常用的方法。推荐的方法是使用创建虚拟 Python 环境。这允许您在不影响系统的情况下安装 Python 包。

    让我们创建一个演示项目目录。

    $ mkdir ~/sampleproject
    $ cd ~/sampleproject
    

    使用以下命令创建虚拟环境。将 sample_env 替换为您要调用虚拟环境的名称。

    $ python3 -m venv sample_env
    

    这将在您的项目目录中安装 Python 的可移植版本 pip。要将任何包安装到项目中,您需要使用以下命令激活环境。

    $ source sample_env/bin/activate
    

    您的 shell 提示符将更改以反映虚拟环境。

    (sample_env) :~/sampleproject$
    

    现在虚拟环境已经激活,使用pip安装Django。运行以下命令来安装 Django。

    (sample_env) $ pip install django
    

    验证安装。

    (sample_env) $ django-admin --version
    4.1.2
    

    根据您的项目需求,您可以通过以下方式安装不同版本的 Django。

    (sample_env) $ pip install django==3.2.1
    

    验证安装。

    (sample_env) $ django-admin --version
    3.2.1
    

    如您所见,此方法安装的 Django 版本比从 Rocky Linux 存储库获取的版本更新。

    要退出虚拟环境,请运行以下命令。

    (sample_env) $ deactivate
    

    安装开发版

    你也可以使用pip安装开发版的Django。为此,我们将从 Djangos Github 存储库中获取开发版本。

    使用以下命令将存储库克隆到 ~/django-dev 目录。

    $ git clone https://github.com/django/django ~/django-dev
    

    切换到新创建的目录。

    $ cd ~/django-dev
    

    创建虚拟环境。

    $ python3 -m venv dev_django_env
    

    激活环境。

    $ source dev_django_env/bin/activate
    

    使用 pip 安装 Django。 -e 标志以可编辑模式安装它,如果您从版本控制安装,则需要这种模式。

    (dev_django_dev) $ pip install -e ~/django-dev
    

    验证安装。

    (dev_django_dev) $ django-admin --version
    4.2.dev20221012095013
    

    可以看到,这里的版本是最新的开发版本。 Django 的开发版本对生产环境没有用处。

    第 5 步 - 创建示例项目

    让我们构建一个示例 Django 项目。为示例项目创建一个目录。

    $ mkdir ~/dj-sample
    $ cd ~/dj-sample
    

    创建 Python 虚拟环境。

    $ python3 -m venv sample_proj
    

    激活环境。

    $ source sample_proj/bin/activate
    

    安装车轮包。

    (sample_proj) $ pip install wheel
    

    安装 Django 和所需的包。

    (sample_proj) $ pip install django psycopg2 psycopg2-binary
    

    要构建项目,我们需要使用 startproject 命令。此命令创建另一个目录,其中包括:

    • 管理脚本,manage.py,用于管理特定于 Django 的任务。
    • 与包含项目代码的项目同名的目录。

    我们将在当前工作目录中创建项目目录。为此,请在以下命令末尾使用点 (.) 字符。

    (sample_proj) $ django-admin startproject demoproject .
    

    Django 使用 SECRET_KEY 变量来提供加密签名。它在安装期间生成默认值。您应该将其替换为安全值。运行以下命令以生成密钥并复制它以备后用。

    (sample_proj) $ python3 -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'
    

    您将使用密钥获得以下输出。

    wm#dzb^ymuo3s3tza=f5cx^kan!$4sch1!b-q=v%)=d0pb(jqf
    

    第一步是调整项目设置。打开设置文件进行编辑。

    (sample_proj) $ nano demoproject/settings.py
    

    将 SECRET_KEY 变量的当前值替换为您生成的密钥。

    SECRET_KEY = 's)3m=4s&!a=p#$8(z6e+u8(^tkpw28qyj0t#8ku2'
    

    更改 DATABASES 部分的设置,如下所示。

    DATABASES = {
        'default': {
    		'ENGINE': 'django.db.backends.postgresql_psycopg2',
    		'NAME': 'DATABASE_DB',
    		'USER': 'DATABASE_USER',
    		'PASSWORD': 'DATABASE_PASSWORD',
    		'HOST': 'DATABASE_HOST',
    		'PORT': 'DATABASE_PORT',
    	},
    }
    

    接下来,移动到文件的底部并添加静态文件位置的设置。这对于 Nginx 工作和处理对这些文件的请求很重要。在 STATIC_URL 变量上方添加以下行。

    STATIC_ROOT = os.path.join(BASE_DIR, "static/")
    

    由于 STATIC_ROOT 变量使用了 os 模块,我们需要导入它,因为它默认不导入。在 from pathlib import Path 行上方添加以下行。

    import os
    

    通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。

    验证数据库设置。

    (sample_proj) $ python manage.py check --database default
    

    您应该得到以下输出。

    System check identified no issues (0 silenced).
    

    接下来,我们需要使用 migrate 命令迁移数据库。 Django 中的迁移将您对模型所做的更改传播到数据库模式中。

    (sample_proj) $ python manage.py makemigrations
    (sample_proj) $ python manage.py migrate
    

    您将获得以下输出。

    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, sessions
    Running migrations:
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying admin.0002_logentry_remove_auto_add... OK
      Applying admin.0003_logentry_add_action_flag_choices... OK
      Applying contenttypes.0002_remove_content_type_name... OK
      Applying auth.0002_alter_permission_name_max_length... OK
      Applying auth.0003_alter_user_email_max_length... OK
      Applying auth.0004_alter_user_username_opts... OK
      Applying auth.0005_alter_user_last_login_null... OK
      Applying auth.0006_require_contenttypes_0002... OK
      Applying auth.0007_alter_validators_add_error_messages... OK
      Applying auth.0008_alter_user_username_max_length... OK
      Applying auth.0009_alter_user_last_name_max_length... OK
      Applying auth.0010_alter_group_name_max_length... OK
      Applying auth.0011_update_proxy_permissions... OK
      Applying auth.0012_alter_user_first_name_max_length... OK
      Applying sessions.0001_initial... OK
    

    接下来,创建一个管理用户来访问 Djangos 管理界面。

    (sample_proj) $ python manage.py createsuperuser
    

    系统将提示您输入用户名、电子邮件和密码。

    Username (leave blank to use 'navjot'):
    Email address: 
    Password:
    Password (again):
    Superuser created successfully.
    

    将静态文件复制到静态目录中。出现提示时输入 yes。

    (sample_proj) $ python manage.py collectstatic
    130 static files copied to '/home/navjot/dj-sample/static'.
    

    第 6 步 - 测试开发服务器

    现在是测试应用程序的时候了。为此,您需要修改 Django 设置中的 ALLOWED_HOSTS 指令。该指令定义了可以访问 Django 应用程序的 IP 地址和域名列表。

    使用以下命令打开设置文件。

    (sample_proj) $ nano demoproject/settings.py
    

    找到以下条目。

    ALLOWED_HOSTS = []
    

    在方括号中输入您的服务器 IP 地址。每个条目都应包含在引号中,多个条目需要用逗号分隔。输入 www.example.com 将完全匹配。但是,.example.com 将匹配 example.com 和 www.example.com,以及任何example.com 的其他子域。因此,建议使用句号作为域名前缀,以匹配该域名及其子域名。

    ALLOWED_HOSTS = ['<yourserver_ip_address>']
    

    我们已经使用 IP 地址来匹配我们的服务器。通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。

    在测试开发服务器之前,您需要配置防火墙以允许 Django 工作。 Django 默认使用 8000 端口。使用简单防火墙 (UFW) 打开端口。

    (sample_proj) $ sudo firewall-cmd --add-port=8000/tcp --permanent
    (sample_proj) $ sudo firewall-cmd --reload
    

    启动开发服务器。

    (sample_proj) $ python manage.py runserver 0.0.0.0:8000
    

    在浏览器中启动 URL http://:8000,您将看到以下屏幕。

    您可以通过以下 URL http://:8000/admin/ 访问管理界面,您将看到以下登录屏幕。

    输入之前创建的凭据以登录到如下所示的管理面板。

    完成演示项目后,您可以通过在终端中按 Ctrl + C 来关闭服务器。

    第 7 步 - 安装和测试 Gunicorn

    使用 nohup 运行持久性 Django 服务器

    到目前为止,Django 的服务并不是持久化的。要使服务持久化,有两种方法。第一种方法涉及使用 nohup 实用程序。 nohup 是一个 POSIX 命令,表示不挂断。它用于以一种即使用户注销也不会停止的方式执行命令。

    确保您已通过按 Ctrl + C 从终端退出服务器。

    运行以下命令以运行 Djangos 开发服务器。

    (sample_proj) $ nohup python manage.py runserver 0.0.0.0:8000 &
    

    现在,您的 Django 服务器将继续运行,直到您手动终止它。该命令将为您提供进程 ID 并输出另一个命令。

    [1] 42595
    (sample_proj) $ nohup: ignoring input and appending output to 'nohup.out'
    ^C
    

    按 Ctrl + C 退出。原来的 Django 服务器会继续运行。您可以通过在浏览器中打开 URL 来验证。

    完成后,您需要终止该进程。 nohup 命令为您提供了一个进程 ID。但实际上,正在运行两个进程。要查找这两个进程的 ID,请运行以下命令。

    (sample_proj) $ ps aux | grep manage.py
    navjot    153474  1.6  3.9  46264 39016 pts/0    S    04:15   0:00 python manage.py runserver 0.0.0.0:8000
    navjot    153475  3.0  4.4 196060 43500 pts/0    Sl   04:15   0:00 /home/navjot/dj-sample/sample_proj/bin/python manage.py runserver 0.0.0.0:8000
    navjot    153483  0.0  0.2   6420  2248 pts/0    S+   04:15   0:00 grep --color=auto manage.py
    

    如您所见,正在运行两个进程,一个 ID 为 153474,另一个 ID 为 153475。

    运行以下命令以使用您在上面获得的进程 ID 关闭服务器。

    (sample_proj) $ sudo kill -9 153474 153475
    

    安装 Gunicorn

    运行持久性 Django 服务器的第二种方法需要您安装 Gunicorn 和 Nginx Web 服务器。 Gunicorn 是一个 Python WSGI HTTP 服务器。它将与 Django 应用程序交互,然后 Nginx 将充当 Gunicorn 的反向代理。此方法的额外好处是为您提供使用 Nginx 所带来的安全性和性能。

    安装 Gunicorn。

    (sample_proj) $ pip install gunicorn
    

    在继续之前,我们需要测试 Gunicorns 为项目服务的能力。运行以下命令以运行 Gunicorn。

    (sample_proj) $ gunicorn --bind 0.0.0.0:8000 demoproject.wsgi:application
    

    这将在运行 Django 的相同界面上启动 Gunicorn。要验证,请在浏览器中打开 URL http://:8000,您将获得相同的 Django 主页。这意味着 Gunicorn 运行完美。

    完成测试后,在终端上按 Ctrl + C 退出 Gunicorn。

    停用虚拟环境以返回到您的常规 shell。

    (sample_proj) $ deactivate
    

    第 8 步 - 为 Gunicorn 创建套接字和服务文件

    第一步是创建一个 Gunicorn 套接字文件。 Gunicorn 套接字将在启动时创建并监听连接。当连接发生时,systemd 会自动启动 Gunicorn 进程来处理它。

    创建并打开 Gunicorn 套接字文件进行编辑。

    $ sudo nano /etc/systemd/system/gunicorn.socket
    

    将以下代码粘贴到其中。

    [Unit]
    Description=gunicorn socket
    
    [Socket]
    ListenStream=/run/gunicorn.sock
    
    [Install]
    WantedBy=sockets.target
    

    通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。

    接下来,创建并打开 Gunicorn 服务文件进行编辑。

    $ sudo nano /etc/systemd/system/gunicorn.service
    

    将以下代码粘贴到其中。

    [Unit]
    Description=django gunicorn daemon
    Requires=gunicorn.socket
    After=network.target
    
    [Service]
    User=navjot
    Group=nginx
    WorkingDirectory=/home/navjot/dj-sample
    ExecStart=/home/navjot/dj-sample/sample_proj/bin/gunicorn \
              -t 3000 \
              --access-logfile - \
              --workers 3 \
              --bind unix:/run/gunicorn.sock \
              demoproject.wsgi:application -w 2
    
    [Install]
    WantedBy=multi-user.target
    

    通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。将 navjot 替换为您的系统用户名。 nginx 组将允许 Nginx 服务器与 Django 通信。

    重新加载系统守护进程以刷新 systemd 文件。

    $ sudo systemctl daemon-reload
    

    启用并启动 Gunicorn 套接字文件。

    $ sudo systemctl start gunicorn.socket
    $ sudo systemctl enable gunicorn.socket
    

    检查 Gunicorn 套接字的状态。

    $ sudo systemctl status gunicorn.socket
    

    您将收到类似的输出。

    ? gunicorn.socket - gunicorn socket
         Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: disabled)
         Active: active (listening) since Thu 2022-10-13 04:19:28 UTC; 14s ago
          Until: Thu 2022-10-13 04:19:28 UTC; 14s ago
       Triggers: ? gunicorn.service
         Listen: /run/gunicorn.sock (Stream)
         CGroup: /system.slice/gunicorn.socket
    
    Oct 13 04:19:28 django.nspeaks.xyz systemd[1]: Listening on gunicorn socket.
    

    正如您可以检查的那样,Gunicorn 服务仍未运行。

    $ sudo systemctl status gunicorn.service
    ? gunicorn.service - django gunicorn daemon
         Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled)
         Active: inactive (dead)
    TriggeredBy: ? gunicorn.socket
    

    要测试套接字激活机制,请运行以下命令。

    $ curl --unix-socket /run/gunicorn.sock localhost
    

    您将在终端中收到 Django 主页的 HTML 输出。这也会启动 Gunicorn 来为应用程序提供服务。再次检查该服务的状态,您将看到它现在正在运行。

    $ sudo systemctl status gunicorn.service
    ? gunicorn.service - django gunicorn daemon
         Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: disabled)
         Active: active (running) since Thu 2022-10-13 06:13:55 UTC; 1min 34s ago
    TriggeredBy: ? gunicorn.socket
       Main PID: 157742 (gunicorn)
          Tasks: 4 (limit: 5915)
         Memory: 96.2M
            CPU: 1.198s
         CGroup: /system.slice/gunicorn.service
                 ??157742 /home/navjot/dj-sample/sample_proj/bin/python3 /home/navjot/dj-sample/sample_proj/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock demoproject.wsgi:application -w 2
                 ??157746 /home/navjot/dj-sample/sample_proj/bin/python3 /home/navjot/dj-sample/sample_proj/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock demoproject.wsgi:application -w 2
                 ??157747 /home/navjot/dj-sample/sample_proj/bin/python3 /home/navjot/dj-sample/sample_proj/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock demoproject.wsgi:application -w 2
                 ??157748 /home/navjot/dj-sample/sample_proj/bin/python3 /home/navjot/dj-sample/sample_proj/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock demoproject.wsgi:application -w 2
    .......
    

    第 9 步 - 安装 Nginx

    最后一步是安装和配置 Nginx。 Rocky Linux 附带旧版本的 Nginx。您需要下载官方 Nginx 存储库以安装最新版本。

    创建并打开 /etc/yum.repos.d/nginx.repo 文件以创建官方 Nginx 存储库。

    $ sudo nano /etc/yum.repos.d/nginx.repo
    

    将以下代码粘贴到其中。

    [nginx-stable]
    name=nginx stable repo
    baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
    gpgcheck=1
    enabled=1
    gpgkey=https://nginx.org/keys/nginx_signing.key
    module_hotfixes=true
    
    [nginx-mainline]
    name=nginx mainline repo
    baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
    gpgcheck=1
    enabled=0
    gpgkey=https://nginx.org/keys/nginx_signing.key
    module_hotfixes=true
    

    通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。

    安装 Nginx 服务器。

    $ sudo dnf install nginx -y
    

    验证安装。

    $ nginx -v
    nginx version: nginx/1.22.1
    

    启用并启动 Nginx 服务器。

    $ sudo systemctl enable nginx --now
    

    检查服务器的状态。

    $ sudo systemctl status nginx
    ? nginx.service - nginx - high performance web server
         Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
         Active: active (running) since Thu 2022-10-13 06:17:24 UTC; 1s ago
           Docs: http://nginx.org/en/docs/
        Process: 157900 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
       Main PID: 157901 (nginx)
          Tasks: 2 (limit: 5915)
         Memory: 1.9M
            CPU: 18ms
         CGroup: /system.slice/nginx.service
                 ??157901 "nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf"
                 ??157902 "nginx: worker process"
    
    Oct 13 06:17:24 django.example.com systemd[1]: Starting nginx - high performance web server...
    

    第 10 步 - 安装 SSL

    到目前为止,您的 Django 应用程序是通过纯文本 HTTP 连接提供服务的。强烈建议您通过 SSL 证书保护它。为此,请使用 Snapd 工具使用 Certbot 工具。它需要 EPEL 存储库才能工作。

    $ sudo dnf install epel-release
    

    我们将使用 Snapd 安装 Certbot。安装快照。

    $ sudo dnf install snapd
    

    启用并启动 Snap 服务。

    $ sudo systemctl enable snapd.socket --now
    

    为 Snapd 工作创建必要的链接。

    $ sudo ln -s /var/lib/snapd/snap /snap
    $ echo 'export PATH=$PATH:/var/lib/snapd/snap/bin' | sudo tee -a /etc/profile.d/snapd.sh
    

    安装核心 Snapd 存储库。

    $ sudo snap install core
    $ sudo snap refresh core
    

    安装 Certbot。

    $ sudo snap install --classic certbot
    $ sudo ln -s /snap/bin/certbot /usr/bin/certbot
    

    生成证书。下面的命令也会自动配置 Nginx。

    $ sudo certbot certonly --nginx --agree-tos --no-eff-email --staple-ocsp --preferred-challenges http -m  -d django.example.com
    

    上面的命令会将证书下载到服务器上的 /etc/letsencrypt/live/django.example.com 目录。

    生成 Diffie-Hellman 组证书。

    $ sudo openssl dhparam -dsaparam -out /etc/ssl/certs/dhparam.pem 4096
    

    要检查 SSL 续订是否正常工作,请试运行该过程。

    $ sudo certbot renew --dry-run
    

    如果您没有看到任何错误,则一切就绪。您的证书将自动更新。

    第 11 步 - 配置 Nginx

    创建并打开文件 /etc/nginx/conf.d/django-gunicorn.conf 进行编辑。

    $ sudo nano /etc/nginx/conf.d/django-gunicorn.conf
    

    将以下代码粘贴到其中。

    # enforce HTTPS
    server {
      listen 80 default_server;
      server_name django.example.com;
      return 301 https://$server_name$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name django.example.com;
    
        access_log  /var/log/nginx/django.access.log;
        error_log   /var/log/nginx/django.error.log;
    
        http2_push_preload on; # Enable HTTP/2 Server Push
    
        ssl_certificate /etc/letsencrypt/live/django.example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/django.example.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/django.example.com/chain.pem;
        ssl_session_timeout 1d;
    
        # Enable TLS versions (TLSv1.3 is required upcoming HTTP/3 QUIC).
        ssl_protocols TLSv1.2 TLSv1.3;
    
        # Enable TLSv1.3's 0-RTT. Use $ssl_early_data when reverse proxying to
        # prevent replay attacks.
        #
        # @see: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_early_data
        ssl_early_data on;
    
        ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384';
        ssl_prefer_server_ciphers on;
        ssl_session_cache shared:SSL:50m;
    
        # OCSP Stapling ---
        # fetch OCSP records from URL in ssl_certificate and cache them
        ssl_stapling on;
        ssl_stapling_verify on;
        ssl_dhparam /etc/ssl/certs/dhparam.pem;
    
        add_header X-Early-Data $tls1_3_early_data;
    
        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            root /home/navjot/dj-sample;
        }
    
        location / {
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_pass http://unix:/run/gunicorn.sock;
        }
    }
    
    # This block is useful for debugging TLS v1.3. Please feel free to remove this
    # and use the `$ssl_early_data` variable exposed by NGINX directly should you
    # wish to do so.
    map $ssl_early_data $tls1_3_early_data {
      "~." $ssl_early_data;
      default "";
    }
    

    将上述文件中的根位置替换为您服务器上的目录。

    通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。

    打开文件 /etc/nginx/nginx.conf 进行编辑。

    $ sudo nano /etc/nginx/nginx.conf
    

    在行 include /etc/nginx/conf.d/*.conf; 之前添加以下行。

    server_names_hash_bucket_size  64;
    

    通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。

    验证您的 Nginx 配置。

    $ sudo nginx -t
    

    如果您没有看到任何错误,则表示您可以开始了。

    您还需要将域名添加到 ALLOWED_HOSTS 指令中。打开 settings.py 文件。

    $ nano ~/dj-sample/demoproject/settings.py
    

    更改 ALLOWED_HOSTS 变量的值。

    ALLOWED_HOSTS = ['<yourserver_ip_address>','django.example.com']
    

    通过按 Ctrl + X 并在出现提示时输入 Y 来保存文件。

    重新启动 Gunicorn 套接字和服务。

    $ sudo systemctl restart gunicorn.socket
    $ sudo systemctl restart gunicorn.service
    

    重新加载 Nginx 服务器。

    $ sudo systemctl reload nginx
    

    打开 HTTP 端口。如果您不再使用 8000 端口,也可以将其删除。

    $ sudo firewall-cmd --remove-port=8000/tcp --permanent
    $ sudo firewall-cmd --reload
    

    通过打开 URL http://django.example.com 进行验证,Django 主页将加载。

    结论

    我们的教程到此结束,您在其中学习了如何在 Rocky Linux 9 服务器上安装 Django 以及 Gunicorn 和 Nginx。您还安装了 SSL 证书以增强 Django 项目的安全性。如果您有任何问题,请在下面的评论中发表。

©2015-2025 艾丽卡 support@alaica.com