Install Nextcloud on Ubuntu 24.04 LTS – Complete Guide

In this guide, we are going to explain in detail, How to Install NextCloud On Ubuntu 24.04 LTS. This is a detailed step by step guide. during the installation, we have focused on increasing the performance and security of the system.

What is Nextcloud?

Nextcloud is a self-hosted collaboration platform designed to enhance productivity through integrated services like Files, Talk, Groupware, and Office. It offers functionality similar to Dropbox, Office 365, or Google Drive when used with office suites like Collabora Online or OnlyOffice.

nextcloud ubuntu 24.04 dashboard view
nextcloud ubuntu 24.04 files view
nextcloud ubuntu 24.04 photos view

Nextcloud has four main products. Files provides self-hosted file storage and synchronization. Talk offers private audio/video conferencing and chat. Groupware includes productivity tools like Calendar and Mail, and Office provides an online office suite for collaborative document editing.

Nextcloud can be hosted in the cloud or on-premises, offering flexible deployment options. It allows storing documents on private servers or trusted data centers, ensuring greater control and security.

Below we provided a step by step guide on How to Install NextCloud On Ubuntu 24.04 LTS. We completed in 14 steps. Each steps are mandatory to complete before go to next step.

We divided the installation into three main phases. First, we provided the steps for “Basic Nextcloud Setup” then we did the Performance Tuning. Finally, we provided steps for Systems Security.

nextcloud install ubuntu 24.04 3phase
Nextcloud Complete Installation in 3 Phase
nextcloud install ubuntu 24.04 phase1

Step1: Update and Upgrade the system.

1. Update and Upgrade the Ubuntu Packages

apt update && apt upgrade -y

Step2: Install Apache2 and PHP Modules.

1. install Apache2

apt install apache2 -y

3. Install PHP and other Dependencies

apt install php php-common libapache2-mod-php php-bz2 php-gd php-mysql \
php-curl php-mbstring php-imagick php-zip php-common php-curl php-xml \
php-json php-bcmath php-xml php-intl php-gmp zip unzip wget -y

4. Enable required Apache modules

a2enmod env rewrite dir mime headers setenvif ssl

5. Now, Restart, Enable and Check Apache is Running Properly.

systemctl restart apache2
systemctl enable apache2

6. Apache service should be in running state.

root@nc:~# systemctl status apache2
 apache2.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/apache2.service; 
     enabled; preset: enabled)
     Active: active (running) since Tue 2024-06-18 04:39:09 UTC; 8s ago
       Docs: https://httpd.apache.org/docs/2.4/
   Main PID: 16319 (apache2)
      Tasks: 6 (limit: 2269)
     Memory: 16.1M (peak: 16.3M)
        CPU: 97ms
     CGroup: /system.slice/apache2.service
             ├─16319 /usr/sbin/apache2 -k start
             ├─16326 /usr/sbin/apache2 -k start

7. Check modules are loaded on Apache (Output omitted)

root@nc:~# apache2ctl -M
Loaded Modules:
 core_module (static)
 so_module (static)
 watchdog_module (static)
 http_module (static)
 log_config_module (static)
............

Step3: Install and Configure MariaDB Server

1. Install mariadb-server package

apt install mariadb-server -y

2. Login to MariaDB, Just type the below command, It will drop you to MySQL Prompt.

mysql
root@nc:~# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 1131
Server version: 10.11.7-MariaDB-2ubuntu2 Ubuntu 24.04
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>

3. Create Database and User for Nextcloud and Provide User Permissions.

CREATE USER 'ncloud'@'localhost' IDENTIFIED BY 'Sh@do5!d';
CREATE DATABASE ncloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
GRANT ALL PRIVILEGES ON ncloud.* TO 'ncloud'@'localhost';
FLUSH PRIVILEGES;
quit;

4. Now, restart and enable MariaDB service.

systemctl restart mariadb
systemctl enable mariadb

5. check MariaDB is Running.

root@nc:~# systemctl status mariadb
 mariadb.service - MariaDB 10.11.7 database server
     Loaded: loaded (/usr/lib/systemd/system/mariadb.service; 
     enabled; preset: enabled)
     Active: active (running) since Tue 2024-06-18 04:43:21 UTC; 10s ago
       Docs: man:mariadbd(8)
             https://mariadb.com/kb/en/library/systemd/
   Main PID: 17589 (mariadbd)
     Status: "Taking your SQL requests now..."
      Tasks: 12 (limit: 14975)
     Memory: 78.8M (peak: 81.8M)
        CPU: 573ms
     CGroup: /system.slice/mariadb.service
             └─17589 /usr/sbin/mariadbd
