Ubuntu 24.04 安装 Netbox 4.7 指南

Ubuntu 24.04 从零安装 Netbox 4.7.3 的完整实测手册:PostgreSQL/Redis 依赖、Release Archive 与 git clone 双方案、configuration.py 必填参数、gunicorn+systemd 托管、nginx TLS 反代与排障 FAQ。

NetboxNetboxDCIM2026/10/22

Ubuntu 24.04 安装 Netbox 4.7 指南

目标:在一台全新 Ubuntu 24.04 服务器上,从零安装 Netbox 4.7.3(官方 Release Archive + Python venv + PostgreSQL + Redis + gunicorn/systemd + nginx),最终产出可登录使用的生产形态实例。全程命令与回显均在 Ubuntu 24.04.5 LTS(PostgreSQL 16.15 / Redis 7.0.15 / Python 3.12.3)实测通过;Netbox 版本经 GitHub Releases 实查为当前最新稳定版(2026-10-22 查证)。

一、环境信息

  • 操作系统:Ubuntu 24.04.5 LTS(x86_64,PRETTY_NAME="Ubuntu 24.04.5 LTS")
  • Netbox:v4.7.3(官方最新稳定版,2026-10-22 实查 GitHub Releases)
  • PostgreSQL:16.15(Ubuntu 24.04 官方仓库自带,满足官方"15 或更高"要求)
  • Redis:7.0.15(满足官方"6.0 或更高"要求)
  • Python:3.12.3(满足官方"3.12 或更高"要求)
  • WSGI 服务器:gunicorn 26.2.0(随 Netbox 依赖自动安装);应用依赖 Django 6.1.2
  • HTTP 服务器:nginx 1.24.0(Ubuntu 官方仓库)
  • 安装目录:/opt/netbox-4.7.3/,软链 /opt/netbox → /opt/netbox-4.7.3/
  • 运行账户:系统用户 netbox(UID/GID 由 adduser 自动分配)
  • 端口规划:gunicorn 监听 127.0.0.1:8001(仅本机),nginx 对外 80/443
  • Python 虚拟环境:/opt/netbox/venv/,实测体积 425M(103 个发行包)
  • 演示管理账号:admin / q1w2e3r4(生产环境请自行换强口令)

二、前置条件

本章把 Netbox 运行所需的"地基"一次铺好:系统依赖包、PostgreSQL 数据库、Redis 缓存/队列。三者全部来自 Ubuntu 官方仓库,无需添加第三方源。

2.1 安装系统依赖

Netbox 是 Django 应用,安装 Python 依赖时部分包(psycopg、cryptography 等)需要编译环境与开发头文件。一次性装齐系统级依赖:

sudo apt update
sudo apt install -y python3 python3-pip python3-venv python3-dev \
build-essential libxml2-dev libxslt1-dev libffi-dev libpq-dev \
libssl-dev zlib1g-dev

安装完成后确认 Python 版本(官方要求 v4.5+ 仅支持 Python 3.12 及以上):

python3 -V

实测回显:

Python 3.12.3

2.2 安装 PostgreSQL 并创建库与用户

Netbox 官方明确仅支持 PostgreSQL(15 或更高),不支持 MySQL/MariaDB。安装并启动:

sudo apt install -y postgresql

验证版本与编码(UTF8 为官方强制建议):

psql -V
sudo systemctl is-active postgresql

实测回显:

psql (PostgreSQL) 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1)
active

⚠️ 注意:在部分最小化安装环境(如云厂商裁剪版系统盘)中,包安装完成后的服务可能不会自动拉起,若 systemctl is-active 显示 inactive,先执行 sudo systemctl start postgresql 再继续。

以 postgres 系统用户进入 psql,创建 Netbox 专用数据库与同名用户(口令按官方示例流程设置,生产请换强口令):

sudo -u postgres psql
CREATE DATABASE netbox;
CREATE USER netbox WITH PASSWORD 'q1w2e3r4';
ALTER DATABASE netbox OWNER TO netbox;
\connect netbox;
GRANT CREATE ON SCHEMA public TO netbox;
\q

实测回显(逐条 OK):

CREATE DATABASE
CREATE ROLE
ALTER DATABASE
You are now connected to database "netbox" as user "postgres".
GRANT

验证账号密码认证可用,并确认库编码为 UTF8:

