Nextcloud en Debian 13 + Nginx + PHP-FPM 8.4
Nextcloud is open-source software for creating public and private file storage. It allows you to create your self-hosted services like Dropbox, Google Drive, or Mega.nz. Originally, it's created by the original owncloud developer Frank Karlitschek. In 2016, he forks the Owncloud project and creates a new project with the new name "Nextcloud"
ByDocumentothisantialzheimertime,técnico.
theSiNextcloudestásprojectleyendogrowingestorapidlyesandporquebecomingyamore than file hosting software, it's more like a file sync and content collaboration platform. Backed with a lot of plugins, Nextcloud becomes such a powerful collaboration software. You can install plugins for project management, video conferencing, collaborative editing, note-taking, email client, etc.
In this guide, you will learn how to install Nextcloud on the latest Debian 11 Bullseye. You will be installing Nextcloud under the LAMP Stack (Linux, Apache2/httpd, MySQL/MariaDB, and PHP)sufriste.
Prerequisites
Este cookbook está limpiado (sin retales contradictorios) y orientado a:
ADebian11 server. Ensure all packages are updated to the latest version13APHP-FPMroot8.4.x- Nginx
or(noaApache) - MariaDB
- Redis
root(cachingprivileges.+Thisfileuser will be used for installing new packages and editing system configurations; If you don’t have a user with sudo, in the next section we will see how to add a new user and give him sudo powerslocking)
How0) ToVariables Addque Userustedes indefinen Debianuna vez
InAjusta Debian, there are two command-line tools that you can use to createesto a newtu usercaso account:y mantégalo useraddand adduser.
useradd is a low-level utility for adding users while the adduser a friendly interactive frontend to useradd written in Perl.
To create a new user account named username using the adduser command you would run:consistente:
sudo# adduserDominio usernamepúblico
NC_DOMAIN="files.example.com"
Example# output:
AddingNC_WEBROOT="/var/www/nextcloud" user# `username'código
...NC_DATA="/srv/nextcloud-data" Adding# new group `username'datos (1001)recomendado ...fuera Addingde newwebroot)
user# `username'Base (1001)de withdatos
groupNC_DB="nextcloud"
`username'NC_DB_USER="nextclouduser"
...NC_DB_PASS="CAMBIAR_ESTO"
Creating# homeRedis
directory `/home/username' ...
Copying files from `/etc/skel' ...
You will be asked a series of questions. The password is required, and all other fields are optional.
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for username
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n]
On the last prompt you’ll need to confirm that the information is correct by entering “Y”.
The command will create the new user’s home directory, and copy files from /etc/skel directory to the user’s home directory. Within the home directory, the user can write, edit, and delete files and directories.
By default on Debian, members of the group sudo are granted with sudo access.
If you want the newly created user to have administrative rights, add the user to the sudo group:
sudo usermod -aG sudo usernameREDIS_PASS="CAMBIAR_ESTO"
How1) ToBase Deletedel a User in Debiansistema
If the user account is no longer needed, you can delete it either with userdel or deluser. On Debian, you should usually use the deluser command as it is more friendly than the low-level userdel.
To delete the user, without removing the user files, run:
sudo deluserapt usernameupdate
If you want to delete the user and its home directory and mail spool, use the --remove-home flag:
sudo deluserapt -y full-upgrade
sudo apt -remove-homey usernameinstall ca-certificates curl unzip gnupg lsb-release bzip2 vim-tiny
SSH2) serverMariaDB
Get Root and Update Repositories
First, execute the following command to get the root privileges.
If you havesudoinstalled, execute the sudo command below:
sudo suapt -y install mariadb-server mariadb-client
sudo systemctl enable --now mariadb
sudo mysql_secure_installation
NowCrear typeDB they passwordusuario login for your user.(utf8mb4):
If you don't have the sudo package, execute thesucommand as below:
susudo mysql Now type your-u root password-p and<<SQL
pressCREATE DATABASE ${NC_DB} CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER '${NC_DB_USER}'@'localhost' IDENTIFIED BY '${NC_DB_PASS}';
GRANT ALL PRIVILEGES ON ${NC_DB}.Enter
- TO
After'${NC_DB_USER}'@'localhost';that,FLUSHupdatePRIVILEGES;all your Debian repositories using the apt command below:
apt updateSQL
Installing3) ApachePHP Web8.4 Server+ PHP-FPM
After
3.1 updatingPaquetes
Execute thesudo aptcommand below to-y installthephp8.4-fpmapachephp8.4-cliwebphp8.4-commonserver:\
aptphp8.4-curl installphp8.4-zip apache2php8.4-xml php8.4-mbstring \
php8.4-intl php8.4-bz2 php8.4-bcmath php8.4-gmp \
php8.4-imagick php8.4-mysql \
php8.4-redis
TypeSi en su mirror no existeyand pressEnterto continue the installation.
If the installation is complete, check the apache service using the following command:systemctl is-enabled apache2 systemctl status apache2
You will see the output,enabledphp8.4-*whichentoncesmeanssutheDebianapachenoservicetraewillesaautomaticallyversiónstartenatesesystemmomentostartup.yAndtocaráthereposcurrentalternativostateoofbajartheaapachelaservice,versiónit'sdisponible. No inventen compatibilidad: miren la matriz PHP/Nextcloud de su release.
3.2 Ajustes PHP-FPM
Recomendación práctica: no toquen active (running).
Next, enable Apache modulesssl,rewrite, andheadersphp.inibyaexecutingmanotheparatodo.a2enmodcommandCreenbelow:un
a2enmod ssl rewrite headers
After that, execute the following command to restart the apache service:
systemctl restart apache2
New apache modules will be applied, verify those modules using the apachectl command below:
apachectl -M | egrep "ssl|rewrite|headers"
Installing and Configuring PHP
For this guide, you will be deploying Nextcloud with the latest stable version of PHP 8.1.propio.
By default, the Debian repository provides packages for PHP 8.1. But, Nextcloud requires some additional PHP packages that can be installed from a 3rd-party repository. And you will be adding a new repository to your Debian system.
Execute the command below to add a PHP repository for the Debian system:
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main"\ | sudo tee /etc/apt/sources.list.d/sury-php.list
Download the GPG key to the /etc/apt/trusted.gpg.d directory:
curl -o /etc/apt/trusted.gpg.d/sury-php8.gpg https://packages.sury.org/php/apt.gpg
Now run the apt update command again to update all repositories:
apt update
Install PHP packages and additional PHP modules for Nextcloud using the apt command below:
apt install -y php php-curl php-cli php-mysql php-gd php-common php-xml php-json php-intl php-pear php-imagick php-dev php-common php-mbstring php-zip php-soap php-bz2 php-bcmath php-gmp php-apcu
After that, execute the apt command again for installing some additional packages:
apt install -y libmagickcore-dev
The libmagickcore-dev packages are needed by the php-imagick for SVG image processing on Nextcloud.
If all packages installation is complete, change the working directory toCrear/etc/php/8.1/apache2and edit the configurationphp.4/fpm/conf.d/99-nextcloud.iniusing nano:
cd /etc/php/8.1/apache2/
nano php.ini
For the basic nextcloud deployment, change the default options using the following configuration (here: https://www.php.net/manual/en/timezones.php you can check the correct timezone for your installation):
file_uploads; === OnNextcloud allow_url_fopensane defaults = On==
memory_limit = 512M
upload_max_filesize = 1G2G
post_max_size = 2G
max_execution_time = 300360
display_errorsmax_input_time = Off
date.timezone = (see the above note)360
output_buffering = Off
expose_php Uncomment= theOff
; zend_extension=opcacheoptionAjusten toa loadsu thezona
opcachedate.timezone extension:
zend_extension=opcacheAtlantic/Canary
; OPcache (básico)
opcache.enable=1
opcache.enable_cli=1
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.memory_consumption=256
opcache.save_comments=1
opcache.revalidate_freq=60
MoveReiniciar toy the [opcache] section and add the following configuration:habilitar:
[opcache]sudo ...systemctl ....
.....
opcache.enable =--now 1php8.4-fpm
opcache.interned_strings_buffersudo = 8
opcache.max_accelerated_files = 10000
opcache.memory_consumption = 128
opcache.save_comments = 1
opcache.revalidate_freq = 1
Save the configuration by pressing Ctrl+x and type y, then press Enter to exit.
Now restart the apache service to apply new changes using the command below:
systemctl restart apache2php8.4-fpm
Installing4) andRedis Configuring(caché MariaDB+ file locking)
For
sudo thisapt stage, you will be installing the mariadb database server, securing mariadb deployment, and creating a new database and user for Nextcloud.
To-y install the mariadb database server, run the command below:
apt install mariadb-redis-server
mariadb-clientsudo systemctl enable --now redis-server
TypeEndurecer mínimo (local only + contraseña):
Editar y/etc/redis/redis.conf to confirm and install mariadb packages.:
Once the installation is complete, check the mariadb service using the following command:
systemctlbind is-enabled127.0.0.1 mariadb::1
systemctlprotected-mode statusyes
mariadbrequirepass CAMBIAR_ESTO
The mariadb service is active and running, and it's enabled to start automatically at system startup.
Next, you need to secure your mariadb deployment by setting up the root password for mariadb and remove some default configuration. To do that, you can use the command-line tool mysql_secure_installation, which is included on the default mariadb installation.
Execute the mysql_secure_installation command below:Reiniciar:
mysql_secure_installationsudo
systemctl Interactiverestart prompts (example):
Enter current password for root (enter for none):
OK, successfully used password, moving on...
Switch to unix_socket authentication [Y/n] Y
Enabled successfully!
Reloading privilege tables..
... Success!
Change the root password? [Y/n] Y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!
Remove anonymous users? [Y/n] Y
... Success!
Disallow root login remotely? [Y/n] Y
... Success!
Remove test database and access to it? [Y/n] Y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reload privilege tables now? [Y/n] Y
... Success!
Final message (example):
Cleaning up...
All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!redis-server
Creating5) DatabaseNginx and+ UserTLS for(Let’s NextcloudEncrypt)
5.1
LogInstalar inNginx toy the mariadb shell using the mysql command below:
Certbot
mysqlsudo apt -uy rootinstall nginx
sudo systemctl enable -p-now nginx
sudo apt -y install certbot python3-certbot-nginx
5.2
Now execute the following mysql query to create a new database nextcloud (or whatever else you choose to name it):
Certificado
CREATEsudo DATABASEcertbot nextcloud;--nginx -d "${NC_DOMAIN}"
Execute6) theDescargar following query to create a new database user nextclouduserNextcloud (orfuente whatever else you choose to name it). Change the strongpassword with your strong password.
oficial)
CREATEsudo USERinstall nextclouduser@localhost-d IDENTIFIED-m BY0755 'StrongPassword';
Allow the user nextclouduser to access and write the nextcloud database using the following query:
GRANT ALL PRIVILEGES ON nextcloud.* TO nextclouduser@localhost;
Now reload all tables privileges to apply the new database configuration:
FLUSH PRIVILEGES;
Then you can type quit and press Enter to exit from the mariadb shell.
Download Nextcloud Source Code
Change the working directory to /var/www
and download the latest version of Nextcloud source code using the wget command as below:
cd /var/www/www
curl -L -o nextcloud.ziptar.bz2 https://download.nextcloud.com/server/releases/nextcloud-25.0.1.ziplatest.tar.bz2
sudo tar Now-xjf installnextcloud.tar.bz2
the unzip package using the following command:
apt install unzip
Next, extract the Nextcloud source code nextcloud.zip and you will get a new directory nextcloud, then change the owner of the nextcloud directory to www-data user:
unzip nextcloud-22.1.0.zipsudo chown -R www-data:www-data nextcloud
sudo Nowchmod you're-R ready0750 to generate SSL Letsencrypt and configuring apache virtual host for Nextcloud.
Generating SSL Letsencrypt
In this stage, you will be installing the certbot tool and generate the SSL certificates for the Nextcloud installation. You will be generating SSL Letsencrypts with the webroot plugin.
Execute the following command to install the certbot tool for generating SSL Letsencrypt:
apt install certbotnextcloud
Type y and press Enter to continue the installation.
Once the installation is complete, create a newData directory forfuera letsencryptdel authorization using the following commands:
mkdir -p /var/lib/letsencrypt/.well-known
chgrp www-data /var/lib/letsencrypt
chmod g+s /var/lib/letsencrypt
Next, change the working directory to the /etc/apache2/conf-available/ and create a new configuration well-known.conf using nano:
cd /etc/apache2/conf-available/
nano well-known.conf
Copy and paste the following configuration:webroot:
Alias /.well-known/acme-challenge/ "/var/lib/letsencrypt/.well-known/acme-challenge/"
<Directory "/var/lib/letsencrypt/">
AllowOverride None
Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
Require method GET POST OPTIONS
</Directory>
Press Ctrl+x and type y and press Enter to save the configuration and exit.
Now activate the new configuration by creating a symlink of the well-known.conf file to the directory conf-enabled using the ln command below:
ln -s /etc/apache2/conf-available/well-known.conf /etc/apache2/conf-enabled/
Now execute the following commands to verify the apache configuration and restart the apache service:
apachectl configtest
systemctl restart apache2
If you've no error, you're ready to generate SSL Letsencrypt with the webroot plugin.
Before generating SSL Letsencrypt, ensure your domain name is resolved to the server IP address. After that, you can generate SSL Letsencrypt with the webroot plugin by running the certbot command below. Also, change the email address and domain name to your own.
sudo certbot certonly --agree-tos --email user@email.com --webroot -w /var/lib/letsencrypt/install -d files.domain-name.io-o www-data -g www-data -m 0770 "${NC_DATA}"
7) Nginx vhost base (genérico)
When the process is complete, your SSL certificates are available at theCrear /etc/letsencrypt/live/files.domain-name.io/ directory.
Setup Apache Virtual Host for Nextcloud
In this step, you will be adding a new apache/httpd virtual host configuration for Nextcloud.
Change the working directory to /etc/apache2/nginx/sites-available/ and create new configuration nextcloud.conf using nano:
cd /etc/apache2/sites-available/
nano nextcloud.conf
Change the detail domain name and SSL path directory to your own and paste the configuration to the nextcloud.conf file (change the string files.domain-name.io to the domain you are installing the nextcloud instance).:
<VirtualHostupstream *php-handler {
server unix:/run/php/php8.4-fpm.sock;
}
server {
listen 80;
listen [:80>:]:80;
ServerNameserver_name files.domain-name.ioexample.com;
ServerAliasreturn www.files.domain-name.io
# auto redirect HTTP to HTTPS
Redirect permanent /301 https://files.domain-name.io/$host$request_uri;
</VirtualHost>}
<VirtualHostserver *{
listen 443 ssl http2;
listen [::]:443> ServerNamessl http2;
server_name files.domain-name.ioexample.com;
ServerAlias www.files.domain-name.io
DocumentRootroot /var/www/nextcloud/nextcloud;
Protocols h2 http/1.1
# auto redirect www to non-www
<If "%{HTTP_HOST} == 'www.files.domain-name.io'">
Redirect permanent / https://files.domain-name.io/
</If>
# log files
ErrorLog /var/log/apache2/files.domain-name.io-error.log
CustomLog /var/log/apache2/files.domain-name.io-access.log combined
SSLEngine On
SSLCertificateFilessl_certificate /etc/letsencrypt/live/files.domain-name.io/example.com/fullchain.pempem;
SSLCertificateKeyFilessl_certificate_key /etc/letsencrypt/live/files.domain-name.io/example.com/privkey.pempem;
# HSTSAjusten <IfModuletamaño mod_headers.c>según Headersu alwaysrealidad
setclient_max_body_size 2G;
fastcgi_buffers 64 4K;
add_header Strict-Transport-Security "max-age=15552000; includeSubDomains" <always;
index index.php index.html /IfModule>index.php$request_uri;
<Directoryaccess_log /var/www/nextcloud/>log/nginx/nextcloud.access.log;
Options +FollowSymlinks
AllowOverride All
<IfModule mod_dav.c>
Dav off
</IfModule>
SetEnv HOMEerror_log /var/www/nextcloudlog/nginx/nextcloud.error.log;
SetEnvlocation HTTP_HOME= /var/www/nextcloudrobots.txt <{ allow all; log_not_found off; access_log off; }
location = /Directory>.well-known/carddav <{ return 301 $scheme:/VirtualHost>/$host/remote.php/dav; }
location = /.well-known/caldav { return 301 $scheme://$host/remote.php/dav; }
location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ { deny all; }
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) { deny all; }
location ~ \.php(?:$|/) {
rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+)\.php(/.*)$ /index.php$request_uri;
include fastcgi_params;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param HTTPS on;
fastcgi_param modHeadersAvailable true;
fastcgi_param front_controller_active true;
fastcgi_pass php-handler;
fastcgi_intercept_errors on;
fastcgi_request_buffering off;
}
location ~ \.(?:css|js|woff2?|svg|gif|map|png|jpg|jpeg|ico)$ {
try_files $uri /index.php$request_uri;
expires 6M;
access_log off;
}
location / {
try_files $uri $uri/ /index.php$request_uri;
}
}
Press Ctrl+x and type Y, then press Enter to save the configuration and exit.Activar:
Now activate the nextcloud.conf virtual host configuration by executing the following command:
a2ensitesudo ln -sf /etc/nginx/sites-available/nextcloud.conf
/etc/nginx/sites-enabled/nextcloud.conf
sudo Nownginx verify-t
the new apache configuration and make sure you have no error, then restart the apache service:
apachectl configtestsudo systemctl restartreload apache2nginx
Mounting8) anInstalación externalde andNextcloud settingpor automounting with fstab
If you want to use an external disk to store the dataCLI (i.e. the internal disk is a 128GB SSD, and you think it will not have enough space in the future), you need some litlle thing to do before starting the real installation; that’s because you have to pass the “data folder” path while installing.
We assume that you have a formatted (external) disk connected to your “Nextcloud box”; how to format a disk is out of the scope of this book.
To mount, and automount via fstab a disk you have to follow this steps:
List all the disk mounted in your disk:
repetible)
root@***:/# fdisk -l
Disk /dev/sda: 238.47 GiB, 256060514304 bytes, 500118192 sectors
Disk model: KINGSTON SKC6002
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: 0A40E05A-39BE-4E1C-8615-E89A7120B3EB
Device Start End Sectors Size Type
/dev/sda1 2048 1050623 1048576 512M EFI System
/dev/sda2 1050624 498116607 497065984 237G Linux filesystem
/dev/sda3 498116608 500117503 2000896 977M Linux swap
Disk /dev/sdb: 1.82 TiB, 2000398934016 bytes, 3907029168 sectors
Disk model: RAID
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: E56B6393-517A-4AFD-95D6-4CC40ED1F81F
Device Start End Sectors Size Type
/dev/sdb1 2048 3907028991 3907026944 1.8T Linux filesystem
The disk we want to use is mounted on /dev/sdb.
Type the command file -s /dev/sdb and press Enter to find the file system of the drive, replacing /dev/sdb with the correct device name.
The FAT32 file system will be listed after OEM-ID as mkdosfs
The NTFS file system will be listed as NTFS
If EXT4 is listed in the results of the command, the drive uses the Linux EXT4 file system (this is our case).
Create a mount point for your device by typing mkdir /mnt/ext and pressing Enter.
A mount point is simply a directory where the files from your drive will be linked so that you can locate them.
The directory name, ext in the example, can be any name that you would like, just avoid using spaces and remember that the name is case-sensitive.
Mount the device with the mount -t vfat /dev/sdb /mnt/ext command, followed by the Enter key.
The notation /dev/sdb means all the physical disk, while /dev/sdb1 means only the specific logic volume on the physical disk; in this case we are using the whole disk.
Replace sdb and ext with the appropriate device and directory. Replace vfat (used for FAT32 file systems) with ntfs-3g for NTFS file systems or ext4 for EXT4 file systems.
To unmount the drive when you are finished, type umount /dev/sdb and press Enter.
Now that we know what disk we’ll use, we need an UUID, we’ll read it trough the blkid command:
root@***:# blkid /dev/sdb
/dev/sdb: PTUUID="e56b6393-517a-4afd-95d6-4cc40ed1f81f" PTTYPE="gpt"
root@***:# blkid /dev/sdb1
/dev/sdb1: LABEL="***" UUID="9a4d9706-4fa5-4f9e-9d45-9b6f03099ea2" BLOCK_SIZE="4096" TYPE="ext4" PARTUUID="2c62e3ca-9c0c-4455-a939-960b5c089846"
We’re gonna mount the logical volume (sdb1) so we need this UUID to set in /etc/fstab, use less to see without modify the actual fstab:
root@***:/# less /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# systemd generates mount units based on this file, see systemd.mount(5).
# Please run 'systemctl daemon-reload' after making changes here.
#
# <file system> <mount point> <type> <options> <dump> <pass>
# / was on /dev/sda2 during installation
UUID=7e3f4840-09d6-446c-b5f8-ae221c166ad0 / ext4 errors=remount-ro 0 1
# /boot/efi was on /dev/sda1 during installation
UUID=6969-2748 /boot/efi vfat umask=0077 0 1
# swap was on /dev/sda3 during installation
UUID=c14bcfe3-0f5d-461c-8a5a-e19a63f45908 none swap sw 0 0
UUID="9a4d9706-4fa5-4f9e-9d45-9b6f03099ea2" /media/ext auto rw,user,auto 0 0
UUID=9a4d9706-4fa5-4f9e-9d45-9b6f03099ea2 /media/ext auto defaults 0 0
As you can see the system write some information during installation, but some other we have to modify: this are the UUID="9a4d9706-4fa5-4f9e-9d45-9b6f03099ea2" /media/ext auto rw,user,auto 0 0 line, the other line was added directly from systemd.
Now that we have the correct fstab we can issue the command systemctl daemon-reload and proceed to install the nextcloud instance.
Nextcloud Installation
Open your web browser and type the URL address of your Nextcloud installation:
https://files.domain-name.io
Create your first and admin user for Nextcloud and the data directory is writable by the user `www-data’.
Scroll the page to the bottom, type details database name, user, and the password. For the option Install recommended apps, uncheck it to make installation faster. Then click the Finish setup button to install Nextcloud.
If the installation is successful, you will see the Nextcloud dashboard as below.
Now click the user icon at the top right and click the menu Settings. At the Administration section, click Overview.
At the Security and setup warnings section, you will some recommendation that you need to do, depends on your installation environment.
At the Versions section, you will see the current branch of your Nextcloud installation.
You will see details of your environment, system load, disk space status, memory status, network status, etc.
As said before, the nextcloud has become more than just file sync. With the support of additional apps/plugins, it's become a collaboration suit.
At the profile icon top right, click the menu Apps, and you will see nextcloud apps store as below.
Choose the apps you want to install, then click the button Download and enable to install new apps.
Below is the default view of the Nextcloud user dashboard. You can extend the functionality of your dashboard by installing additional plugins.
Nextcloud Performace Tuning
After installed Nextcloud, you can do some steps further to increase the Nextcloud performance by enabling the local memory cache and setting up a cronjob for Nextcloud itself.
At the top PHP installation section, you already set up the PHP for caching. To enable caching on Nextcloud, edit the Nextcloud configuration config.php.
Change the working directory to /var/www/nextcloud/config and edit the configuration config.php using nano editor:
cd /var/www/nextcloud/config/
nano config.php
Add following configuration inside the array ( .. ); bracket as below:
<?php
$CONFIG = array (
....
# Additional configuration
'memcache.local' => '\OC\Memcache\Redis',
);
Now press the Ctrl+x button and type y, then press Enter to save the configuration and exit.
Here you have a real config file from my installation (sensitive data are obscured); see below to configure and secure Redis, or hoew to mount/automount an external volume:
<?php
$CONFIG = array (
'instanceid' => '*******************',
'passwordsalt' => '*******************',
'secret' => '*******************',
'memcache.local' => '\OC\Memcache\Redis',
'redis' =>
array (
'password' => '*******************',
),
'trusted_domains' =>
array (
0 => '192.168.1.*',
1 => 'localhost',
2 => '127.0.0.1',
3 => '***.com',
4 => '****.es',
),
'datadirectory' => '/media/ext/data',
'dbtype' => 'mysql',
'version' => '25.0.1.1',
'overwrite.cli.url' => 'https://192.168.1.*',
'dbname' => '*******************',
'dbhost' => 'localhost',
'dbport' => '',
'dbtableprefix' => '***_',
'mysql.utf8mb4' => true,
'dbuser' => '*******************',
'dbpassword' => '*******************',
'installed' => true,
'forceSSLforSubdomains' => false,
'default_phone_region' => 'ES',
'mail_from_address' => 'info',
'mail_smtpmode' => 'smtp',
'mail_sendmailmode' => 'smtp',
'mail_domain' => '***.org',
'mail_smtpauth' => 1,
'mail_smtphost' => '***.net',
'mail_smtpport' => '25',
'mail_smtpname' => '***@***.es',
'mail_smtppassword' => '*******************',
'maintenance' => false,
);
A Nextcloud system needs to run some background tasks on regular basis and without any user/admin interaction. To do that, you can use the cronjob for task scheduler Nextcloud tasks.
On the Debian Linux system, the default apache installation is running under the user is www-data. Create a new cronjob for user www-data using the command below:
crontabsudo -u www-data php -d memory_limit=512M /var/www/nextcloud/occ maintenance:install \
--database "mysql" \
--database-name "${NC_DB}" \
--database-user "${NC_DB_USER}" \
--database-pass "${NC_DB_PASS}" \
--database-host "localhost" \
--admin-user "admin" \
--admin-pass "CAMBIAR_ESTO" \
--data-dir "${NC_DATA}"
Dominio y URL:
sudo -u www-data php /var/www/nextcloud/occ config:system:set trusted_domains 0 --value="${NC_DOMAIN}"
sudo -u www-data php /var/www/nextcloud/occ config:system:set overwrite.cli.url --value="https://${NC_DOMAIN}"
9) Cron (lo correcto)
sudo -u www-data crontab -e
If you've multiple editors on your system, choose the editor as your comfortable use. For this guide, we will be using a nano editor.
Add the following configuration (you have to call --define apc.enable_cli=1 Because is disabled by default):Añadan:
*/5 * * * * php -f /var/www/nextcloud/cron.php
--define apc.enable_cli=1
Save
the10) configurationRedis anden exit.config.php (sin APCu)
Cronjob configuration you must know:
This cronjob configuration allows user www-data to execute the PHP scriptEditar /var/www/nextcloud/cron.config/config.php everyy 5meter minutes.
esto Todentro verifydel the cronjob configuration, you can execute the following command:array:
crontab'memcache.distributed' => '\OC\Memcache\Redis',
'memcache.locking' => '\OC\Memcache\Redis',
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'CAMBIAR_ESTO',
'timeout' => 1.5,
],
Quitar APCu es una decisión válida si ustedes quieren simplificar. El precio es que pierden el “caché local” rápido. Redis sigue resolviendo lo importante: locking y cache distribuida.
11) Permisos
Código:
sudo chown -R www-data:www-data /var/www/nextcloud
sudo find /var/www/nextcloud/ -type d -exec chmod 750 {} \;
sudo find /var/www/nextcloud/ -type f -exec chmod 640 {} \;
Data dir:
sudo chown -R www-data:www-data "${NC_DATA}"
sudo chmod -R 770 "${NC_DATA}"
12) Checklist post-instalación
sudo -u www-data php /var/www/nextcloud/occ status
sudo -lu www-data php /var/www/nextcloud/occ db:add-missing-indices
sudo -u www-data php /var/www/nextcloud/occ maintenance:repair
If your configuration is a success, you will get the configuration on top as your output. Otherwise, you will get a blank result.
Conclusion
Congratulation! You have successfully installed Nextcloud on Debian 11 Bullseye. The Nextcloud server is running under the LAMP Stack with SSL enabled. There are still some small tweaks to do to improve performance and install and configure Redis for caching (if you haven't already done so).
How to Fix Common NextCloud Performance Issues
The Nextcloud default PHP configuration values are not tailored for applications that require connections to be open for minutes (or hours) to facilitate large file uploads.
Getting NextCloud up and running may seem like a simple process, with all sorts of Bash installation scripts available on the Internet for installing NextCloud on a virtual or dedicated server. But an out of the box installation of NextCloud is not usually ready for production use.
Very basic functionality in NextCloud, such as uploading and downloading large files, can be broken without the administrator even being aware, if it is not tested prior to rolling out NextCloud to your organization’s users.
If your network architecture has a proxy or load balancer in front of the NextCloud app server(s), the web server and PHP timeouts should be checked on the NextCloud servers, in addition to connection timeouts on the load balancer.
Below we have listed some of the most common errors that are reported to NextCloud administrators by their users, and how you can troubleshoot to resolve them. We recommend trying these steps for intermediate to advanced users of Linux, keeping in mind to restart HAProxy, Nginx, or PHP-FPM after making each change.
Can’t upload large files > 512 MB to NextCloud (from browser)
Are you using NextCloud behind any reverse proxies? Reverse proxies may include CloudFlare, cloud managed load balancers, or any load balancer. CloudFlare’s free tier imposes a 100 MB max upload size. Try disabling CloudFlare by grey clouding the DNS entry for your NextCloud instance.
If you must use CloudFlare or a similar reverse proxy, you will only be able to upload large file using the NextCloud desktop client, as the desktop client is configured to split files into chunks for uploading which are then reassembled on the server-side.
Max upload sizes and connection timeouts are hard coded with cloud managed load balancers, so we recommend using a custom load balancer such as HAProxy instead. If using HAProxy, in the defaults or frontend section(s) of the haproxy.cfg file, the values should be set as follows:
timeout connect 30s
timeout client 2h
timeout server 2h
Add or modify these values in the php.ini and/or php-fpm.d/www.conf file (for PHP-FPM installations). The upload_max_size should always be <= post_max_size. You can set the values higher than 4GB if users will upload files larger than that through the web interface.
max_execution_time >= 300
max_input_time >= 300
memory_limit >= 512M
post_max_size >= 4GB
upload_max_filesize >= 4GB
Add or modify these directives in the ssl server block in your Nginx configuration for NextCloud. Setting the client_max_body_size to 0 means that uploads will not be limited by Nginx.
client_max_body_size 0;
fastcgi_buffers 64 4K;
Downloads of files from NextCloud fail at 1GB
Add or modify these directives in the ssl server block in your Nginx configuration for NextCloud. The fastcgi_max_temp_file_size defaults to 1GB that is why downloads of large files fail at exactly 1GB.
proxy_buffering off;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
fastcgi_max_temp_file_size 0;
Can’t login to NextCloud (can’t submit or redirects back to login form)
Make sure /var/lib/php/session is owned by the web server user. The ownership of this directory can sometimes be set to root:apache after upgrading PHP through the package repositories.
CloudFlare’s Rocket Loader can conflict with the Content Security Policy (CSP) that is recommended for NextCloud in the official documentation. Disable Rocket Loader and other security or performance optimizations using a Page Rule.
If you have multiple NextCloud app servers behind a load balancer, set up shared session storage in php.ini with a database or Redis session handler.
Web interface is very slow or encountering 503 Service Unavailable errors
Enable memory caching for NextCloud with APCu, Memcached, or Redis. For a single-node NextCloud deployment, APCu is the simplest memory cache to configure. For a multi-node deployment, Redis should be used for distributed caching, in addition to Transactional File Locking (if not using NFSv3 or v4 with file locking enabled, or object storage) with two separate Redis databases using the 'dbindex' option.
Disable thumbnail generation by adding the following line to config/config.php in your NextCloud app folder:
'enable_previews' => false,
(Look at the above config.php file to calrify)
How To Install and Secure Redis on Debian 11
Introduction
Redis is an in-memory key-value store known for its flexibility, performance, and wide language support. This tutorial demonstrates how to install, configure, and secure Redis on a Debian server.
Step 1 — Installing and Configuring Redis
In order to get the latest version of Redis, we will use apt to install it from the official Debian repositories.
Type this command to switch to root user:
sudo su
Type your password when asked ans hit Enter.
Update your local apt package cache and install Redis by typing:
apt update
apt install redis
This will download and install Redis and its dependencies. Following this, there is one important configuration change to make in the Redis configuration file, which was generated automatically during the installation.
Open this file with your preferred text editor:
nano /etc/redis/redis.conf
Inside the file, find the supervised directive. This directive allows you to declare an init system to manage Redis as a service, providing you with more control over its operation. The supervised directive is set to no by default. Since you are running Debian, which uses the systemd init system, change this to systemd:
# supervised no - no supervision interaction
# supervised upstart - signal upstart by putting Redis into SIGSTOP mode
# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
# supervised auto - detect upstart or systemd method based on
# UPSTART_JOB or NOTIFY_SOCKET environment variables
supervised systemd
That’s the only change you need to make to the Redis configuration file at this point, so save and close it when you are finished. Then, reload the Redis service file to reflect the changes you made to the configuration file:
systemctl restart redis
Step 2 — Testing Redis
Start by checking that the Redis service is running:
sudo systemctl status redis
If it is running without any errors, this command will produce output similar to the following:
● redis-server.service - Advanced key-value store
Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2018-09-05 20:19:44 UTC; 41s ago
...
└─10841 /usr/bin/redis-server 127.0.0.1:6379
To test that Redis is functioning correctly, connect to the server using the command-line client:
redis-cli
In the prompt that follows, test connectivity with the ping command:
PONG
Next, check that you’re able to set keys by running:
set test "It's working!"
Output:
OK
Retrieve the value by typing:
get test
Output:
"It's working!"
Exit the Redis prompt to get back to the shell:
exit
As a final test, restart the Redis instance:
sudo systemctl restart redis
Then connect with the command-line client once again and confirm that your test value is still available:
redis-cli
get test
Output:
"It's working!"
Exit:
exit
Step 3 — Binding to localhost
By default, Redis is only accessible from localhost. To ensure this, open the Redis configuration file:
nano /etc/redis/redis.conf
Locate this line and make sure it is uncommented:
bind 127.0.0.1
Restart the service:
systemctl restart redis
To check that this change has gone into effect, run:
netstat -lnp | grep redis
Output:
tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN 10959/redis-server
Step 4 — Configuring a Redis Password
Open the configuration file:
nano /etc/redis/redis.conf
Scroll to the SECURITY section and look for:
# requirepass foobared
Uncomment it and change foobared to a secure password.
Generate a random password:
openssl rand 60 | openssl base64 -A
Example output:
RBOJ9cCNoGCKhlEBwQLHri1g+atWgn4Xn4HwNUbtzoVxAYxkiYBi7aufl4MILv1nxBqR4L6NNzI0X6cE
Set it:
requirepass RBOJ9cCNoGCKhlEBwQLHri1g+atWgn4Xn4HwNUbtzoVxAYxkiYBi7aufl4MILv1nxBqR4L6NNzI0X6cE
Restart Redis:
systemctl restart redis.service
Test it:
redis-cli
set key1 10
(error) NOAUTH Authentication required.
auth your_redis_password
OK
set key1 10
OK
get key1
"10"
quit
Step 5 — Renaming Dangerous Commands
Open the configuration file once more:
nano /etc/redis/redis.conf
To disable a command, rename it to an empty string:
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command DEBUG ""
To rename a command:
rename-command SHUTDOWN SHUTDOWN_MENOT
rename-command CONFIG ASC12_CONFIG
Restart Redis:
systemctl restart redis
Test:
redis-cli
auth your_redis_password
OK
config get requirepass
(error) ERR unknown command 'config'
asc12_config get requirepass
1) "requirepass"
2) "your_redis_password"
exit
Note: If you’re already using the Redis command line and then restart Redis, you’ll need to re-authenticate. Otherwise, you’ll get this error if you type a command:
NOAUTH Authentication required.
Regarding the practice of renaming commands, there’s a cautionary statement at the end of the SECURITY section in /etc/redis/redis.conf which reads:
Please note that changing the name of commands that are logged into the AOF file or transmitted to slaves may cause problems.
Thus, the best way to handle renaming in cases like that is to make sure that renamed commands are applied to all instances in master-slave installations.