Please enable JavaScript in your browser to complete this form.

Newsletter

Get Special Free Tips, Tricks & Tutorials

Step4: Download Nextcloud, Unzip and Permission

Now download the latest Nextcloud archive. Go to the Nextcloud Download Page Or you can download from this direct link.

1. Download and unzip in the /var/www/html folder

cd /var/www/html
wget https://download.nextcloud.com/server/releases/latest.zip
unzip latest.zip

2. Remove the zip file, which is not necessary now.

rm -rf latest.zip

3. Change the ownership of the nextcloud directory to the HTTP user.

chown -R www-data:www-data /var/www/html/nextcloud/

Step5: Install Nextcloud From Command Line

Now, we will install nextcloud on ubuntu 24.04 LTS from the command line. Configuration will be silent and quicker than going through the web GUI setup. we need to provide database and admin credentials for Command Line installation. you can visit this page to know more about nextcloud CLI installation.

1. Run the below command to install nextcloud (provide your own credentials)

cd /var/www/html/nextcloud
sudo -u www-data php occ  maintenance:install --database \
"mysql" --database-name "ncloud"  --database-user "ncloud" --database-pass \
'Sh@do5!d' --admin-user "admin" --admin-pass "password"

If everything goes well the command will output “Nextcloud was successfully installed”.

2. Nextcloud allows access only from localhost, it could through error “Access through untrusted domain”. we need to allow accessing Nextcloud by using ip or domain name.

vi /var/www/html/nextcloud/config/config.php

  'trusted_domains' =>
  array (
    0 => 'localhost',
    1 => 'nc.mailserverguru.com',   // we Included the Sub Domain
  ),
  .....
:x

3. Configure Apache to load Nextcloud from the /var/www/html/nextcloud folder.

vi /etc/apache2/sites-enabled/000-default.conf

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/nextcloud
        
        <Directory /var/www/html/nextcloud>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
	      </Directory>
        
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

4. Now restart Apache

systemctl restart apache2

Now, Go to the Browser and type http://[ip or fqdn] of the server, The below Nextcloud login page will appear.

ubuntu 24.04 nextcloud login
Nextcloud Login

 

We are done in the 1st phase. We have seen How to install Nextcloud on Ubuntu 24.04.

In the 2nd phase, we will go for the performance tuning, we will install PHP-FPM for PHP files processing, then we will enable various caching system to increase the application performance.

In this Phase we Have 5 Steps:

  1. Install PHP-FPM with Apache
  2. Create info.php Page
  3. Enable OPCache & OPCache-JIT
  4. Enable APCu in PHP
  5. Configure Redis Cache
install nextcloud ubuntu 24.04 phase2

Step6: Install and Configure PHP-FPM with Apache

Here we will install PHP-FPM, which is faster than the mpm-prefork module, which is the default method of executing php files on Apache.

1. Install PHP-FPM

apt install php8.3-fpm

2. Check the PHP-FPM is running, its version and Socket is created.

service php8.3-fpm status
php-fpm8.3 -v
ls -la /var/run/php/php8.3-fpm.sock

3. Disable mod_php and prefork module

a2dismod php8.3
a2dismod mpm_prefork

4. Enable PHP-FPM

a2enmod mpm_event proxy_fcgi setenvif
a2enconf php8.3-fpm

5. Restart Apache to reload all the modules and configurations

systemctl restart apache2

Now, for file upload size and performance settings, we need to tweak some php.ini settings listed below in the /etc/php/8.3/fpm/php.ini file. You can assign your own values depending on your environment.

upload_max_filesize = 64M
post_max_size = 96M
memory_limit = 512M
max_execution_time = 600
max_input_vars = 3000
max_input_time = 1000

6. check the current values.

grep -E "upload_max_filesize|post_max_size|memory_limit|max_execution_time|max_input_vars|max_input_time" /etc/php/8.3/fpm/php.ini

7. Instead of manual change, you can execute the below command to change at once. it will save time.

