How to install NextCloud in Ubuntu 22.04

8 min read

Step-by-Step NextCloud Installation on Ubuntu 22.04.

What’s NextCloud

Nextcloud is an open-source software suite that offers a secure, self-hosted alternative to popular cloud storage and productivity platforms. With a focus on privacy and control over data, Nextcloud enables individuals and businesses to deploy their private cloud services, including file sharing, collaboration tools, and communication features, on their servers.

The platform’s functionality resembles services like Google Drive, Dropbox, or Microsoft OneDrive, but with Nextcloud, users retain full ownership and control over their data. It supports file sharing, calendar and contact management, task scheduling, and real-time document editing with collaborative tools similar to those found in Google Docs and Microsoft Office 365. Moreover, Nextcloud can be extended via apps to include features like email, video conferencing, and more, creating a comprehensive ecosystem for digital collaboration and communication.


  • Linux Ubuntu 22.04 LTS
  • PHP v8.2
  • MySQL DB
  • NGINX / Apache
  • Redis for caching
  • Let’s Encrypt for SSL/HTTPS

Installing packages

PHP modules with FPM

add-apt-repository ppa:ondrej/php
apt update && apt install -y imagemagick php8.2-{apcu,bcmath,imagick,curl,common,fpm,gd,gmp,intl,imap,ldap,mbstring,memcache,memcached,mysql,redis,smbclient,xml,zip}

MySQL DB Server

apt install -y mysql-server


apt install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring

curl | gpg --dearmor \
| sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \ `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list
apt update && apt install -y nginx


apt install -y redis

Let’s Encrypt

apt install -y certbot



Configuring PHP-FPM with Nginx is a critical setup for optimizing web applications, especially on virtual machines (VMs) where resource allocation like CPU and RAM directly impacts performance. PHP-FPM (FastCGI Process Manager) efficiently manages PHP processes, offering enhanced speed and scalability for websites. When combined with the lightweight and high-performance Nginx server, it becomes a powerful stack for running PHP-based applications.

It’s important to fine-tune PHP-FPM settings like pm.max_childrenpm.start_servers, and pm.max_requests to match the VM’s CPU and RAM capacity, ensuring optimal utilization of resources without overloading the server. For accurately calculating these PHP-FPM settings based on your VM’s specific CPU and RAM configurations, visit PHP-FPM Calculator. This tool simplifies the process, helping you achieve a balanced, efficient server environment.

Enable PHP Modules for NextCloud

mkdir /var/big_temp_file/
chown www-data.www-data /var/big_temp_file/

tee /etc/php/8.2/mods-available/nextcloud.ini >/dev/null <<EOF
; configuration for nextcloud
; priority=99
# cache
apc.enable_cli = 1
opcache.enable = 1
opcache.save_comments = 1
opcache.revalidate_freq = 60
opcache.validate_timestamps = 0
opcache.jit = 1255
opcache.jit_buffer_size = 128M

# upload
memory_limit = -1
upload_max_filesize = 1G
post_max_size = 1G
max_input_time = 3600
max_execution_time = 3600
upload_tmp_dir = /var/big_temp_file/


phpenmod nextcloud

Create PHP-FPM pool for NextCloud

tee /etc/php/8.2/fpm/pool.d/nextcloud.conf >/dev/null <<EOF
user = www-data
group = www-data
listen = /run/php/nextcloud.sock
listen.owner = www-data = www-data
pm = dynamic
pm.max_children = 86
pm.start_servers = 21
pm.min_spare_servers = 21
pm.max_spare_servers = 64
clear_env = no

systemctl restart php8.2-fpm.service


MySQL configuration plays a crucial role in optimizing database performance and resource usage. Proper MySQL optimization ensures a smoother, more reliable database operation.

tee /etc/mysql/mysql.conf.d/nextcloud.cnf >/dev/null <<EOF
skip_name_resolve = 1
innodb_buffer_pool_size = 128M
innodb_buffer_pool_instances = 1
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 32M
innodb_max_dirty_pages_pct = 90
tmp_table_size= 64M
max_heap_table_size= 64M
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1

default-character-set = utf8mb4

character_set_server = utf8mb4
collation_server = utf8mb4_general_ci
transaction_isolation = READ-COMMITTED
binlog_format = ROW

systemctl restart mysql


Redis, an in-memory data structure store known for its speed and versatility, can be configured to listen on a TCP port and also to communicate through Unix domain sockets. This dual capability allows Redis to be highly flexible in different deployment scenarios, enhancing both security and performance.

usermod -a -G redis www-data
mkdir /var/run/redis
chown redis.redis /var/run/redis/

vim /etc/redis/redis.conf
# Comment these line:

# bind ::1
# port 6379

# Then uncomment this
unixsocket /var/run/redis/nextcloud.sock
unixsocketperm 770

systemctl restart redis
ls /var/run/redis/

Let’s Encrypt

Let’s Encrypt is a free, automated, and open Certificate Authority (CA) that provides digital certificates to enable HTTPS (SSL/TLS) on web servers, thereby securing server-client communications. It’s widely used because it eliminates the manual creation, validation, installation, and renewal of certificates for secure websites. The primary reasons for using Let’s Encrypt include its cost-effectiveness (it’s free), the automation of certificate management processes, and enhancing web security by encrypting data in transit.

certbot certonly --standalone -n --agree-tos -m [email protected] -d --pre-hook "systemctl stop nginx" --post-hook "systemctl start nginx"

# Set cronjob for SSL renewal
crontab -e

0  0,12 *  *  * certbot renew -q

make sure the domain already pointing to your server IP


Using Nginx as the web server for Nextcloud deployments is a popular choice for several compelling reasons, primarily revolving around performance, efficiency, and security.

vim /etc/nginx/conf.d/nextcloud.conf 

upstream php-handler {
    server unix:/run/php/nextcloud.sock;

# Set the `immutable` cache control options only for assets with a cache busting `v` argument
map $arg_v $asset_immutable {
    "" "";
    default ", immutable";

server {
    listen 80      default_server reuseport;
    listen [::]:80 default_server reuseport;

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # Enforce HTTPS
    return 301 https://$server_name$request_uri;

server {
    listen 443      ssl http2 default_server reuseport;
    listen [::]:443 ssl http2 default_server reuseport;

    # Path to the root of your installation
    root /var/www/nextcloud;

    # Use Mozilla's guidelines for SSL/TLS settings
    ssl_certificate     /etc/letsencrypt/live/;
    ssl_certificate_key /etc/letsencrypt/live/;

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # HSTS settings
    # WARNING: Only add the preload option once you read about
    # the consequences in This option
    # will add the domain to a hardcoded list that is shipped
    # in all major browsers and getting removed from this list
    # could take several months.
    add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;

    # set max upload size and increase upload timeout:
    client_max_body_size 512M;
    client_body_timeout 300s;
    fastcgi_buffers 64 4K;

    # Enable gzip but do not remove ETag headers
    gzip on;
    gzip_vary on;
    gzip_comp_level 4;
    gzip_min_length 256;
    gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
    gzip_types application/atom+xml text/javascript application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/ application/wasm application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

    # Pagespeed is not supported by Nextcloud, so if your server is built
    # with the `ngx_pagespeed` module, uncomment this line to disable it.
    #pagespeed off;

    # The settings allows you to optimize the HTTP2 bandwidth.
    # See
    # for tuning hints
    client_body_buffer_size 512k;

    # HTTP response headers borrowed from Nextcloud `.htaccess`
    add_header Referrer-Policy                   "no-referrer"       always;
    add_header X-Content-Type-Options            "nosniff"           always;
    add_header X-Frame-Options                   "SAMEORIGIN"        always;
    add_header X-Permitted-Cross-Domain-Policies "none"              always;
    add_header X-Robots-Tag                      "noindex, nofollow" always;
    add_header X-XSS-Protection                  "1; mode=block"     always;

    # Remove X-Powered-By, which is an information leak
    fastcgi_hide_header X-Powered-By;

    # Set .mjs and .wasm MIME types
    # Either include it in the default mime.types list
    # and include that list explicitly or add the file extension
    # only for Nextcloud like below:
    include mime.types;
    types {
        text/javascript js mjs;
	      application/wasm wasm;

    # Specify how to handle directories -- specifying `/index.php$request_uri`
    # here as the fallback means that Nginx always exhibits the desired behaviour
    # when a client requests a path that corresponds to a directory that exists
    # on the server. In particular, if that directory contains an index.php file,
    # that file is correctly served; if it doesn't, then the request is passed to
    # the front-end controller. This consistent behaviour means that we don't need
    # to specify custom rules for certain paths (e.g. images and other assets,
    # `/updater`, `/ocs-provider`), and thus
    # `try_files $uri $uri/ /index.php$request_uri`
    # always provides the desired behaviour.
    index index.php index.html /index.php$request_uri;

    # Rule borrowed from `.htaccess` to handle Microsoft DAV clients
    location = / {
        if ( $http_user_agent ~ ^DavClnt ) {
            return 302 /remote.php/webdav/$is_args$args;

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;

    # Make a regex exception for `/.well-known` so that clients can still
    # access it despite the existence of the regex rule
    # `location ~ /(\.|autotest|...)` which would otherwise handle requests
    # for `/.well-known`.
    location ^~ /.well-known {
        # The rules in this block are an adaptation of the rules
        # in `.htaccess` that concern `/.well-known`.

        location = /.well-known/carddav { return 301 /remote.php/dav/; }
        location = /.well-known/caldav  { return 301 /remote.php/dav/; }

        location /.well-known/acme-challenge    { try_files $uri $uri/ =404; }
        location /.well-known/pki-validation    { try_files $uri $uri/ =404; }

        # Let Nextcloud's API for `/.well-known` URIs handle all other
        # requests by passing them to the front-end controller.
        return 301 /index.php$request_uri;

    # Rules borrowed from `.htaccess` to hide certain paths from clients
    location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
    location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

    # Ensure this block, which passes PHP files to the PHP process, is above the blocks
    # which handle static assets (as seen below). If this block is not declared first,
    # then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
    # to the URI, resulting in a HTTP 500 error response.
    location ~ \.php(?:$|/) {
        # Required for legacy support
        rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|ocs-provider\/.+|.+\/richdocumentscode(_arm64)?\/proxy) /index.php$request_uri;

        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        set $path_info $fastcgi_path_info;

        try_files $fastcgi_script_name =404;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $path_info;
        fastcgi_param HTTPS on;

        fastcgi_param modHeadersAvailable true;         # Avoid sending the security headers twice
        fastcgi_param front_controller_active true;     # Enable pretty urls
        fastcgi_pass php-handler;

        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;

        fastcgi_max_temp_file_size 0;

    # Serve static files
    location ~ \.(?:css|js|mjs|svg|gif|png|jpg|ico|wasm|tflite|map|ogg|flac)$ {
        try_files $uri /index.php$request_uri;
        # HTTP response headers borrowed from Nextcloud `.htaccess`
        add_header Cache-Control                     "public, max-age=15778463$asset_immutable";
        add_header Referrer-Policy                   "no-referrer"       always;
        add_header X-Content-Type-Options            "nosniff"           always;
        add_header X-Frame-Options                   "SAMEORIGIN"        always;
        add_header X-Permitted-Cross-Domain-Policies "none"              always;
        add_header X-Robots-Tag                      "noindex, nofollow" always;
        add_header X-XSS-Protection                  "1; mode=block"     always;
        access_log off;     # Optional: Don't log access to assets

    location ~ \.woff2?$ {
        try_files $uri /index.php$request_uri;
        expires 7d;         # Cache-Control policy borrowed from `.htaccess`
        access_log off;     # Optional: Don't log access to assets

    # Rule borrowed from `.htaccess`
    location /remote {
        return 301 /remote.php$request_uri;

    location / {
        try_files $uri $uri/ /index.php$request_uri;

rm -fv /etc/nginx/conf.d/default.conf
systemctl restart nginx

make sure the SSL Certificate from Let’s Encrypt already setup.

Install NextCloud

Installation of Nextcloud is straightforward, especially on popular Linux distributions like Ubuntu. This flexibility allows users, ranging from tech enthusiasts to large enterprises, to set up and customize their cloud to fit specific needs, ensuring data security and privacy without relying on third-party cloud providers.

Nextcloud’s emphasis on data sovereignty, combined with its rich feature set and the community’s robust support, makes it an attractive choice for anyone looking to manage their cloud services. Whether for personal use, within an organization, or for offering professional services, Nextcloud provides a versatile platform on which to build a variety of cloud-based solutions.

Create DB credentials

CREATE USER 'nextcloud'@'localhost' IDENTIFIED BY 'P455W0RD_DB';
CREATE DATABASE IF NOT EXISTS nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
GRANT ALL PRIVILEGES on nextcloud.* to 'nextcloud'@'localhost';

Installing via CLI

mkdir -p /var/www
mv nextcloud /var/www
chown -R www-data:www-data /var/www/nextcloud

cd /var/www/nextcloud/
sudo -u www-data php occ  maintenance:install \
--database='mysql' --database-name='nextcloud' \
--database-user='nextcloud' --database-pass='P455W0RD_DB' \
--admin-user='admin' --admin-pass='P455W0RD_NextCloud' \

sudo -u www-data php occ config:system:set trusted_domains 1
sudo -u www-data php occ config:system:set trusted_domains 2 --value=[::1]
sudo -u www-data php occ config:app:set files max_chunk_size --value 20971520


Leave a Reply

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