Once the server has been built it's time to prepare and install Nextcloud itself. As I want to import and activate selected applications when I'm ready I'm using the .zip download from Nextcloud Installs for a VM I've built myself rather than one of the packaged options.

This follows on from the Test Nextcloud 26 Server Build article where I build the test server in my public subnet. At this stage the server is configured and available internally but there is no public access.

Contents:

Prepare Server

The first step is to prepare the server we've built by configuring as a LAMP stack (Linux Apache MariaDB PHP). As a reminder the server used here is a virtual machine running Ubuntu 20.04 LTS patched through to April 2023.

Configure Linux

Although the server has been built already we need to correct the way the /srv/nextcloud filesystem was created and mounted by the Ubuntu installer to use btrfs subvolumes so I can enable snapshot backups. I'll also need unzip to extract the downloaded Nextcloud archive later on.

Create btrfs subvolumes

The Ubuntu 20.04 LTS installer created the btrfs filesystem for us and mounted it at /srv/nextcloud, but to enable it for use with snapshots we need to create a root subvolume and the two child subvolume that will hold the Nextcloud site and data that we'll be enabling for snaphots. This also means we'll need to adjust /etc/fstab to mount the filesystem at the root subvolume too.

Following the Ubuntu conventions the root subvolume will be called @nextcloud and within that we'll create subvolumes www and data and a backup directory were we'll mount the snapshots during the backup process.

Nextcloud directory structure

This can all be done from the command line as root.

root@host:/# cd /srv/nextcloud
root@host:/srv/nextcloud# btrfs subvol create @nextcloud
Create subvolume './@nextcloud'

root@host:/srv/nextcloud# cd @nextcloud
root@host:/srv/nextcloud/@nextcloud# mkdir -p backup/db

root@host:/srv/nextcloud/@nextcloud# btrfs subvol create www
Create subvolume './www'

root@host:/srv/nextcloud/@nextcloud# btrfs subvol create data
Create subvolume './data'

root@host:/srv/nextcloud# btrfs subvol list .
ID 257 gen 11 top level 5 path @nextcloud
ID 258 gen 10 top level 257 path www
ID 259 gen 11 top level 257 path data

The next step is to edit the /etc/fstab file so that it mounts /srv/nextcloud using the @nextcloud subvolume.

# /srv/nextcloud was on /dev/sdd during curtin installation
/dev/disk/by-uuid/f00d1234-ab12-cd34-ef56-ab12cd34ef56 /srv/nextcloud btrfs defaults,subvol=@nextcloud 0 0

And then finally remount the volume properly

cd /srv/
umount nextcloud
mount -a

This should now appear as a normal directory tree. We can now exit from root as well.

Install unzip

Unzip is not installed by default, but we can add this from the standard Ubuntu repository.

sudo apt install unzip

Apache 2.4

The default version of Apache2 from the Ubuntu 20.04 LTS repositories is sufficient.

sudo apt install apache2

This will also install whole bunch of dependencies. When complete we should be able to access the server on the OS hostname and get the default Apache2 homepage.

One the initial install is completed we also need to enable some additional modules for Nextcloud.

sudo a2enmod rewrite
sudo a2enmod headers

The env, dir and mime modules are active by default so we shouldn't need to touch them. We will configure an Apache2 site for Nextcloud as part of the Nextcloud installation later.

MariaDB 10.6

We need to use a more up to date version of MariaDB than is supplied by Ubuntu 20.04 LTS so we need to enable the repository from mariadb.org first. The installation process is based on their information.

Install

The first step is to get their repository signing key so we can verify the files in the repository.

user@host:~$ sudo apt-key adv --fetch-keys 'https://mariadb.org/mariadb_release_signing_key.asc'
[sudo] password for localadmin: 
Executing: /tmp/apt-key-gpghome.DZdeH5kdaF/gpg.1.sh --fetch-keys https://mariadb.org/mariadb_release_signing_key.asc
gpg: requesting key from 'https://mariadb.org/mariadb_release_signing_key.asc'
gpg: key F1656F24C74CD1D8: public key "MariaDB Signing Key <This email address is being protected from spambots. You need JavaScript enabled to view it.>" imported
gpg: Total number processed: 1
gpg:               imported: 1