sed -i 's/^upload_max_filesize.*/upload_max_filesize = 64M/; s/^post_max_size.*/post_max_size = 96M/; s/^memory_limit.*/memory_limit = 512M/; s/^max_execution_time.*/max_execution_time = 600/; s/^;max_input_vars.*/max_input_vars = 3000/; s/^max_input_time.*/max_input_time = 1000/' /etc/php/8.3/fpm/php.ini

Now, we need update PHP-FPM pool Configurations at /etc/php/8.3/fpm/pool.d/www.conf, below are some optimum values, but you should assign your own values.

pm.max_children = 64
pm.start_servers = 16
pm.min_spare_servers = 16
pm.max_spare_servers = 32

8. Check current values.

grep -E "pm.max_children|pm.start_servers|pm.min_spare_servers|pm.max_spare_servers" /etc/php/8.3/fpm/pool.d/www.conf

9. Change all the values at once with the below command.

sed -i 's/^pm.max_children = .*/pm.max_children = 64/; s/^pm.start_servers = .*/pm.start_servers = 16/; s/^pm.min_spare_servers = .*/pm.min_spare_servers = 16/; s/^pm.max_spare_servers = .*/pm.max_spare_servers = 32/' /etc/php/8.3/fpm/pool.d/www.conf

10. Now, restart PHP-FPM to apply all the changes.

service php8.3-fpm restart

Now, Insert the below code to apache’s default site configuration file /etc/apache2/sites-enabled/000-default.conf, it will direct apache to handover the php file processing to PHP-FPM.

	<FilesMatch ".php$">
         SetHandler "proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://localhost/"
	</FilesMatch>

11. After providing the code, apache’s default site configuration will look like the below snippet.

vi /etc/apache2/sites-enabled/000-default.conf 

<VirtualHost *:80>

	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/html/nextcloud

	<Directory /var/www/html/nextcloud>
          Options Indexes FollowSymLinks
          AllowOverride All
          Require all granted
	</Directory>

	<FilesMatch ".php$"> 
          SetHandler "proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://localhost/"
	</FilesMatch>

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

12. Now, Restart Apache to take the change.

systemctl restart apache2

Step7: Create info.php Page for PHP feature check

Create an info.php page, it will show us whether PHP-FPM, OPCache, APCu are enabled with the PHP.

cd /var/www/html/nextcloud

vi info.php
    <?php phpinfo(); ?>
:x

Now, Browse [URL]/info.php. if the PHP-FPM is enabled on the PHP. it will show “Server API FPM/FastCGI”

nextcloud ubuntu 24.04 php-fpm
PHP-FPM is Enabled for Nextcloud

Step8: Enable OPCache in PHP

Opcache is a caching engine for PHP. It stores precompiled script bytecode in shared memory, so parsing PHP scripts on each request won’t be necessary. It increases PHP file execution and website loading performance. Opcache is enabled by default.

1. Check it is running or not from the [URL]/info.php file previously we created.

nextcloud ubuntu 24.04 opcache
PHP OPcache is Enabled for Nextcloud

2. Opcache JIT (Just-In-Time) compilation is an important feature. JIT compilation improves PHP performance by compiling code into machine language at runtime, rather than interpreting it each time it’s executed. This can significantly enhance the performance of CPU-intensive tasks. So it will be very effective to enable it to increase nextcloud performance.

vi /etc/php/8.3/fpm/conf.d/10-opcache.ini

zend_extension=opcache.so
opcache.enable_cli=1
opcache.jit=on
opcache.jit = 1255
opcache.jit_buffer_size = 128M

:x

opcache.enable_cli” this option is not mandatory, but would be very useful if we use nextcloud cli commands or scripts frequently.

3. Restart PHP-FPM to take effect the change.

service php8.3-fpm restart

Now Browse info.php again, it will show all the above features enabled.

nextcloud-ubuntu-24.04-opcache-zit
OPcache and OPcache-JIT is Enabled for Nextcloud

Step9: Enable APCu in PHP

APCu is the user data caching. It is a local cache for systems. Nextcloud uses this for memory caching. we need to enable APCu on CLI which is disabled by default which could cause issues with nextcloud’s cron jobs.

1. Install APCu

apt install php8.3-apcu

2. Enable APCu on CLI.

vi /etc/php/8.3/fpm/conf.d/20-apcu.ini

extension=apcu.so
apc.enable_cli=1

:x

3. Now, Restart PHP-FPM and Apache

systemctl restart php8.3-fpm
systemctl restart apache2