PGPASSWORD=q1w2e3r4 psql --username netbox --host localhost netbox -c "SELECT version();"

实测回显:

                                                        version
-------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0, 64-bit
(1 row)
sudo -u postgres psql -c "\l"

实测回显(节选):

   Name    |  Owner   | Encoding | Locale Provider | Collate  |  Ctype   | ICU Locale | ICU Rules |   Access privileges
-----------+----------+----------+-----------------+----------+----------+------------+-----------+-----------------------
 netbox    | netbox   | UTF8     | libc            | C.UTF-8  | C.UTF-8  |            |           |

💡 说明:GRANT CREATE ON SCHEMA public TO netbox 是官方要求的最后一步——PostgreSQL 15 起 public schema 默认不再对所有者之外的普通用户开放建表权,漏掉这一步会在后续 migrate 阶段报 permission denied for schema public。

2.3 安装 Redis

Redis 承担两个角色:tasks(后台任务队列,RQ worker 消费)与 caching(查询缓存)。安装即可,默认配置已够用:

sudo apt install -y redis-server
systemctl is-active redis-server
redis-server -v
redis-cli ping

实测回显:

active
Redis server v=7.0.15 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=d064f9f48c901a92
PONG

三、版本选型说明

  • Netbox 版本:截至 2026-10-22,GitHub Releases 最新稳定版为 v4.7.3(v4.7.0 于 2026-09-02 发布,v4.7.1 于 2026-09-15 发布)。新装一律选最新稳定版;升级路径见官方 Upgrading 文档与本系列《Netbox 4.7 常用 CLI 命令与工具详解》。
  • PostgreSQL:官方底线 15;Ubuntu 24.04 仓库的 16.15 直接满足,无需第三方源。
  • Redis:官方底线 6.0(低于 6.0 的支持已在 v4.7 移除);Ubuntu 24.04 仓库的 7.0.15 直接满足。
  • Python:官方底线 3.12(v4.5 起放弃 3.10/3.11);Ubuntu 24.04 自带 3.12.3 直接满足。若系统默认 Python 低于 3.12(如 Ubuntu 22.04 的 3.10),需先安装 3.12+ 并以 PYTHON=/usr/bin/python3.12 /opt/netbox/upgrade.sh 方式执行安装脚本。

关键差异一句话:三件套全部落在 Ubuntu 24.04 官方仓库的原生版本区间内,是本篇选择 Ubuntu 24.04 而非 22.04 的直接原因——22.04 需额外引入 Python 3.12(DeadSnakes PPA)与 PostgreSQL 15+(PGDG 源),链路变长。

四、安装方案 A:官方 Release Archive + venv(在线,主推)

4.1 方案说明

官方文档主推路径:从 GitHub Releases 下载版本化的 tar.gz 源码包,解压到 /opt/netbox-<版本> 并用 /opt/netbox 软链指向,配合官方 upgrade.sh 一键完成 venv 创建、依赖安装、数据库迁移、离线文档构建与静态资源收集。升级时解压新版本、重指软链、重跑 upgrade.sh 即可,新旧版本可并行共存。

4.2 下载并解压源码包

cd /root
wget https://github.com/netbox-community/netbox/archive/refs/tags/v4.7.3.tar.gz
sha256sum v4.7.3.tar.gz
tar -xzf v4.7.3.tar.gz -C /opt
ln -s /opt/netbox-4.7.3/ /opt/netbox
ls -l /opt | grep netbox

实测回显:

7b6bd0d792fd523bd57970b4b0fa61e92007cb33597d60dc1fd68a2a13e8073b  v4.7.3.tar.gz
lrwxrwxrwx 1 root root   18 Oct 22 10:19 netbox -> /opt/netbox-4.7.3/
drwxrwxr-x 9 root root 4096 Oct 13 11:48 netbox-4.7.3

💡 说明:sha256 值用于下载完整性核对(本文实测值基于 v4.7.3 官方发布包)。软链方式与官方一致:版本化目录 + 软链,未来升级只换软链指向。

4.3 创建系统用户并授权目录

WSGI 服务与后台 worker 将以专用系统用户 netbox 运行,媒体/报表/脚本三个目录归它所有:

