How to Install Nextcloud on Ubuntu 24.04: The Complete Step-by-Step Guide

Prerequisites and System Requirements

Before beginning the installation, verify your Ubuntu 24.04 system meets the minimum requirements. You need a server with at least 2 GB of RAM (4 GB recommended for production), a dual-core processor, and 20 GB of free disk space. A fully qualified domain name (FQDN) pointing to your server’s IP address is essential for HTTPS configuration. Ensure your system is updated: sudo apt update && sudo apt upgrade -y. You must have a non-root user with sudo privileges. This guide assumes you are using a clean Ubuntu 24.04 LTS installation.

Step 1: Install the LAMP Stack (Linux, Apache, MySQL/MariaDB, PHP)

Nextcloud runs on the LAMP stack. Begin by installing Apache: sudo apt install apache2 -y. Enable and start the service: sudo systemctl enable --now apache2. Next, install MariaDB, a drop-in replacement for MySQL: sudo apt install mariadb-server mariadb-client -y. Secure the database installation: sudo mysql_secure_installation. Follow the prompts to set a root password, remove anonymous users, disable remote root login, and remove test databases. Finally, install PHP 8.3 and required extensions. Ubuntu 24.04 ships with PHP 8.3. Run: sudo apt install php8.3 libapache2-mod-php php8.3-mysql php8.3-gd php8.3-xml php8.3-mbstring php8.3-curl php8.3-zip php8.3-bz2 php8.3-intl php8.3-ldap php8.3-imagick php8.3-gmp php8.3-bcmath php8.3-redis php8.3-apcu -y. Confirm PHP version: php -v.

Step 2: Configure MariaDB for Nextcloud

Create a dedicated database and user for Nextcloud. Log into MariaDB: sudo mysql -u root -p. Execute the following SQL commands:

CREATE DATABASE nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER 'nextclouduser'@'localhost' IDENTIFIED BY 'YourStrongPasswordHere';
GRANT ALL PRIVILEGES ON nextcloud.* TO 'nextclouduser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Replace YourStrongPasswordHere with a strong, unique password. For production, enable MariaDB’s encryption at rest if required by your compliance policies.

Step 3: Download and Extract Nextcloud

Navigate to the web root: cd /var/www/. Download the latest Nextcloud release. Visit the official download page to verify the current version, then use wget: sudo wget https://download.nextcloud.com/server/releases/latest.zip. Install unzip if needed: sudo apt install unzip -y. Extract the archive: sudo unzip latest.zip. This creates a nextcloud directory. Set correct ownership: sudo chown -R www-data:www-data /var/www/nextcloud/. Set appropriate permissions: sudo chmod -R 755 /var/www/nextcloud/. Remove the zip file: sudo rm latest.zip.

Step 4: Configure Apache Virtual Host

Create a new Apache configuration file: sudo nano /etc/apache2/sites-available/nextcloud.conf. Add the following content, replacing your-domain.com with your actual domain:


    ServerName your-domain.com
    ServerAdmin admin@your-domain.com
    DocumentRoot /var/www/nextcloud/

    
        Options +FollowSymlinks
        AllowOverride All
        Require all granted
        
            Dav off
        
        SetEnv HOME /var/www/nextcloud
        SetEnv HTTP_HOME /var/www/nextcloud
    

    ErrorLog ${APACHE_LOG_DIR}/nextcloud_error.log
    CustomLog ${APACHE_LOG_DIR}/nextcloud_access.log combined

Enable the site and required modules: sudo a2ensite nextcloud.conf && sudo a2enmod rewrite headers env dir mime. Disable the default site: sudo a2dissite 000-default.conf. Restart Apache: sudo systemctl restart apache2.

Step 5: Secure with Let’s Encrypt SSL (HTTPS)

Install Certbot: sudo apt install certbot python3-certbot-apache -y. Obtain an SSL certificate: sudo certbot --apache -d your-domain.com. Follow the interactive prompts, entering your email and agreeing to terms. Certbot automatically modifies your VirtualHost to use HTTPS and sets up auto-renewal. Verify renewal: sudo certbot renew --dry-run. For strict security, force HTTPS by redirecting all HTTP traffic. Certbot typically does this automatically; verify your configuration includes:

RewriteEngine on
RewriteCond %{SERVER_NAME} =your-domain.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

Step 6: Configure PHP Settings

Nextcloud requires specific PHP values. Edit the PHP ini file: sudo nano /etc/php/8.3/apache2/php.ini. Adjust these parameters:

memory_limit = 512M
upload_max_filesize = 20G
post_max_size = 20G
max_execution_time = 3600
max_input_time = 3600
date.timezone = UTC
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=1
opcache.fast_shutdown=1

For large file uploads, you may need to adjust upload_max_filesize and post_max_size to match your needs. Save and restart Apache: sudo systemctl restart apache2.

Step 7: Install and Configure Redis for Caching

Redis improves Nextcloud performance significantly. Install Redis: sudo apt install redis-server php8.3-redis -y. Configure Redis for local socket communication: sudo nano /etc/redis/redis.conf. Set port 0 and uncomment unixsocket /var/run/redis/redis-server.sock, then set unixsocketperm 770. Add the www-data user to the Redis group: sudo usermod -aG redis www-data. Restart Redis: sudo systemctl restart redis-server. This config will be referenced in the Nextcloud config file later.

Step 8: Complete Installation via Web Interface

Open a browser and navigate to https://your-domain.com. The Nextcloud setup page appears. Create an admin account with a strong password. Click “Storage & database” and select “MySQL/MariaDB”. Enter the database details: Database user: nextclouduser, Database password: YourStrongPasswordHere, Database name: nextcloud, Database host: localhost. Click “Finish setup”. Nextcloud will install and present the dashboard. If you receive any errors about missing PHP modules, install them using sudo apt install php8.3-{module_name} and restart Apache.

Step 9: Post-Installation Configuration (config.php)

After the web setup, edit the Nextcloud configuration file for advanced settings: sudo nano /var/www/nextcloud/config/config.php. Add the following array entries to optimize performance and security:

  'trusted_domains' =>
  array (
    0 => 'localhost',
    1 => 'your-domain.com',
    2 => '192.168.1.100', // Your local IP if needed
  ),
  'default_phone_region' => 'US', // Change to your country code
  'memcache.local' => 'OCMemcacheAPCu',
  'memcache.distributed' => 'OCMemcacheRedis',
  'memcache.locking' => 'OCMemcacheRedis',
  'redis' =>
  array (
    'host' => '/var/run/redis/redis-server.sock',
    'port' => 0,
    'timeout' => 0.0,
  ),
  'overwriteprotocol' => 'https',
  'mail_from_address' => 'nextcloud', // For email notifications
  'mail_smtpmode' => 'sendmail',
  'log_type' => 'errorlog',
  'logfile' => '/var/log/nextcloud.log',
  'loglevel' => 1, // 0=DEBUG, 1=INFO, 2=WARN, 3=ERROR

Create the log file: sudo touch /var/log/nextcloud.log && sudo chown www-data:www-data /var/log/nextcloud.log. Set correct permissions for the config file: sudo chmod 640 /var/www/nextcloud/config/config.php.

Step 10: Enable Background Jobs (Cron)

Nextcloud uses background jobs for file scanning, email notifications, and cleanup. Disable AJAX-based cron and switch to system cron. In your Nextcloud admin panel, go to “Basic settings” → “Background jobs” and select “Cron”. Or, set it via CLI: sudo -u www-data php /var/www/nextcloud/occ background:cron. Then add a cron job: sudo crontab -u www-data -e. Add the line: */5 * * * * php -f /var/www/nextcloud/cron.php. This runs every 5 minutes. Verify cron is active: sudo systemctl status cron.

Step 11: Set Up Nextcloud Command-Line Occ Tool

The occ command is essential for maintenance. Create an alias for convenience: alias occ='sudo -u www-data php /var/www/nextcloud/occ'. Add this to your .bashrc if desired. Test with: sudo -u www-data php /var/www/nextcloud/occ status. Upgrade Nextcloud in the future using: sudo -u www-data php /var/www/nextcloud/occ upgrade. Use occ maintenance:mode --on to put Nextcloud in maintenance mode before updates.

Step 12: Configure Firewall for Ubuntu 24.04

