Nextcloud: Difference between revisions

From Newroco Tech Docs
Jump to navigationJump to search
No edit summary
 
(21 intermediate revisions by 2 users not shown)
Line 15: Line 15:


'''Note''': Package ''php-mcrypt'' has been removed since php7.2 which comes on ubuntu 18.04, so just skip that one.
'''Note''': Package ''php-mcrypt'' has been removed since php7.2 which comes on ubuntu 18.04, so just skip that one.
<pre>
<pre>apt-get install -y apache2 postfix postgresql postgresql-contrib libapache2-mod-php php php-gd php-json php-pgsql php-curl php-intl php-imagick php-zip php-xml php-mbstring php-ldap php-bcmath php-gmp libmagickcore-6.q16-6-extra</pre>
apt-get install -y apache2 postfix postgresql postgresql-contrib libapache2-mod-php
'''NOTE''': last package may be other version depending on the Ubuntu version. Check repo with '''apt-cache search libmagickcore | grep libmagickcore'''
apt-get install -y php-gd php-json php-pgsql php-curl
 
apt-get install -y php-intl php-mcrypt php-imagick
apt-get install -y php-zip php-xml php-mbstring php-ldap</pre>
14.04
14.04
<pre>
<pre>apt-get install apache2 postgresql postgresql-contrib libapache2-mod-php5
apt-get install apache2 postgresql postgresql-contrib libapache2-mod-php5
apt-get install php5-gd php5-json php5-pgsql php5-curl
apt-get install php5-gd php5-json php5-pgsql php5-curl
apt-get install php5-intl php5-mcrypt php5-imagick php5-ldap</pre>
apt-get install php5-intl php5-mcrypt php5-imagick php5-ldap</pre>
Line 33: Line 30:
a2enmod mime
a2enmod mime
a2enmod ssl
a2enmod ssl
a2ensite default-ssl
a2ensite default-ssl</pre>
</pre>


==== Prepare PHP to use PostgreSQL ====
==== Prepare PHP to use PostgreSQL ====
Line 62: Line 58:
# psql -d template1
# psql -d template1


CREATE USER yourdbuser CREATEDB;
CREATE USER yourdbuser WITH PASSWORD 'yourdbuser_password';
CREATE DATABASE nextcloud OWNER yourdbuser;
CREATE DATABASE nextcloud OWNER yourdbuser;
\q
\q
Line 76: Line 72:
<pre>
<pre>
# "local" is for Unix domain socket connections only
# "local" is for Unix domain socket connections only
local  all     ncdbuser                                trust
local  all             ncdbuser                                trust
local  all            all                                    peer
local  all            all                                    peer
</pre>
</pre>
Line 82: Line 78:
Then restart postgresql
Then restart postgresql


<pre>service postgresql restart</pre>
<pre>systemctl restart postgresql</pre>