The next step is to add the repository details to apt. There are a number of mirrors scattered around the world so pick whichever is nearest to you. They have a handy apt configuration generator on the download page too.

In the /etc/apt/sources.list.d directory create a file called mariadb.list and set permissions to 644. You'll need to be root to create (and edit) the file. Paste the following, or the config from the MariaDB download page into the file and save.

# MariaDB 10.6 repository list - created 2023-04-10 19:57 UTC
# https://mariadb.org/download/
deb https://mirrors.xtom.nl/mariadb/repo/10.6/ubuntu focal main
# deb-src https://mirrors.xtom.nl/mariadb/repo/10.6/ubuntu focal main

Once that is completed update the repository config

sudo apt update

And then install the MariaDB server and client

sudo apt install mariadb-server mariadb-client

This will of course select some additional packages to be installed. Once that's completed start the database server

sudo systemctl start mariadb

Prepare

It is highly recommended to run the hardening tool, mysql_secure_installation, even on test systems. This only needs to be done once, and we need to to do this as the Linux root user so we can login as the MariaDB root user. The default are sufficient for us so it makes running the tool easy.

root@host:~# mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] n
 ... skipping.

You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] n
 ... skipping.

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

 

Create backup user

The final step to prepare MariaDB for use is to create a user for the backup process. I am using Bacula 9 for running backups, and the process will be to trigger a database dump to /srv/nextcloud/backup/db and then let Bacula copy the dump file.

As the Linux root user login to mysql and run the following 3 commands, but substitute the username and password of your choice for backup-user and backup-password. Make a secure note of whatever backup user and password you choose.

root@host:~# mysql
CREATE USER 'backup-user'@'localhost' IDENTIFIED BY 'backup-password';
GRANT SELECT, SHOW VIEW, LOCK TABLES, RELOAD, REPLICATION CLIENT ON *.* TO 'backup-user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Still as the root user create a mariadb.cnf file in /etc/bacula/scripts and set the permissions to 640 root:root so only the Bacula client (which runs as root) can read it. Copy the following into the mariadb.cnf file, again substituting whatever you chose above for the backup-user and backup-password

# Options file for MariaDB

[mariadb-dump]
host = localhost
user = backup-user
password = backup-password

Save the file. We will configure the backup scripts that will use this configuration once the Nextcloud application is deployed and we've got something to test the backups with.

PHP 8.1

The PHP versions in the Ubuntu 20.04 LTS repositories are now out of support and applications such as Nextcloud and Joomla are starting to complain. The minimum version for Nextcloud is now PHP 8.0. There are multiple references across the interwebs to using a PPA from Ondrej Sury as an installation source. I'm usually a bit skeptical about using PPA's for server applications, but Ondrej is credited as a long-time packager of PHP for Debian, among other things so we'll use this.

There's two ways to add his repository,

Option 1: Add PHP repository manually

The first step is to import his key from the Ubuntu keyserver.

user@host:~$ sudo gpg --no-default-keyring --keyring /usr/share/keyrings/ondrej.gpg --keyserver keyserver.ubuntu.com --recv-keys 14AA40EC0831756756D7F66C4F4EA0AAE5267A6C
gpg: WARNING: unsafe permissions on homedir '/root/.gnupg'
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key 4F4EA0AAE5267A6C: public key "Launchpad PPA for Ondřej Surý" imported
gpg: Total number processed: 1
gpg:               imported: 1

Then we need to enable the PPA as the source for PHP by creating an ondrej-php.list file with 644 permissions in /etc/apt/sources.list.d - which you'll need root access to create. This can be done by an echo command but I find it easier to use an editor and copy/paste.