If you use UFW (Uncomplicated Firewall), allow necessary ports: sudo ufw allow 80/tcp && sudo ufw allow 443/tcp. Enable UFW: sudo ufw enable. For SSH access, keep port 22 open: sudo ufw allow 22/tcp. Verify rules: sudo ufw status verbose. For systems with iptables directly, ensure both HTTP and HTTPS are open.

Step 13: Install and Enable Nextcloud Apps

Access your Nextcloud instance as admin. Go to “Apps” in the top-right menu. Recommended apps to install: “Calendar”, “Contacts”, “Mail”, “Collabora Online” (for document editing), “Talk” (for video calls), and “End-to-End Encryption”. For each app, click “Enable”. For external storage, enable the “External storage support” app and configure S3, Dropbox, or local drives in “Settings → Administration → External storage”. Install them from the official app store or via the occ command: sudo -u www-data php /var/www/nextcloud/occ app:install calendar.

Step 14: Optimize Database Performance

Nextcloud can be slow without database optimization. Run these MariaDB commands to improve performance. Log into MariaDB: sudo mysql -u root -p. Execute:

SET GLOBAL innodb_buffer_pool_size = 1G; -- Adjust based on RAM (25% of total)
SET GLOBAL innodb_log_file_size = 256M;
SET GLOBAL query_cache_size = 64M;

Make these persistent by editing: sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf. Add or modify under [mysqld]:

innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
query_cache_size = 64M
query_cache_type = 1

Restart MariaDB: sudo systemctl restart mariadb.

Step 15: Set Up Backup Strategy

Automate backups using a cron job. Create a backup script: sudo nano /usr/local/bin/nextcloud-backup.sh. Include:

#!/bin/bash
BACKUP_DIR="/backup/nextcloud"
DATE=$(date +%Y%m%d%H%M)
mkdir -p $BACKUP_DIR/$DATE
# Backup database
mysqldump --single-transaction -u nextclouduser -p'YourStrongPasswordHere' nextcloud > $BACKUP_DIR/$DATE/db.sql
# Backup data and config
rsync -Aax /var/www/nextcloud/ $BACKUP_DIR/$DATE/nextcloud/
# Backup data folder (if separate)
rsync -Aax /var/nextcloud_data/ $BACKUP_DIR/$DATE/data/

Make executable: sudo chmod +x /usr/local/bin/nextcloud-backup.sh. Add to crontab: sudo crontab -e. Add: 0 3 * * * /usr/local/bin/nextcloud-backup.sh. Test the script manually: sudo /usr/local/bin/nextcloud-backup.sh.

Step 16: Hardening Security

Disable dangerous Apache modules: sudo a2dismod autoindex status info. Set proper file permissions: sudo chmod 644 /var/www/nextcloud/.htaccess && sudo chmod 644 /var/www/nextcloud/.user.ini. Enable two-factor authentication in Nextcloud settings for all users. Use the “Security” app to enforce password policies. Set a strict Content Security Policy by adding to Apache config:


    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-XSS-Protection "1; mode=block"
    Header set Referrer-Policy "strict-origin-when-cross-origin"

Restart Apache: sudo systemctl restart apache2.

Step 17: Troubleshoot Common Issues

If you encounter a “502 Bad Gateway” error, check Apache logs: sudo tail -f /var/log/apache2/nextcloud_error.log. For PHP memory limit errors, increase memory_limit in php.ini. If file uploads fail, verify upload_max_filesize and post_max_size values. For database connection errors, confirm MariaDB is running and credentials match config.php. Use occ commands for deep diagnostics: sudo -u www-data php /var/www/nextcloud/occ maintenance:repair. For Redis connection issues, verify socket permissions: sudo chmod 770 /var/run/redis/redis-server.sock. If the web interface returns a blank page, enable PHP error display temporarily: sudo nano /etc/php/8.3/apache2/php.ini, set display_errors = On, restart Apache, and view the error.

Step 18: Enable Maintenance Mode for Future Updates

Before any major update, put Nextcloud into maintenance mode: sudo -u www-data php /var/www/nextcloud/occ maintenance:mode --on. Then update via: sudo -u www-data php /var/www/nextcloud/updater/updater.phar. Or manually replace files. After update, disable maintenance mode: sudo -u www-data php /var/www/nextcloud/occ maintenance:mode --off. Always test updates in a staging environment first.

Leave a Comment