UbuntuUbuntu Based

How To Install NetBox on Ubuntu 24.04 LTS

Install NetBox on Ubuntu 24.04

NetBox stands as the industry-leading open-source infrastructure resource modeling (IRM) application, originally developed by DigitalOcean’s network engineering team. This powerful platform combines IP address management (IPAM), data center infrastructure management (DCIM), and network automation capabilities into a unified solution that thousands of organizations worldwide rely on for managing their network infrastructure.

Ubuntu 24.04 LTS (Noble Numbat) provides an excellent foundation for NetBox deployment, offering long-term support, stability, and compatibility with all NetBox requirements. The combination of Ubuntu’s robust package management system and NetBox’s Django-based architecture creates a reliable platform for both development and production environments.

Proper planning before installation ensures smooth deployment and optimal performance. This comprehensive guide walks through every step of the installation process, from initial system preparation to advanced configuration options, providing both novice and experienced system administrators with the knowledge needed to successfully deploy NetBox.

Throughout this tutorial, you’ll learn to configure PostgreSQL databases, set up Redis caching, implement proper security measures, and establish production-ready web server configurations. Whether you’re managing a small network or enterprise-scale infrastructure, this guide provides the foundation for a robust NetBox installation.

Table of Contents

Prerequisites and System Requirements

Before beginning the NetBox installation process, ensure your Ubuntu 24.04 LTS system meets the minimum hardware and software requirements for optimal performance.

Hardware Requirements:

  • Development Environment: 2 GB RAM, 2 CPU cores, 20 GB disk space
  • Production Environment: 4 GB RAM (8 GB recommended), 4 CPU cores, 50 GB disk space
  • Network Access: Stable internet connection for package downloads

Software Dependencies:

  • Python 3.10 or higher (Ubuntu 24.04 includes Python 3.12)
  • PostgreSQL 14 or higher
  • Redis 4.0 or higher
  • Git version control system

System Access Requirements:

  • Root or sudo access to the Ubuntu server
  • SSH access for remote installation
  • Ability to modify firewall rules and system services

Network Configuration Prerequisites:

  • Fully qualified domain name (FQDN) for production deployments
  • Static IP address (recommended for production)
  • DNS resolution properly configured
  • SSL certificate for HTTPS access (production environments)

Security Baseline:
Ensure your Ubuntu system has the latest security updates installed and basic firewall protection enabled. Consider implementing fail2ban for additional security against brute-force attacks, especially if the server will be accessible from the internet.

Preparing Your Ubuntu 24.04 LTS Server

System preparation forms the foundation of a successful NetBox installation. Begin by updating the package repository and upgrading existing packages to their latest versions.

sudo apt update && sudo apt upgrade -y

Creating a Dedicated User

Security best practices recommend creating a dedicated user account for NetBox operations rather than using the root account.

sudo adduser netbox
sudo usermod -aG sudo netbox

Configuring System Hostname

Set a meaningful hostname that reflects the server’s purpose:

sudo hostnamectl set-hostname netbox.yourdomain.com
echo "127.0.1.1 netbox.yourdomain.com netbox" | sudo tee -a /etc/hosts

Timezone Configuration

Ensure the system timezone matches your organization’s requirements:

sudo timedatectl set-timezone America/New_York

Basic Firewall Setup

Configure UFW (Uncomplicated Firewall) for enhanced security:

sudo ufw enable
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

System Optimization

Adjust system limits for better performance with database operations:

echo "netbox soft nofile 65536" | sudo tee -a /etc/security/limits.conf
echo "netbox hard nofile 65536" | sudo tee -a /etc/security/limits.conf

Installing Required Dependencies

NetBox requires several system packages and libraries to function properly. Install all necessary dependencies using Ubuntu’s package manager.

Essential System Packages

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 git

Additional Development Tools

sudo apt install -y curl wget gnupg2 software-properties-common apt-transport-https ca-certificates

Python Package Management

Verify Python installation and upgrade pip to the latest version:

python3 --version
pip3 --version
python3 -m pip install --upgrade pip