adduser --system --group netbox
chown --recursive netbox /opt/netbox/netbox/media/
chown --recursive netbox /opt/netbox/netbox/reports/
chown --recursive netbox /opt/netbox/netbox/scripts/
ls -ld /opt/netbox/netbox/media /opt/netbox/netbox/reports /opt/netbox/netbox/scripts

实测回显:

info: Selecting UID from range 100 to 999 ...
info: Adding system user `netbox' (UID 103) ...
info: Adding new group `netbox' (GID 106) ...
info: Adding new user `netbox' (UID 103) with group `netbox' ...
info: Not creating `/nonexistent'.
drwxrwxr-x 2 netbox root 4096 Oct 13 11:48 /opt/netbox/netbox/media
drwxrwxr-x 2 netbox root 4096 Oct 13 11:48 /opt/netbox/netbox/reports
drwxrwxr-x 2 netbox root 4096 Oct 13 11:48 /opt/netbox/netbox/scripts

4.4 编写 configuration.py(5 个必填参数)

进入 Netbox 配置目录,以示例配置为底本复制出正式配置:

cd /opt/netbox/netbox/netbox/
cp configuration_example.py configuration.py

先生成随机 SECRET_KEY 与 API_TOKEN_PEPPERS 所需的随机串(官方自带生成脚本):

python3 ../generate_secret_key.py
python3 ../generate_secret_key.py

实测回显(每次运行结果都不同,以下是本次实测生成的两个值):

00JiVo2&PB4KdQ-e1iP(HPP(*-+yzoN%yiVaMTW*-jY6^z9Zas
UwJKwgp%SpYB+&s8RXB4_#BE7Sa@fftR%WafsYAFc2w_GSWbmq

编辑 configuration.py,落以下 5 个必填参数(其余参数保持默认即可,完整参数说明见本系列《Netbox 4.7 配置参数详解》):

ALLOWED_HOSTS = ['*']   # 生产建议收敛为具体域名/IP 列表,如 ['netbox.example.com', '192.168.10.10']

DATABASES = {
    'default': {
        'NAME': 'netbox',         # Database name
        'USER': 'netbox',         # PostgreSQL username
        'PASSWORD': 'q1w2e3r4',   # PostgreSQL password
        'HOST': 'localhost',      # Database server
        'PORT': '',               # Database port (leave blank for default)
        'CONN_MAX_AGE': 300,      # Max database connection age
    }
}

REDIS = {
    'tasks': {
        'HOST': 'localhost',
        'PORT': 6379,
        'USERNAME': '',
        'PASSWORD': '',
        'DATABASE': 0,            # tasks 队列用 0 号库
        'SSL': False,
    },
    'caching': {
        'HOST': 'localhost',
        'PORT': 6379,
        'USERNAME': '',
        'PASSWORD': '',
        'DATABASE': 1,            # caching 必须用与 tasks 不同的库号
        'SSL': False,
    },
}

SECRET_KEY = '00JiVo2&PB4KdQ-e1iP(HPP(*-+yzoN%yiVaMTW*-jY6^z9Zas'

API_TOKEN_PEPPERS = {
    1: 'UwJKwgp%SpYB+&s8RXB4_#BE7Sa@fftR%WafsYAFc2w_GSWbmq',
}

逐项说明:

参数作用关键约束
ALLOWED_HOSTSHTTP Host 头校验白名单'*' 仅限调试,生产必须收敛为真实域名/IP
DATABASESPostgreSQL 连接四要素与 2.2 节建库信息一致
REDIStasks/caching 两库必须异号常见错误是两个都写 0
SECRET_KEY会话/哈希盐≥50 字符随机串;多 Web 节点高可用部署时必须一致
API_TOKEN_PEPPERSv2 API Token 哈希加固(v4.5+ 必填)≥1 条,数字 ID 从 1 起;更换会使旧 Token 失效

⚠️ 注意:本文的 SECRET_KEY/pepper/数据库口令均为演示实测值,读者部署时必须用 generate_secret_key.py 现场重新生成,禁止照抄。

4.5 执行 upgrade.sh(venv + 依赖 + 迁移 + 静态文件)

官方一键安装/升级脚本,网络正常时约 3~8 分钟:

/opt/netbox/upgrade.sh

实测回显(输出节选——首部 pip 依赖解析):

Collecting Django==6.1.2 (from -r requirements.txt (line 3))
  Downloading django-6.1.2-py3-none-any.whl.metadata (7.9 kB)
Collecting django-rq==4.2.0 (from -r requirements.txt (line 6))
  Downloading django_rq-4.2.0-py3-none-any.whl.metadata (7.7 kB)
...
Collecting mkdocstrings==1.0.7 (from -r requirements.txt (line 27))
  Downloading mkdocstrings-1.0.7-py3-none-any.whl.metadata (15 kB)

实测回显(输出节选——中部数据库迁移):

  Applying ipam.0001_squashed... OK
  Applying virtualization.0001_squashed_0022... OK
  Applying extras.0002_squashed_0059...

实测回显(输出节选——尾部收尾与告警框):

  vpn.ipsecpolicy... No objects found.
  vpn.ipsecprofile... No objects found.
Completed. Total entries: 8
Removing expired user sessions (python3 netbox/manage.py clearsessions)...
--------------------------------------------------------------------
WARNING: No existing virtual environment was detected. A new one has
been created. Update your systemd service files to reflect the new
Python and gunicorn executables. (If this is a new installation,
this warning can be ignored.)

netbox.service ExecStart:
  /opt/netbox-4.7.3/venv/bin/gunicorn

netbox-rq.service ExecStart:
  /opt/netbox-4.7.3/venv/bin/python

After modifying these files, reload the systemctl daemon:
  > systemctl daemon-reload
--------------------------------------------------------------------
Upgrade complete! Don't forget to restart the NetBox services:
  > sudo systemctl restart netbox netbox-rq

验证安装产物:

du -sh /opt/netbox/venv
/opt/netbox/venv/bin/pip list | wc -l

实测回显:

425M    /opt/netbox/venv
103

💡 说明:首次运行时的 WARNING 属预期(新建了 venv),官方提示新装可忽略;upgrade.sh 还会顺带执行 trace_paths --no-input 与 clearsessions 两个维护命令,这也是它每次升级后必跑的原因。

4.6 创建超级用户

官方 createsuperuser 在交互终端直接运行即可(输入用户名/邮箱/密码):

source /opt/netbox/venv/bin/activate
cd /opt/netbox/netbox
python3 manage.py createsuperuser

在无法交互的自动化环境(脚本/CI)中,用环境变量 + --noinput 方式,本系列实测演示账号:

DJANGO_SUPERUSER_PASSWORD=q1w2e3r4 python3 manage.py createsuperuser --noinput --username admin --email admin@example.com

实测回显:

Superuser created successfully.

⚠️ 注意:非交互环境如果漏掉 --noinput,会报 Superuser creation skipped due to not running in a TTY. 并跳过建号——这是 Django 的 TTY 保护,不是故障。

4.7 gunicorn + systemd 托管

Netbox 依赖中已自带 gunicorn。官方方式:复制示例配置与两个 systemd 单元文件,启用并启动 netbox(Web 服务)与 netbox-rq(后台队列 worker)两个服务:

cp /opt/netbox/contrib/gunicorn.py /opt/netbox/gunicorn.py
cp -v /opt/netbox/contrib/netbox.service /opt/netbox/contrib/netbox-rq.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now netbox netbox-rq

实测回显(enable 部分输出):

Created symlink /etc/systemd/system/multi-user.target.wants/netbox.service → /etc/systemd/system/netbox.service.
Created symlink /etc/systemd/system/multi-user.target.wants/netbox-rq.service → /etc/systemd/system/netbox-rq.service.

gunicorn 配置文件 /opt/netbox/gunicorn.py 官方默认内容(可直接先用,后续按需调 worker 数):

# The IP address (typically localhost) and port that the NetBox WSGI process should listen on
bind = '127.0.0.1:8001'

# Number of gunicorn workers to spawn. This should typically be 2n+1, where
# n is the number of CPU cores present.
workers = 5

# Number of threads per worker process
threads = 3

# Timeout (in seconds) for a request to complete
timeout = 120

# The maximum number of requests a worker can handle before being respawned
max_requests = 5000
max_requests_jitter = 500

逐项说明:

参数默认值含义与调整建议
bind127.0.0.1:8001仅监听本机回环,必须由 nginx 反代对外;不要改成 0.0.0.0 直接裸奔
workers5经验公式 2×CPU+1;2C 机器保持 5 合理
threads3每 worker 线程数,慢请求多可适当上调
timeout120单请求超时秒数,报表/批量导出大时可加大
max_requests5000worker 处理 N 个请求后重生,防内存泄漏累积

验证两个服务状态:

systemctl is-active netbox netbox-rq
systemctl --no-pager -l status netbox | head -14

实测回显:

active
active
● netbox.service - NetBox WSGI Service
     Loaded: loaded (/etc/systemd/system/netbox.service; enabled; preset: enabled)
     Active: active (running) since Thu 2026-10-22 10:29:49 UTC; 6s ago
       Docs: https://docs.netbox.dev/
   Main PID: 7133 (gunicorn)
      Tasks: 6 (limit: 94371)
     Memory: 1.0G (peak: 1.0G)
        CPU: 19.058s
     CGroup: /system.slice/netbox.service
             ├─7133 /opt/netbox-4.7.3/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox --config /opt/netbox/gunicorn.py netbox.wsgi
             ├─7136 /opt/netbox-4.7.3/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox --config /opt/netbox/gunicorn.py netbox.wsgi
             ├─7137 /opt/netbox-4.7.3/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox --config /opt/netbox/gunicorn.py netbox.wsgi
             ├─7138 /opt/netbox-4.7.3/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox --config /opt/netbox/gunicorn.py netbox.wsgi
             ├─7139 /opt/netbox-4.7.3/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox --config /opt/netbox/gunicorn.py netbox.wsgi

💡 说明:实测 gunicorn 主进程 + 5 worker 共 6 个进程,冷启动后瞬时内存约 1.0G(各 worker 共享页后实际占用更低),这也是官方建议 2GB 内存起步的依据。

4.8 nginx 反向代理与 HTTPS

gunicorn 只监听 127.0.0.1:8001,对外服务由 nginx 承担(静态文件 + TLS 卸载 + 反向代理)。安装并套用官方配置模板:

apt install -y nginx
cp /opt/netbox/contrib/nginx.conf /etc/nginx/sites-available/netbox.conf
rm -f /etc/nginx/sites-enabled/default
ln -s /etc/nginx/sites-available/netbox.conf /etc/nginx/sites-enabled/netbox.conf

官方 nginx.conf 模板内容(注意它默认引用自签证书路径并要求 TLS):

server {
    listen [::]:443 ssl ipv6only=off;

    # CHANGE THIS TO YOUR SERVER'S NAME
    server_name netbox.example.com;

    ssl_certificate /etc/ssl/certs/netbox.crt;
    ssl_certificate_key /etc/ssl/private/netbox.key;

    client_max_body_size 25m;

    location /static/ {
        alias /opt/netbox/netbox/static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    # Redirect HTTP traffic to HTTPS
    listen [::]:80 ipv6only=off;
    server_name _;
    return 301 https://$host$request_uri;
}

生成自签证书(生产建议换 Let's Encrypt 或企业 CA 签发)并修正 server_name 后启动:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout /etc/ssl/private/netbox.key -out /etc/ssl/certs/netbox.crt \
  -subj "/CN=netbox-server"
sed -i 's/server_name netbox.example.com;/server_name netbox-server;/' /etc/nginx/sites-available/netbox.conf
nginx -t
systemctl enable --now nginx
systemctl is-active nginx

实测回显:

-----
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
active

4.9 验证运行

三层验证链:TLS 入口 → 登录认证 → API 可用。

curl -skI https://127.0.0.1/
curl -sI http://127.0.0.1/ | head -3

实测回显(HTTPS 正常放行至 Django,返回 302 跳登录页;HTTP 被 301 到 HTTPS):

HTTP/1.1 302 Found
Server: nginx/1.24.0 (Ubuntu)
Date: Thu, 22 Oct 2026 10:31:06 GMT
Content-Type: text/html; charset=utf-8

HTTP/1.1 301 Moved Permanently
Server: nginx/1.24.0 (Ubuntu)

命令行验证 admin 账号可登录(取 CSRF Token 后提交表单):

cd /tmp && rm -f cj.txt
CSRF=$(curl -sk -c cj.txt https://127.0.0.1/login/ | grep -oE 'csrfmiddlewaretoken" value="[^"]+' | head -1 | sed 's/.*value="//')
curl -sk -b cj.txt -c cj.txt -o /dev/null -w "login_status=%{http_code} redirect=%{redirect_url}\n" \
  -H "Referer: https://127.0.0.1/login/" \
  --data-urlencode "csrfmiddlewaretoken=$CSRF" \
  --data-urlencode "username=admin" \
  --data-urlencode "password=q1w2e3r4" \
  https://127.0.0.1/login/
curl -sk -b cj.txt https://127.0.0.1/ | grep -oE '<title>[^<]+' | head -1

实测回显:

login_status=302 redirect=https://127.0.0.1/
<title>Home | NetBox

最后确认版本与后台 worker(REST API 无需认证即可读到的状态端点):

curl -sk https://127.0.0.1/api/status/ | python3 -m json.tool | grep -E 'netbox-version|python-version|django-version|rq-workers'

实测回显:

    "django-version": "6.1.2",
    "netbox-version": "4.7.3",
    "python-version": "3.12.3",
    "rq-workers-running": 2,

浏览器访问 https://<服务器IP>/(首次会提示自签证书风险,选择继续访问),用 admin / q1w2e3r4 登录即进入 Netbox 控制台。

4.10 重启复核(开机自启)

服务器重启后所有组件应自动拉起(六个 systemd 单元均已 enabled)。重启后复核:

systemctl is-active postgresql redis-server netbox netbox-rq nginx
systemctl is-enabled netbox netbox-rq nginx

实测回显(本系列实测中通过整机方式重启了宿主环境后复核):

active active active active active
enabled enabled enabled

五、安装方案 B:git clone(在线,升级便利)

5.1 方案说明

以 git clone 拉取仓库并 checkout 版本 tag 代替下载 tar 包。优点:升级时 git fetch && git checkout vX.Y.Z 即可、无需手动下载解压;缺点:仓库体积大、首次 clone 慢、.git 目录占用额外磁盘。

5.2 安装步骤

apt install -y git
mkdir -p /opt/netbox/
cd /opt/netbox/
git clone --depth 1 --branch v4.7.3 https://github.com/netbox-community/netbox.git .
git log -1 --format='commit %h%nbranch: v4.7.3%ndate: %ad' --date=short

实测回显(断点续传说明:直连 clone 曾在中途断开,报 fetch-pack: unexpected disconnect while reading sideband packet,改走 HTTP 代理后一次成功——网络不稳定环境建议直接给 git 配代理):

commit 3cd2c1d
branch: v4.7.3
date: 2026-10-12

⚠️ 排障实录:直连 GitHub clone 大仓库时常见 unexpected disconnect while reading sideband packet / early EOF,属网络中断,重试并给 git 配置代理可解:git config --global http.proxy http://192.168.1.62:7897(按实际代理地址填写)。

之后的"创建用户 → configuration.py → upgrade.sh → createsuperuser → systemd → nginx"全部与方案 A 的 4.3~4.9 完全一致,此处不再重复。

5.3 与方案 A 的取舍

git 方案 checkout 后的目录结构与 tar 包解压结果一致(/opt/netbox 即 Netbox 根),官方对两种方式同等支持。后续升级:git 方案 git fetch --tags && git checkout v<新版本> && /opt/netbox/upgrade.sh;tar 方案下载新包解压到 /opt/netbox-<新版本>、ln -sfn 重指软链、重跑 upgrade.sh。

六、方案对比与选择建议

维度方案 A:Release Archive方案 B:git clone
网络传输单个 tar.gz(约 16MB 级)仓库全量对象(首次 165MB 级,--depth 1 可大幅缩减)
升级方式下载新包 + 重指软链 + upgrade.shgit fetch + checkout + upgrade.sh
断点容错wget 可断点续传(-c)clone 中断需重来或配代理
磁盘占用无 .git额外 .git 目录
可追溯性sha256 校验commit hash 天然可溯
适用场景常规生产部署(官方默认推荐)追版本频繁、需本地读源码/打补丁的环境

选择建议:常规部署选方案 A(传输小、有 sha256 校验、官方默认路径);需要频繁跟版或改源码选方案 B。

七、配置说明

7.1 文件位置速查

文件/目录位置用途
主配置/opt/netbox/netbox/netbox/configuration.py全部 Netbox 参数(本系列《Netbox 4.7 配置参数详解》逐项详解)
gunicorn 配置/opt/netbox/gunicorn.pyworker 数、bind 地址、超时
systemd 单元/etc/systemd/system/netbox.service、netbox-rq.service进程托管与开机自启
nginx 站点/etc/nginx/sites-available/netbox.confTLS 与反代
静态文件/opt/netbox/netbox/static/collectstatic 产物(upgrade.sh 自动收集)
上传媒体/opt/netbox/netbox/media/图片附件等(属主 netbox)
venv/opt/netbox/venv/Python 虚拟环境(425M 实测)

7.2 防火墙放行

仅放行 80/443 对外,8001 保持仅回环:

ufw allow 80,443/tcp
ufw status

实测回显(未启用 ufw 的机器 status 为 inactive,属正常):

Status: inactive

八、常见问题(FAQ)

Q1:migrate 阶段报 permission denied for schema public 漏了 2.2 节最后的 GRANT CREATE ON SCHEMA public TO netbox。补执行后重跑 /opt/netbox/upgrade.sh 即可。

Q2:nginx 启动报 cannot load certificate "/etc/ssl/certs/netbox.crt" 官方 nginx.conf 默认引用自签证书,先按 4.8 节 openssl req 生成证书再 nginx -t。本系列实测即遇到此报错,生成证书后一次通过。

Q3:createsuperuser 提示 Superuser creation skipped due to not running in a TTY. 非交互环境缺少 TTY,Django 拒绝交互式建号。改用 DJANGO_SUPERUSER_PASSWORD=<密码> python3 manage.py createsuperuser --noinput --username <用户名> --email <邮箱>。

Q4:systemctl status netbox 显示 active 但访问 502 gunicorn 监听 127.0.0.1:8001,nginx 反代指向必须一致;journalctl -eu netbox 看 gunicorn 是否实际绑定成功。实测中 gunicorn 的完整启动日志可通过 journalctl -u netbox -n 20 --no-pager 查看。

Q5:日志里出现 WORKER TIMEOUT (pid:xxx) 后个别请求失败 实测曾在日志中捕获:[CRITICAL] WORKER TIMEOUT (pid:201) 随后 Worker exiting、Booting worker with pid: 1549——某请求超过 timeout=120 被 gunicorn 强杀重生。处理:排查慢请求(如报表/批量导入),必要时调大 /opt/netbox/gunicorn.py 的 timeout 并 systemctl restart netbox。

Q6:日志里反复出现 Control server error: Permission denied: '/nonexistent' adduser --system 默认不给家目录(/nonexistent),gunicorn 控制服务器尝试写该路径被拒。不影响正常服务,属已知噪音;如需消除,给 netbox 用户设一个真实家目录(如 usermod -d /opt/netbox netbox)后重启服务。

Q7:upgrade.sh 中途网络中断 pip 下载阶段中断可直接重跑 upgrade.sh,pip 有本地缓存;因脚本幂等(重复 migrate 显示 No migrations to apply),无需清理重来。

Q8:克隆仓库报 fetch-pack: unexpected disconnect while reading sideband packet 见 5.2 节排障实录:网络中断所致,配 git 代理或改用方案 A 的 tar 包下载(wget 断点续传更稳)。

九、卸载与清理

按"停服务 → 删文件 → 删库删账号"顺序完整卸载:

systemctl disable --now netbox netbox-rq
rm -f /etc/systemd/system/netbox.service /etc/systemd/system/netbox-rq.service
systemctl daemon-reload
rm -f /etc/nginx/sites-enabled/netbox.conf /etc/nginx/sites-available/netbox.conf
systemctl reload nginx
rm -f /opt/netbox
rm -rf /opt/netbox-4.7.3
userdel netbox

数据库清理(进入 psql 后逐条执行):

sudo -u postgres psql
DROP DATABASE netbox;
DROP USER netbox;
\q

Redis 的 0/1 号库若专用于 Netbox,可 redis-cli -n 0 flushdb 与 redis-cli -n 1 flushdb 清空(与其他应用共用 Redis 时勿执行)。

十、参考链接

本系列其他文档:《Netbox 介绍与选型指南》(认知与选型)、《Netbox 4.7 配置参数详解》(configuration.py 逐项参数)、《Netbox 4.7 常用 CLI 命令与工具详解》(manage.py 全套命令与运维实操)。