Now move on to [[#Configure_the_web_core]]
Now move on to [[#Configure_the_web_core]]
Line 121: Line 117:
<pre>listen_addresses = 'localhost,master.ip.add.ress'</pre>
<pre>listen_addresses = 'localhost,master.ip.add.ress'</pre>
uncomment and set
uncomment and set
<pre>wal_level = hot_standby</pre>
<pre>wal_level = replica</pre>
and
and
<pre>archive_mode = on
<pre>archive_mode = on
Line 188: Line 184:


<pre>su postgres
<pre>su postgres
psql -d template1
psql


CREATE USER yourdbuser CREATEDB;
CREATE USER yourdbuser WITH PASSWORD 'your_password';
CREATE DATABASE nextcloud OWNER yourdbuser;
CREATE DATABASE nextcloud OWNER yourdbuser;
\q
\q
Line 213: Line 209:
16.04 onwards (will need universe [[repository adding]] for some options)
16.04 onwards (will need universe [[repository adding]] for some options)
<pre>
<pre>
apt-get install postfix apache2 libapache2-mod-php
apt-get install -y apache2 postfix libapache2-mod-php php php-gd php-json php-pgsql php-curl php-intl php-imagick php-zip php-xml php-mbstring php-ldap php-bcmath php-gmp</pre>
apt-get install php-gd php-json php-pgsql php-curl
apt-get install php-intl php-mcrypt php-imagick
apt-get install php-zip php-xml php-mbstring php-ldap</pre>
14.04
14.04
<pre>
<pre>
Line 351: Line 344:
And restart apache
And restart apache
  apache2ctl restart
  apache2ctl restart
Also, on the reverse proxy vhost add this header
<pre>Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"</pre>
====Redirect source IP to VMs====
If nextclod is running behind a reverse proxy server in order to redirerct the source IP to the VM on the VM's enable these 2 modules:
<pre>a2enmod remoteip && a2enmod headers
systemctl restart apache2</pre>
Add this to the apache vhost
<pre>RemoteIPHeader X-Forwarded-For</pre>
Comment this line in '''/etc/apache2/apache2.conf'''
<pre>LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined</pre>
and add this one under
<pre>LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined</pre>
Add this to '''/var/www/nextcloud/config/config.php'''
<pre>  'forwarded_for_headers' =>
  array (
    0 => 'HTTP_X_FORWARDED_FOR',
  ),</pre>
Reload apache2 config
<pre>apache2ctl graceful</pre>


===Completing NextCloud installation===
===Completing NextCloud installation===
Line 376: Line 395:


and add
and add
  */15 *  *  *  * php -f /var/www/nextcloud/cron.php
  */5 *  *  *  * php -f /var/www/nextcloud/cron.php
 
=== Setting the log rotate ===
Nextcloud logs are not rotated by default and this would lead to very big log files in the future. To rotate logs when the file reaches 10MB add this to /var/www/nextcloud/config/config.php
<pre>'log_rotate_size' => 10485760,</pre>


===Upgrade process (updater app)===
===Upgrade process (updater app)===
Line 445: Line 468:
And restart apache2
And restart apache2


<pre>apache2ctl graceful</pre>
'''NOTE''': If Nextcloud reports that background jobs are not running or the occ command can't be ran and throws this error:
<pre>An unhandled exception has been thrown:
OC\HintException: [0]: Memcache \OC\Memcache\APCu not available for local cache (Is the matching PHP module installed and enabled?)</pre>
Then you need to add this line to '''/etc/php/7.4/mods-available/apcu.ini'''
<pre>apc.enable_cli=1</pre>
And reload apache
<pre>apache2ctl graceful</pre>
<pre>apache2ctl graceful</pre>


Line 451: Line 485:
<pre>  'session_lifetime' => 60 * 60 * 8,
<pre>  'session_lifetime' => 60 * 60 * 8,
   'session_keepalive' => false,</pre>
   'session_keepalive' => false,</pre>
===Nextcloud as OAuth2 provider===
When Nextcloud is configured as an OAuth2 provider, Nextcloud and the client service will need to have some direct communication, but unfortunately that communication will be tagged by NC's bruteforce mechanism as spam/harmful and will start to throttle the client service. To fix this go to the admin panel on NC, under Administration -> Security -> Brute-force IP whitelist and whitelist the IP of the client service. Because there might be firewalls and other devices between, you can check the exact IP that needs to be whitelisted in the '''oc_bruteforce_attempts''' DB table.

Latest revision as of 07:09, 21 July 2021

Administration and use

See individual pages

Install of NextCloud supporting notes

All commands assume sudo or that you are logged in as root. These notes are for installation with PostgreSQL on Ubuntu 14.04, other DBMS and Linux/Unix variants may not have similar outcomes. The installations here assume use with an organisation and therefore include add-ons that may not be useful in personal installation.

Small office install, single server

Install the dependencies

16.04 onwards (will need universe repository adding for some options)

Note: Package php-mcrypt has been removed since php7.2 which comes on ubuntu 18.04, so just skip that one.

apt-get install -y apache2 postfix postgresql postgresql-contrib libapache2-mod-php php php-gd php-json php-pgsql php-curl php-intl php-imagick php-zip php-xml php-mbstring php-ldap php-bcmath php-gmp libmagickcore-6.q16-6-extra

NOTE: last package may be other version depending on the Ubuntu version. Check repo with apt-cache search libmagickcore | grep libmagickcore

14.04

apt-get install apache2 postgresql postgresql-contrib libapache2-mod-php5
apt-get install php5-gd php5-json php5-pgsql php5-curl
apt-get install php5-intl php5-mcrypt php5-imagick php5-ldap

Enable the Apache modules

a2enmod rewrite
a2enmod headers
a2enmod env
a2enmod dir
a2enmod mime
a2enmod ssl
a2ensite default-ssl

Prepare PHP to use PostgreSQL

Edit the PHP PostgreSQL configuration

vi /etc/php/7.0/apache2/conf.d/20-pgsql.ini

or

vi /etc/php5/apache2/conf.d/20-pgsql.ini

and append

[PostgresSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0

Create the base DB & allow web app access

Set up the database and user,

# su postgres
# psql -d template1

CREATE USER yourdbuser WITH PASSWORD 'yourdbuser_password';
CREATE DATABASE nextcloud OWNER yourdbuser;
\q

# exit

Edit PostgreSQL settings to allow local connections for yourdbuser to the nextcloud database (on all DB servers):

# vi /etc/postgresql/<version number>/main/pg_hba.conf

Adding a line before the default "local" permission line e.g.

# "local" is for Unix domain socket connections only
local   all             ncdbuser                                trust
local   all             all                                     peer

Then restart postgresql

systemctl restart postgresql

Now move on to #Configure_the_web_core

Larger installation, loads split out

How far this goes will depend on your needs. A small to medium organisation would want as a minimum to separate the apps (web) server from the DB server from the file storage, and if deploying in a virtual environment look to separate those loads at a physical level. It is worth considering duplicating the app and DB components for increased uptime, although if the file usage pattern is mostly download/update/upload the additional complexity may not be worth the effort.

build your DB server(s)

apt-get install postgresql postgresql-contrib postgresql-client rsync

Enable master/slave replication

consider splitting this out to a postgre page

Switch to the postgres user and create a key pair for it

su postgres
ssh-keygen

Accept defaults and don't use a passphrase.

On the designated master server, create a replication user

psql -c "CREATE USER rep REPLICATION LOGIN CONNECTION LIMIT -1 ENCRYPTED PASSWORD 'yourpasswordhere';"

Then enable the user to have the appropriate PostgreSQL security rights:

vi /etc/postgresql/9.5/main/pg_hba.conf

and add the line

host    replication     rep     slave.ip.add.ress/32   md5

Then configure for replication

vi /etc/postgresql/9.5/main/postgresql.conf

uncomment and add the master server's IP in

listen_addresses = 'localhost,master.ip.add.ress'

uncomment and set

wal_level = replica

and

archive_mode = on
archive_command = 'cd .'

and

max_wal_senders = 10

Finally as root or with sudo, restart postgresql

service postgresql restart

On the designated slave, make the same configuration changes, substituting the master's IP address in pg_hba.conf and the slave's in postgresql.conf, then in postgresql.conf make the additional change of uncommenting and setting

hot_standby = on

following section may be deprecated after none-rsync initial DB propagation adopted


Then you'll need an exception for the user postgres on these servers i.e. using visudo add

postgres ALL=NOPASSWD: /usr/bin/rsync

and copy the master's public key

cat /var/lib/postgresql/.ssh/id_rsa.pub

to the slave

mkdir /var/lib/postgresql/.ssh
vi /var/lib/postgresql/.ssh/authorized_keys
chown -R postgres:postgres /var/lib/postgresql/.ssh
chmod 600 /var/lib/postgresql/.ssh/authorized_keys

Then as root

service postgresql start

Prep for initial replication. On the slave (noting version number in path may change on later installs)

su postgres
rm -r /var/lib/postgresql/9.5/main/*
pg_basebackup -U rep -D /var/lib/postgresql/9.5/main/ -X stream --write-recovery-conf -h master.ip.add.ress

Check the DBMS is up by connecting to it

su postgres
psql

If you get an error running psql return to root and run

service postgresql restart

Then try connecting again.

Assuming no errors, leave the slave connected to the DBMS, switch to the master server (in another console) and as root do

su postgres
psql
CREATE TABLE rep_test (test varchar(40));
INSERT INTO rep_test VALUES ('fubar or not fubar');

Switch back to the slave server and check this has replicated

SELECT * FROM rep_test;

You should get a response like

 test        
--------------------
 fubar or not fubar
(1 row)

If not, check you have carried out all the steps in these instructions and check logs for clues.

Create the base DB & allow web app access

Set up the database and user,

su postgres
psql

CREATE USER yourdbuser WITH PASSWORD 'your_password';
CREATE DATABASE nextcloud OWNER yourdbuser;
\q

exit

Edit PostgreSQL settings to allow local connections for yourdbuser to the nextcloud database:

vi /etc/postgresql/<version number>/main/pg_hba.conf

Adding a host line for each web/app server

host    all       yourdbuser        webapp.ip.add.ress/32          md5

Then restart postgresql

service postgresql restart

Build web/app server

16.04 onwards (will need universe repository adding for some options)

apt-get install -y apache2 postfix libapache2-mod-php php php-gd php-json php-pgsql php-curl php-intl php-imagick php-zip php-xml php-mbstring php-ldap php-bcmath php-gmp

14.04

apt-get install apache2 libapache2-mod-php5
apt-get install php5-gd php5-json php5-pgsql php5-curl
apt-get install php5-intl php5-mcrypt php5-imagick php5-ldap

Enable the Apache modules

a2enmod rewrite
a2enmod headers
a2enmod env
a2enmod dir
a2enmod mime
a2enmod ssl
a2ensite default-ssl

Prepare PHP to use PostgreSQL

Edit the PHP PostgreSQL configuration on all app/web servers

vi /etc/php(version)/apache2/conf.d/20-pgsql.ini

and append

[PostgresSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0

Configure the web core

Get the latest Nextcloud package by visiting https://nextcloud.com/install/, copying the download link and then

wget https://download.nextcloud.com/server/releases/nextcloud-9.0.53.zip

(being sure to use the link you just copied)

Also retrieve the relevant checksum (again changing the line to match the version you've downloaded)

wget https://download.nextcloud.com/server/releases/nextcloud-9.0.53.zip.md5

Verify the download:

md5sum -c nextcloud-9.0.53.zip.md5 < nextcloud-9.0.53.zip

Assuming the download is verified successfully, unzip the archive

# unzip nextcloud-9.0.53.zip

and then copy the resulting directory to the Apache root dir

# mv nextcloud /var/www/

Create & enable the vhost. Unless you are #using a SSL-enabled reverse proxy to front your Nextcloud server, you should also ensure the service is https only, and for neatness redirect any http to https.

# vi /etc/apache2/sites-available/nextcloud.conf

<VirtualHost *:443>
## nextcloud vhost settings
ServerName your.fq.dn

DocumentRoot /var/www/nextcloud

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

#                SSLEngine on

#                SSLCertificateFile      /etc/letsencrypt/<to be enabled via [[Certbot]]
#                SSLCertificateKeyFile /etc/letsencrypt/<to be enabled via [[Certbot]]


<Directory /var/www/nextcloud/>
  Options +FollowSymlinks
  AllowOverride All

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

 SetEnv HOME /var/www/nextcloud
 SetEnv HTTP_HOME /var/www/nextcloud

</Directory>
</VirtualHost>
# cd /etc/apache2/sites-enabled
# ln -s ../etc/apache2/sites-available/nextcloud.conf

Change the default site non-SSL to be simply a redirect

# vi /etc/apache2/sites-available/000-default.conf

<VirtualHost>
        ServerName your.fq.dn
        Redirect permanent / https://your.fq.dn/
</VirtualHost>

and restart Apache

service apache2 restart

Enable SSL

Use Certbot to enable a trusted SSL certificate. If the NextCloud you're building is not available on a publicly registered domain name, you could just generate your own self-signed certificate.

When the certificate has been acquired or generated, edit your vhost file to suit and restart Apache

# vi /etc/apache2/sites-available/nextcloud.conf

Uncomment and amend

                SSLEngine on

                SSLCertificateFile      /etc/letsencrypt/live/your.fq.dn/cert.pem
                SSLCertificateKeyFile /etc/letsencrypt/live/your.fq.dn/privkey.pem

# apache2ctl restart

using a SSL-enabled reverse proxy

If running behind a reverse proxy, you should also ensure that (a) the proxy is passing the X-Forwarded-For header and (b) your Nextcloud web server is configured to "see" that header and also log the client IP. Add the appropriate module:

# a2enmod remoteip

Modify apache.conf

# vi /etc/apache2/apache2.conf

And add %a to the LogFormat line:

LogFormat "%a %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

And add to the vhost statement

RemoteIPHeader X-Forwarded-For

And restart apache

apache2ctl restart

Also, on the reverse proxy vhost add this header

Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"

Redirect source IP to VMs

If nextclod is running behind a reverse proxy server in order to redirerct the source IP to the VM on the VM's enable these 2 modules:

a2enmod remoteip && a2enmod headers
systemctl restart apache2

Add this to the apache vhost

RemoteIPHeader X-Forwarded-For

Comment this line in /etc/apache2/apache2.conf

LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

and add this one under

LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

Add this to /var/www/nextcloud/config/config.php

  'forwarded_for_headers' =>
  array (
    0 => 'HTTP_X_FORWARDED_FOR',
  ),

Reload apache2 config

apache2ctl graceful

Completing NextCloud installation

To complete the installation you need to temporarily set the nextcloud web directory permissions to be writable by the Apache user

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

Now go the web interface to complete. Note that if using "local" as your DB connection then the host entry (last box) on the wizard database part should be the path to the DB:

/var/run/postgresql/

and you should leave the password blank. Otherwise configure for your (master) DB server.

If you are going to run Nextcloud behind a proxy and use HTTP between proxy and Nextcloud server, it might not load some images like the logo, for this you have to add/modify a few values to /var/www/nextcloud/config/config.php

'overwrite.cli.url' => 'https://your.domain.com',
'overwriteprotocol' => 'https',
'trusted_proxies' =>
array (
  0 => 'your.pro.xy.ip',
),

Setting cron to run background jobs

To ensure that background jobs are always running it's recommended to use crons to run the Nextcloud background tasks. So go on the web interface to Settings -> Basic Settings and select "Cron" instead of "Ajax". After this go to server's CLI and run

crontab -u www-data -e

and add

*/5  *  *  *  * php -f /var/www/nextcloud/cron.php

Setting the log rotate

Nextcloud logs are not rotated by default and this would lead to very big log files in the future. To rotate logs when the file reaches 10MB add this to /var/www/nextcloud/config/config.php

'log_rotate_size' => 10485760,

Upgrade process (updater app)

With a simple install, the updater app will run through and complete the upgrade, notifying via the UI if there is any intervention needed e.g. if it finds files/folders in the NC tree it's not expecting. With a larger install, the updater app will take care of most steps, but for the final stage of upgrading the DB, you will need to complete with the occ command, by:

su - www-data -s /bin/bash  -c 'php /path/to/nextcloud/occ upgrade'

(where www-data is your web server user)

Upgrade process (manual)

In NC11 the internal updater should be able to takeover the updating process but in the meantime a manual upgrade can be done following the below process.

Download the new version.

Put nextcloud into maintenance mode

su - www-data -s /bin/bash -c 'php /var/www/nextcloud/occ maintenance:mode --on'

and stop your webserver

service apache2 stop

If using external storage for any of your data, unmount it now.

Download the latest version (but not more than one major version than is currently installed on the server) as per instructions above. If you do not have a recent backup of your installation, make one now. Separately make a copy of your current config to be safe.

cp config/config.php config/config.php.ours

Then rename your nextcloud directory

mv /var/www/nextcloud/ /var/www/nextcloud.old

unzip the new download and move the resulting nextcloud directory to your web root.

Move your config.php and data directory to the upgraded installation directory (and/remount any external storage in use)

mv nextcloud.old/config/config.php nextcloud/config/
mv nextcloud.old/data/ nextcloud/
service apache2 start

Fix permissions using the script described in the installation stages above and then run the upgrader. If manually upgrading to NC11 on 14.04 you'll need to Upgrade to PHP5.6

su - www-data -s /bin/bash -c 'php /var/www/nextcloud/occ upgrade'

And assuming no errors from the upgrade process, turn maintenance mode off

su - www-data -s /bin/bash -c 'php /var/www/nextcloud/occ maintenance:mode --off'

Optimization

Nextcloud can be optimized with memory caching, for that we need to install these packages:

apt-get install php-apcu redis-server php-redis

After that add these lines to /var/www/nextcloud/config/config.php

'memcache.distributed' => '\\OC\\Memcache\\Redis',
'memcache.local' => '\\OC\\Memcache\\APCu',
'filelocking.enabled' => 'true',
'memcache.locking' => '\\OC\\Memcache\\Redis',
'redis' =>
array (
    'host' => 'localhost',
    'timeout' => 0,
    'dbindex' => 0,
    'port' => 6379,
),

And restart apache2

apache2ctl graceful


NOTE: If Nextcloud reports that background jobs are not running or the occ command can't be ran and throws this error:

An unhandled exception has been thrown:
OC\HintException: [0]: Memcache \OC\Memcache\APCu not available for local cache (Is the matching PHP module installed and enabled?)

Then you need to add this line to /etc/php/7.4/mods-available/apcu.ini

apc.enable_cli=1

And reload apache

apache2ctl graceful

Session Expiration

if you want to set the session expiration add this to /var/www/nextcloud/config/config.php

  'session_lifetime' => 60 * 60 * 8,
  'session_keepalive' => false,

Nextcloud as OAuth2 provider

When Nextcloud is configured as an OAuth2 provider, Nextcloud and the client service will need to have some direct communication, but unfortunately that communication will be tagged by NC's bruteforce mechanism as spam/harmful and will start to throttle the client service. To fix this go to the admin panel on NC, under Administration -> Security -> Brute-force IP whitelist and whitelist the IP of the client service. Because there might be firewalls and other devices between, you can check the exact IP that needs to be whitelisted in the oc_bruteforce_attempts DB table.