Now, Check the [URL]/info.php again, it will show the “APCu support Enabled”

4. Now, Configure Nextcloud to use APCu for memory caching.

vi /var/www/html/nextcloud/config/config.php

'memcache.local' => '\OC\Memcache\APCu',

:x

Step10: Install and Configure Redis Cache

In Nextcloud, Redis is used for local and distributed caching as well as transactional file locking. we used APCu for Local Caching which is faster than Redis. We will use Redis for File locking. Nextcloud’s Transactional File Locking mechanism locks files to avoid file corruption during normal operation.

1. Install Redis Server and Redis php extension

apt install redis-server php-redis -y

2. Start and Enable the Redis service.

systemctl start redis-server
systemctl enable redis-server

2. Configure Redis to use Unix Socket than ports

vi /etc/redis/redis.conf

port 0
unixsocket /var/run/redis/redis.sock
unixsocketperm 770

:x

3. Add Apache user to the Redis group

usermod -a -G redis www-data

4. Configure Nextcloud for using Redis for File Locking

vi /var/www/html/nextcloud/config/config.php

'filelocking.enabled' => 'true',
'memcache.locking' => '\OC\Memcache\Redis',
'redis' => [
     'host'     => '/var/run/redis/redis.sock',
     'port'     => 0,
     'dbindex'  => 0,
     'password' => '',
     'timeout'  => 1.5,
],

:x

5. Enable Redis session locking in PHP

vi /etc/php/8.3/fpm/php.ini

redis.session.locking_enabled=1
redis.session.lock_retries=-1
redis.session.lock_wait_time=10000

:x

6. Restart Redis, PHP-FPM and Apache

systemctl restart redis-server
systemctl restart php8.3-fpm
systemctl restart apache2

7. You can check the features are enabled on PHP

nextcloud-ubuntu-24.04-redis
Redis is Installed for Nextcloud

We can check Redis use, (by enabling the Redis port in the Redis configuration) by running the command redis-cli MONITOR, during Nextcloud loading it will show live data on the screen.

Now, that we have finished Performance improvement steps. We are going to work for the Security, First of all, we will install an SSL certificate for Nextcloud.

In this Phase we Have 4 Steps:

  1. Install SSL and enable HTTP2
  2. Strict Transport Security
  3. Enable Pretty URL’s
  4. Protection with Firewall
install nextcloud ubuntu 24.04 phase3

Step11: Install SSL and Enable HTTP2

1. We will install the LetsEncrypt certificate, so, first, we need the Certbot tools.

apt install certbot python3-certbot-apache -y

2. with the Certbot tool, let’s request a Certificate for our domain. Execute the command

certbot --apache -d nc.mailserverguru.com
  • Provide Your Email and Accept the Terms. Follow the Image for the Instructions.
nextcloud ssl ubuntu 24
Nextcloud Letsencrypt SSL Setup

3. Enable apache HTTP2 module

a2enmod http2

4. Configure default SSL site for the http2 protocols

vi /etc/apache2/sites-enabled/000-default-le-ssl.conf

<VirtualHost *:443>

        Protocols h2 http/1.1

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/nextcloud
  ......
:x

5. Now restart Apache to enable the HTTP2 Protocol

systemctl restart apache2

4. Test the http2 protocol, by sending an http2 request to the web server.

curl -I --http2 -s https://nc.mailserverguru.com/ | grep HTTP

HTTP/2 200

Or, we can Inspect the Browser while accessing Nextcloud URL, we can easily see the protocol column from the Network tab, and it will show h2 as the protocol which is http2.

http2 check for nextcloud
Nextcloud SSL Http2 Check from the Browser

Step12: Enable Strict Transport Security

HTTP Strict Transport Security, which instructs browsers not to allow any connection to the Nextcloud instance using HTTP, prevents man-in-the-middle attacks. provide the below code in the virtual host configuration for the default SSL.

<IfModule mod_headers.c>
    Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains"
</IfModule>
vi /etc/apache2/sites-enabled/000-default-le-ssl.conf

<VirtualHost *:443>
  ServerName nc.mailserverguru.com

<IfModule mod_headers.c>
    Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains"
</IfModule>

</VirtualHost>

Step13: Enable Pretty URL’s

Pretty URLs remove the "index.php” part in all Nextcloud URLs. It will make URLs shorter and prettier.

vi /var/www/html/nextcloud/config/config.php