# PPA for PHP installation
deb [signed-by=/usr/share/keyrings/ondrej.gpg] https://ppa.launchpadcontent.net/ondrej/php/ubuntu focal main

Once the file is saved update the repository lists again.

sudo apt update

Option 2: Add PHP repository easily

A much easier approach is to install the PPA directly

sudo add-apt-repository ppa:ondrej/php

Having tried both, I now much prefer the second method.

PHP is supplied as either an Apache2 module or the FastCGI Process manager. We're going to use the second one, which runs as a service outside of Apache, as it's faster and uses less memory.

user@host:~$ sudo apt install php8.1-fpm libapache2-mod-fcgid
Reading package lists... Done
… NOTICE: Not enabling PHP 8.1 FPM by default. NOTICE: To enable PHP 8.1 FPM in Apache2 do: NOTICE: a2enmod proxy_fcgi setenvif NOTICE: a2enconf php8.1-fpm NOTICE: You are seeing this message because you have apache2 package installed.

This will add another five depended packages too, and it detects that we already have Apache2 so we need to enable the two modules and and configuration listed

sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.1-fpm

That completes the basic PHP 8.1 installation. Nextcloud has some additional PHP packages it needs so we might as well install them at this point too, otherwise we'll get errors on the initial installation page and warnings on the support page.

sudo apt install php8.1-mysql php8.1-zip php8.1-xml php8.1-mbstring php8.1-gd php8.1-curl php8.1-imagick php8.1-intl php8.1-bz2 php8.1-apcu

Finally we need to start the PHP-FPM service and reload Apache2

sudo systemctl start php8.1-fpm
sudo systemctl reload apache2

 

Nextcloud 26

Now that we have all the pre-requisites completed we can install Nextcloud itself. Just before I started this test Nextcloud 26.0.0 was released. Since this is a test installation I figured I might as well go with the latest and greatest which has some implications of course but the trade-off is it'll mean it'll be supported for longer. And I suppose it's only fair that I take a turn at being an early user of a version.

Download

As mentioned at the start the installation .zip file can be downloaded from Nextcloud Installs and  if you've been clever and read this through before starting hopefully you've already got it. If not take a few minutes to get the file now. Keep it safe as we'll use the same installer for the Live system later. Also download the MD5 checksum file for the .zip as well.

If you download the lastest version directly, the file will be called latest.zip and the checksum will be called latest.zip.md5 which isn't exactly helpful if you want to use the file again later. If you follow their "older versions or major releases" link you'll be able to select exactly which version to chose, and it's helpfully named too nextcloud-26.0.0.zip. (Or possibly later depending on when you do this.)

Create Database

Nextcloud needs a database, a user for the database and a password for the user. As the Linux root user connect to MariaDB and execute the following three commands substituting your choices for nextclouddb, nextcloud and nextcloud-password. Make a secure note of all three as they'll be also be needed during the initial configuration, and potentially if you ever have to restore or reinstall.

root@host:/srv/nextcloud# mysql

root@host:/srv/nextcloud# mysql
CREATE DATABASE nextclouddb; GRANT ALL PRIVILEGES ON nextclouddb.* TO 'nextcloud'@'localhost' IDENTIFIED BY 'nextcloud-password'; FLUSH PRIVILEGES; EXIT;

This will have created directory called /var/lib/mysql/nextclouddb which should contain a small db.op file. The database content will be created during Nextcloud initial configuration.

Install

Upload the installation zip and associated md5 checksum file to the server and place in the /srv/nextcloud/www directory. The first task is to check the file zip file against the checksum. As the /srv/nextcloud/www is still owned by root at this point, you'll need to be the root user too. We will fix that shortly.

root@host:/srv/nextcloud/www# md5sum -c nextcloud-26.0.0.zip.md5
nextcloud-26.0.0.zip: OK

Hopefully it won't give any errors or warnings.

Extract

The next task is to extract the files using the unzip command. This will extract all the files to a nextcloud directory so we'll need to move everything up a level after unzipping.