Troubleshooting Common Issues

If you encounter permission errors during pip installation, use the --user flag or ensure you’re working within a virtual environment. Package conflicts can often be resolved by clearing pip cache:

pip3 cache purge

Verifying Dependencies

Confirm all essential packages are properly installed:

dpkg -l | grep -E "(python3-dev|libpq-dev|git)"

This command should return information about each installed package, confirming successful installation.

Configuring the PostgreSQL Database

PostgreSQL serves as NetBox’s primary database backend, storing all configuration data, device information, and user accounts. Proper database configuration ensures optimal performance and data integrity.

Installing PostgreSQL

sudo apt install -y postgresql postgresql-contrib

Starting and Enabling PostgreSQL

sudo systemctl start postgresql
sudo systemctl enable postgresql

Creating the NetBox Database

Switch to the PostgreSQL user account and create the necessary database and user:

sudo -u postgres psql

Within the PostgreSQL prompt, execute these commands:

CREATE DATABASE netbox;
CREATE USER netbox WITH PASSWORD 'secure_password_here';
ALTER DATABASE netbox OWNER TO netbox;
GRANT ALL PRIVILEGES ON DATABASE netbox TO netbox;
\q

Database Security Configuration

Edit the PostgreSQL configuration to restrict connections:

sudo nano /etc/postgresql/16/main/pg_hba.conf

Ensure the following line exists for local connections:

local   netbox          netbox                                  md5

Testing Database Connectivity

Verify the database configuration works correctly:

psql -U netbox -d netbox -h localhost -W

Enter the password you created earlier. A successful connection confirms proper database setup.

Performance Optimization

For production environments, consider adjusting PostgreSQL settings in /etc/postgresql/16/main/postgresql.conf:

shared_buffers = 256MB
effective_cache_size = 1GB
work_mem = 4MB
maintenance_work_mem = 64MB

Restart PostgreSQL after making configuration changes:

sudo systemctl restart postgresql

Installing and Configuring Redis

Redis provides caching and background task queue functionality for NetBox, significantly improving application performance and user experience.

Installing Redis Server

sudo apt install -y redis-server

Configuring Redis

Edit the Redis configuration file to optimize for NetBox usage:

sudo nano /etc/redis/redis.conf

Key configuration changes:

supervised systemd
maxmemory 256mb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000

Starting and Enabling Redis

sudo systemctl start redis-server
sudo systemctl enable redis-server

Testing Redis Functionality

Verify Redis is working correctly:

redis-cli ping

The command should return “PONG”, indicating Redis is operational.

Redis Security Considerations

For production environments, consider setting a Redis password:

sudo nano /etc/redis/redis.conf

Uncomment and set:

requirepass your_redis_password_here

Downloading NetBox

NetBox installation involves downloading the latest stable release and properly configuring file permissions for secure operation.

Creating Installation Directory

sudo mkdir -p /opt/netbox
cd /opt/netbox

Downloading Latest NetBox Release

Visit the NetBox GitHub repository to identify the latest stable version, then download it:

sudo wget https://github.com/netbox-community/netbox/archive/refs/tags/v4.3.4.tar.gz
sudo tar -xzf v4.3.4.tar.gz
sudo mv netbox-4.3.4/* .
sudo rm -rf netbox-4.3.4 v4.3.4.tar.gz

Alternative Git Method

For development or bleeding-edge installations:

sudo git clone https://github.com/netbox-community/netbox.git .
sudo git checkout v4.3.4

Setting Proper Ownership

Create the netbox user and configure appropriate permissions:

sudo adduser --system --group netbox
sudo chown -R netbox:netbox /opt/netbox

File Permission Security

Ensure sensitive files have restricted access:

sudo chmod -R 755 /opt/netbox
sudo chmod -R 640 /opt/netbox/netbox/configuration/

Creating and Configuring the Python Virtual Environment

Virtual environments isolate NetBox dependencies from system Python packages, preventing conflicts and ensuring consistent operation across different deployments.

Creating Virtual Environment

cd /opt/netbox
sudo -u netbox python3 -m venv venv

Activating Virtual Environment

sudo -u netbox /opt/netbox/venv/bin/activate

Installing NetBox Dependencies

sudo -u netbox /opt/netbox/venv/bin/pip install --upgrade pip
sudo -u netbox /opt/netbox/venv/bin/pip install -r requirements.txt

Troubleshooting Installation Issues

If you encounter compilation errors, ensure all development headers are installed:

sudo apt install -y python3-dev libffi-dev libssl-dev

Memory-related errors during installation can be resolved by adding swap space:

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Verifying Installation

Check that all required packages installed successfully:

sudo -u netbox /opt/netbox/venv/bin/pip list | grep -i django

NetBox Initial Configuration

NetBox configuration involves creating and customizing the main configuration file with database connections, security settings, and application-specific parameters.

Creating Configuration File

cd /opt/netbox/netbox/netbox/
sudo -u netbox cp configuration_example.py configuration.py

Generating Secret Key

Create a cryptographically secure secret key:

sudo -u netbox /opt/netbox/venv/bin/python /opt/netbox/netbox/generate_secret_key.py

Copy the generated key for use in the configuration file.

Editing Configuration File

sudo -u netbox nano /opt/netbox/netbox/netbox/configuration.py

Essential configuration parameters:

ALLOWED_HOSTS = ['netbox.yourdomain.com', 'localhost', '127.0.0.1']

DATABASE = {
    'NAME': 'netbox',
    'USER': 'netbox',
    'PASSWORD': 'secure_password_here',
    'HOST': 'localhost',
    'PORT': '',
    'CONN_MAX_AGE': 300,
}

REDIS = {
    'tasks': {
        'HOST': 'localhost',
        'PORT': 6379,
        'USERNAME': '',
        'PASSWORD': '',
        'DATABASE': 0,
        'SSL': False,
    },
    'caching': {
        'HOST': 'localhost',
        'PORT': 6379,
        'USERNAME': '',
        'PASSWORD': '',
        'DATABASE': 1,
        'SSL': False,
    }
}

SECRET_KEY = 'your_generated_secret_key_here'

DEBUG = False

Email Configuration (Optional)

For production environments requiring email notifications:

EMAIL = {
    'SERVER': 'smtp.gmail.com',
    'PORT': 587,
    'USERNAME': 'your_email@gmail.com',
    'PASSWORD': 'your_app_password',
    'USE_SSL': False,
    'USE_TLS': True,
    'TIMEOUT': 10,
    'FROM_EMAIL': 'netbox@yourdomain.com',
}

Security Hardening

Additional security-focused configuration options:

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True

Database Migration and Superuser Creation

Database migration creates the necessary table structure and relationships within PostgreSQL, while superuser creation establishes administrative access to the NetBox interface.

Running Database Migrations

cd /opt/netbox/netbox
sudo -u netbox /opt/netbox/venv/bin/python manage.py migrate

Creating Administrative User

sudo -u netbox /opt/netbox/venv/bin/python manage.py createsuperuser

Follow the prompts to create username, email, and password for the administrative account.

Verifying Migration Success

Check that all migrations completed successfully:

sudo -u netbox /opt/netbox/venv/bin/python manage.py showmigrations

All migrations should show an “X” indicating successful completion.

Troubleshooting Migration Issues

If migrations fail due to database connection issues, verify PostgreSQL is running and credentials are correct:

sudo systemctl status postgresql
sudo -u netbox psql -h localhost -d netbox -U netbox -W

Collecting Static Files

Static file collection gathers CSS, JavaScript, and image assets required for the NetBox web interface, preparing them for efficient serving by the web server.

Collecting Static Files

cd /opt/netbox/netbox
sudo -u netbox /opt/netbox/venv/bin/python manage.py collectstatic --no-input

Setting Static File Permissions

sudo chown -R netbox:netbox /opt/netbox/netbox/static/

Verifying Static File Collection

Confirm static files were collected properly:

ls -la /opt/netbox/netbox/static/

The directory should contain admin, debug_toolbar, and other subdirectories with web assets.

Setting Up the NetBox Service

Creating a systemd service ensures NetBox starts automatically at boot and provides proper process management for production environments.

Creating Service File

sudo nano /etc/systemd/system/netbox.service

Service configuration:

[Unit]
Description=NetBox WSGI Service
Documentation=https://docs.netbox.dev/
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=netbox
Group=netbox
PIDFile=/var/tmp/netbox.pid
WorkingDirectory=/opt/netbox/netbox
ExecStart=/opt/netbox/venv/bin/python /opt/netbox/netbox/manage.py runserver 0.0.0.0:8001 --insecure
Restart=on-failure
RestartSec=30
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Creating NetBox-RQ Service

NetBox requires a separate service for background task processing:

sudo nano /etc/systemd/system/netbox-rq.service
[Unit]
Description=NetBox Request Queue Worker
Documentation=https://docs.netbox.dev/
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=netbox
Group=netbox
WorkingDirectory=/opt/netbox/netbox
ExecStart=/opt/netbox/venv/bin/python /opt/netbox/netbox/manage.py rqworker
Restart=on-failure
RestartSec=30
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Enabling and Starting Services

sudo systemctl daemon-reload
sudo systemctl enable netbox netbox-rq
sudo systemctl start netbox netbox-rq

Monitoring Service Status

sudo systemctl status netbox
sudo systemctl status netbox-rq

Both services should show “active (running)” status.

Setting Up Gunicorn as the WSGI Server

Gunicorn provides a production-ready WSGI server that significantly improves NetBox performance and scalability compared to Django’s development server.

Installing Gunicorn

sudo -u netbox /opt/netbox/venv/bin/pip install gunicorn

Creating Gunicorn Configuration

sudo -u netbox nano /opt/netbox/gunicorn.conf.py

Configuration file contents:

command = '/opt/netbox/venv/bin/gunicorn'
pythonpath = '/opt/netbox/netbox'
bind = '127.0.0.1:8001'
workers = 5
user = 'netbox'
timeout = 120
max_requests = 5000
max_requests_jitter = 500
preload_app = True

Updating NetBox Service

Modify the NetBox systemd service to use Gunicorn:

sudo nano /etc/systemd/system/netbox.service

Update the ExecStart line:

ExecStart=/opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox --config /opt/netbox/gunicorn.conf.py netbox.wsgi

Restarting Services

sudo systemctl daemon-reload
sudo systemctl restart netbox

Configuring a Reverse Proxy with Nginx

Nginx serves as a reverse proxy, handling SSL termination, static file serving, and load balancing, providing enhanced security and performance for production NetBox deployments.

Installing Nginx

sudo apt install -y nginx

Creating NetBox Virtual Host

sudo nano /etc/nginx/sites-available/netbox

Nginx configuration:

server {
    listen 80;
    server_name netbox.yourdomain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name netbox.yourdomain.com;

    ssl_certificate /etc/ssl/certs/netbox.crt;
    ssl_certificate_key /etc/ssl/private/netbox.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;

    client_max_body_size 25m;

    location /static/ {
        alias /opt/netbox/netbox/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    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;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect off;
    }
}

Enabling Site Configuration

sudo ln -s /etc/nginx/sites-available/netbox /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

SSL Certificate Setup with Certbot

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d netbox.yourdomain.com

Follow the prompts to obtain and install SSL certificates automatically.

Securing Your NetBox Installation

Security implementation encompasses firewall configuration, SSL enforcement, and access control measures to protect your NetBox deployment from unauthorized access and potential threats.

Firewall Configuration

sudo ufw allow 'Nginx Full'
sudo ufw delete allow 8001
sudo ufw reload

Securing Administrative Access

Enable two-factor authentication and implement strong password policies through NetBox’s web interface after initial login.

Database Security

Restrict PostgreSQL access to local connections only:

sudo nano /etc/postgresql/16/main/postgresql.conf

Ensure listen_addresses = 'localhost' is set.

File System Permissions

sudo chmod 750 /opt/netbox
sudo chmod 640 /opt/netbox/netbox/netbox/configuration.py

Regular Security Updates

Implement automated security updates:

sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

Testing and Accessing NetBox

Comprehensive testing ensures all components function correctly and users can access NetBox through the web interface without issues.

Verifying Service Status

sudo systemctl status netbox netbox-rq nginx postgresql redis-server

All services should report “active (running)” status.

Web Interface Testing

Navigate to https://netbox.yourdomain.com in your web browser. The NetBox login page should load with proper SSL certificate validation.

Install NetBox on Ubuntu 24.04

API Endpoint Verification

Test API functionality:

curl -H "Accept: application/json; indent=4" https://netbox.yourdomain.com/api/

Database Connectivity Testing

sudo -u netbox /opt/netbox/venv/bin/python /opt/netbox/netbox/manage.py shell

Within the Django shell:

from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT version();")
print(cursor.fetchone())
exit()

Docker-Based NetBox Installation Alternative

Docker deployment offers simplified installation and management for development environments or organizations preferring containerized solutions.

Installing Docker and Docker Compose

sudo apt install -y docker.io docker-compose-v2
sudo usermod -aG docker $USER

Cloning NetBox Docker Repository

git clone https://github.com/netbox-community/netbox-docker.git
cd netbox-docker

Configuration and Deployment

tee docker-compose.override.yml <

Docker vs. Manual Installation Considerations

  • Pros: Simplified deployment, easy updates, consistent environments
  • Cons: Less customization flexibility, higher resource usage, Docker maintenance overhead

Choose Docker deployment for development environments or when containerization aligns with your infrastructure strategy.

Advanced Tips and Best Practices

Backup and Recovery Procedures

Implement regular backup strategies for both database and configuration files:

# Database backup
sudo -u postgres pg_dump netbox > netbox_backup_$(date +%Y%m%d).sql

# Configuration backup
sudo tar -czf netbox_config_$(date +%Y%m%d).tar.gz /opt/netbox/netbox/netbox/configuration.py

Performance Monitoring

Monitor NetBox performance using system tools:

# Process monitoring
htop

# Database performance
sudo -u postgres psql -c "SELECT * FROM pg_stat_activity;"

# Nginx access logs
sudo tail -f /var/log/nginx/access.log

Plugin Management

NetBox supports plugins for extended functionality. Install plugins within the virtual environment:

sudo -u netbox /opt/netbox/venv/bin/pip install netbox-plugin-name

Add plugins to configuration.py:

PLUGINS = ['netbox_plugin_name']

Upgrade Procedures

Plan regular upgrades to maintain security and access new features:

  1. Backup current installation
  2. Download new NetBox version
  3. Update virtual environment dependencies
  4. Run database migrations
  5. Collect static files
  6. Restart services

Common Errors and Troubleshooting

Database Connection Issues

django.db.utils.OperationalError: could not connect to server

Solution: Verify PostgreSQL service status and configuration credentials.

Redis Connection Problems

redis.exceptions.ConnectionError: Error connecting to Redis

Solution: Check Redis service status and configuration file syntax.

Permission Denied Errors

PermissionError: [Errno 13] Permission denied

Solution: Verify file ownership and permissions for NetBox directories.

Static Files Not Loading

404 errors for CSS/JavaScript files

Solution: Rerun collectstatic command and verify Nginx static file configuration.

SSL Certificate Issues

NET::ERR_CERT_AUTHORITY_INVALID

Solution: Renew certificates using Certbot or verify certificate installation.

Log Analysis

Monitor system logs for detailed error information:

sudo journalctl -u netbox -f
sudo tail -f /var/log/nginx/error.log

Congratulations! You have successfully installed NetBox. Thanks for using this tutorial for installing NetBox modern networks on Ubuntu 24.04 LTS system. For additional help or useful information, we recommend you check the official NetBox website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button