'htaccess.RewriteBase' => '/',
                                 
:x

This command will update the .htaccess file for the redirection

sudo -u www-data php --define apc.enable_cli=1 /var/www/html/nextcloud/occ maintenance:update:htaccess

Step14: Access Protection with Firewall

No server can maintain good security without an active firewall policy. after install and configure nextcloud, we have to allow traffic only to specific ports, rest of the ports should be close to the world. if we add more nextcloud apps later, we might need to open new ports to the firewall later.

1. execute the following code’s for the basic Iptables firewall setup.

#!/bin/bash

# Flush all existing rules
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X

# Allow loopback traffic
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# Allow established and related incoming traffic
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow all outgoing traffic
iptables -A OUTPUT -j ACCEPT

# Allow incoming traffic on port 22 (SSH)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow incoming traffic on port 80 (HTTP)
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# Allow incoming traffic on port 443 (HTTPS)
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow ICMP (ping)
iptables -A INPUT -p icmp -j ACCEPT

# Apply security hardening

# Protect against SYN flood attacks
iptables -A INPUT -p tcp ! --syn -m conntrack --ctstate NEW -j DROP
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
iptables -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP
iptables -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP

# Protect against ping flood (limit to 1 ping per second with burst of 3)
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s --limit-burst 3 -j ACCEPT

# Protect against IP spoofing
iptables -A INPUT -s 10.0.0.0/8 -j DROP
iptables -A INPUT -s 172.16.0.0/12 -j DROP
iptables -A INPUT -s 192.168.0.0/16 -j DROP
iptables -A INPUT -s 127.0.0.0/8 -j DROP
iptables -A INPUT -s 224.0.0.0/4 -j DROP
iptables -A INPUT -s 240.0.0.0/5 -j DROP
iptables -A INPUT -s 0.0.0.0/8 -j DROP
iptables -A INPUT -s 169.254.0.0/16 -j DROP

# Log dropped packets (optional)
iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

# Drop all other inbound traffic
iptables -A INPUT -j DROP

# End of script

2. Apply the Iptables Rules through script, follow the below steps.

vi nextcloud_iptables.sh

# copy Iptables Rules from above and Paste here.
    
:x

# Make the script executable
chmod +x nextcloud_iptables.sh

# Run the script 
./nextcloud_iptables.sh 

3. Save the rules permanently. It will reload across reboot.

apt install iptables-persistent netfilter-persistent -y

systemctl enable netfilter-persistent
systemctl start netfilter-persistent

4. If you Update the Rules, you have to save it, so that it can be reloaded across reboot

iptables-save > /etc/iptables/rules.v4

[Note]: Regarding the SSH port, you should only allow your specific node or network to remote access to your nextcloud server.

So, this is it.. 🤗

We have done our Complete Guide on How to Install Nextcloud On Ubuntu 24.04 LTS.

Now It’s Your Turn

I hope this guide will help you to Install NextCloud On Ubuntu 24.04 LTS successfully. I have tried to show you the Installation in step-by-step approach.

If you face any issue or have any dought on any stage, please let me know on the comment section below 👇

Thank You !!

Rahman Munna
Rahman Munna

Rahman Munna is an accomplished IT professional with over 15 years of experience specializing in System Administration across Linux, Windows, and Virtualization Technologies. With a strong focus on Email and Web Server Administration, Rahman has a proven track record of managing and optimizing complex IT infrastructures for multinational organizations.

12 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Hi
    I followed your instructions but when I login and admin its supposed to go to the dashboard but I only get this error:
    Internal Server Error

    The server encountered an internal error and was unable to complete your request.
    Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.
    More details can be found in the server log.

    Any ideas?
    thanks

    • An “Internal Server Error” typically occurs when there is a program incompatibility within the system. This error is related to the server. Please ensure that all supported packages are installed and properly configured. For detailed instructions, refer to the video provided. I hope this resolves the issue. Thank you!

  2. i follow the intruction, after install nexcloud i try to login with password i set on command and cannot login

    cd /var/www/html/nextcloud
    sudo -u www-data php occ maintenance:install –database \
    “mysql” –database-name “ncloud” –database-user “ncloud” –database-pass \
    ‘mypassword’ –admin-user “admin” –admin-pass “mypassword”

  3. Thank you for your amazing tutorial.

    I would to use an external reverse-proxy, like Zoraxy. What is your advice?

    Best regards
    Coco