cd /srv/nextcloud/www
unzip nextcloud-26.0.0.zip

cd nextcloud
mv * ..
mv .* ..
cd ..
rmdir nextcloud

The mv .* .. command will complain it cannot move the . and .. files, which is perfectly normal. You should now be able to see the the Nextcloud files and directories such as apps, cron.php and lib in the /srv/nextcloud/www directory.

All the application files will be owned by root, which isn't much use for a website so we need to change the ownership to the Apache2 user.

cd /srv/nextcloud
chown -R www-data:www-data *

We also want to update the permission on /srv/nextcloud to Apache2 can access it.

chmod 755 /srv/nextcloud

As an alternative you could change the group to www-data if you prefer.

Define Apache2 site

For this installation I am also going to terminate TLS on a proxy and at least for now use plain HTTP between the proxy and Nextcloud. The proxy is also going to "own" the actual URL that users will access so I don't have worry about that either.

To define the site we create a file such as nextcloud.conf in the /etc/apache2/sites-available directory which needs root access. The file should have 644 permissions. In the example below replace internal.example.com with the server hostname.

<VirtualHost *:80>
  DocumentRoot /srv/nextcloud/www/
  ServerName  internal.example.com

  <Directory /srv/nextcloud/www/>
    Require all granted
    AllowOverride All
    Options FollowSymLinks MultiViews

    <IfModule mod_dav.c>
      Dav off
    </IfModule>
  </Directory>
</VirtualHost>

We need to enable the site once it's defined and also disable the default site, and then restart Apache2 to make it take effect.

a2ensite nextcloud.conf
a2dissite 000-default.conf
systemctl restart apache2

Connection Test

In theory we now have everthing ready so it's a good time to do a connection test to make sure all is at it should be. If you open a browser to the hostname of the server, making sure to specify an HTTP connection to whatever you called teh server e.g. http://internal.example.com you should be greeted with the initial configuration page.

Inital configuration page

Just close the browser and don't do anything yet though.

Backup Config

There's a few hours work to get to this point so the next task is to take an initial backup. We've got two options here, and we might as well take both.

Since this is built on a VMware ESXi Virtual Machine, a quick win is to simply shut the VM down and take a snaphot from the VMware console. Once that's completed and the VM is back online again do another connection check to make sure Apache2 and everything else has started up properly.

Bacula Client Config

This is also a good point to get the real backups running too using the Bacula client that was installed by my standard playbooks during Test Nextcloud 26 Server Build. We need to add two scripts to the /etc/bacula/scripts directory so the client can trigger the database dumps and filesystem snapshots.

This first script puts Nextcloud into maintenance mode to temporarily stop writes and then triggers a database dump to /srv/nextcloud/db using the database backup specified in the mariadb-dump.cnf file. It then creates read-only snapshots of the /srv/nextcloud/www and /srv/nextcloud/data subvolumes and mounts them under /srv/nextcloud/backup.

Nextcloud is then taken out of maintenance mode so users can carry on as normal. The snapshots are created almost instantly so the limiting factor is the database dump which should only take a few seconds. Bacula then proceeds to backup the /srv/nextcloud/backup directory containing our dump and snapshots.

Copy the script below to /etc/bacula/scripts/nextcloud-backup.sh and set permissions 654 root:root on it.

# Prepare NextCloud for backup:
# Version 1 - 10 Sept 2022

# Needs to be run as root to change users and take snapshots

# Constants for the functions
NCuser="www-data"
NCocc="/srv/nextcloud/www/occ"

MDBoptions="/etc/bacula/scripts/mariadb-dump.cnf"
MDBname="nextclouddb"
MDBdestination="/srv/nextcloud/backup/db/$MDBname-`date +"%Y%m%d-%H%M"`.bak"


function btrfs-snapshot {
# Clear existing snapshot then create new

  if [[ -d $2 ]]; then
    echo "Clearing old snapshot $2"
    btrfs subvolume delete $2
  fi

  echo "Create snapshot of filesystem"
  btrfs subvolume snapshot -r $1 $2
}


# MAIN body of script

# Enable maintenance mode to freeze writes during backup
sudo -u $NCuser php $NCocc maintenance:mode --on

echo "Dumping database to $MDBdestination"
mariadb-dump --defaults-extra-file=$MDBoptions --single-transaction $MDBname > $MDBdestination

# Create read-only snapshots of www and data
btrfs-snapshot /srv/nextcloud/www  /srv/nextcloud/backup/snapshot-www
btrfs-snapshot /srv/nextcloud/data /srv/nextcloud/backup/snapshot-data

# Disable maintenace mode
sudo -u $NCuser php $NCocc maintenance:mode --off

# And now Bacula does its thing...

This second script is called after the Bacula job is complete and simply drops the read-only snapshots we created and deletes the database dump. Copy the script below to /etc/bacula/scripts/nextcloud-backup-done.sh and set permissions 654 root:root on it.

#!/bin/bash
# Cleanup after NextCloud backup
# Version 1 - 10 Sept 2022

# Needs to be run as root to clear snapshots
# Ensure snapshot and backup destination match nextcloud-backup.sh

MDBdumps="/srv/nextcloud/backup/db"

function btrfs-drop-snapshot {
# Clear existing snapshot

  if [[ -d $1 ]]; then
    echo "Clearing old snapshot $1"
    btrfs subvolume delete $1
  fi
 
}

# Drop the snapshots
btrfs-drop-snapshot  /srv/nextcloud/backup/snapshot-www
btrfs-drop-snapshot  /srv/nextcloud/backup/snapshot-data

# Drop the database dump
  echo "Deleting $MDBdumps/*.bak"
  rm -f $MDBdumps/*.bak

# Complete

Both scripts can be called directly as the root user to test then and make sure they're working before you configure the Bacula job to call them.

Bacula Server Config

My server config playbooks also drop a Bacula client configuration file into my Bacula Server (articles to cover this are in my backlog and will appear at some point). So I just need to add a job definition that call these two scripts

Job {
Name = "Prj_chip-testnc-Data"
Client = Prj_chip-testnc
  JobDefs = ServerData
  FileSet = Nextcloud-Data
  # Overrides here
  # Enabled = No
  Priority = 45
  Pool = Project

  RunScript {
    RunsWhen = Before
    FailJobOnError = Yes
    RunsOnClient = Yes
  Command = "/etc/bacula/scripts/nextcloud-backup.sh"
  }

  RunScript {
    RunsWhen = After
    Runs On Success = Yes
    Runs On Failure = Yes
    Runs On Client = Yes
  Command = "/etc/bacula/scripts/nextcloud-backup-done.sh"
  }
}

The FileSet=Nextcloud-Data refers to the specification of how the /srv/nextcloud/backup directory is backed up, which is held as a separate config file within my Bacula server.

# Application: Nextcloud 
#
# 11 Sept 2022
#

FileSet {
  Name= "Nextcloud-Data"               
  Ignore FileSet Changes = yes
  Include {
    Options {
      signature = MD5
      compression = GZIP
      Exclude = yes
      noatime = yes
      Wilddir = "/*/lost+found"
      sparse = yes
    }

    # Backup locations created by scripts, these are not live directories.
    File = /srv/nextcloud/backup/db
    File = /srv/nextcloud/backup/snapshot-www
    File = /srv/nextcloud/backup/snapshot-data
  }

I have other Nextcloud servers already in use so keeping to a standard architecture means I don't have to customise everything from scratch each time. I will write up my Bacula config at some point, and I might even put the scripts into a public repository somewhere too.

Next

The next steps are to complete the initial configuration of Nextcloud, and then to document the process for making it play nicely with HAproxy so it's accessible on the internet for the users to start playing with. Assuming they can be bothered 'cos it's been up and running for a few days now and they've not even looked.