How to Install NextCloud 13 on Ubuntu Server 18.04 LTS

Post Reply
User avatar
LHammonds
Site Admin
Site Admin
Posts: 712
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

How to Install NextCloud 13 on Ubuntu Server 18.04 LTS

Post: # 686Post LHammonds
Fri Aug 31, 2018 9:29 am

------------- WORK-IN-PROGRESS -------------

Greetings and salutations,

I hope this thread will be helpful to those who follow in my foot steps as well as getting any advice based on what I have done / documented.

To discuss this thread, please participate here: << Insert Ubuntu Forums Link >>

High-level overview

NextCloud is a web application that can store and serve content from a centralized location, much like Dropbox. The difference is that NextCloud allows you to host the serving software on your own machines, taking the trust issues out of putting your personal data someone else's server.

This tutorial will cover how to manually setup an NextCloud server which will use a separate dedicated database server and SSL encryption.

Advantages of manually installing NextCloud:
* Can use the latest version of NextCloud currently available (Repository rarely contains latest version)
* Are not forced to install MySQL locally (handy if you have a dedicated database server)
* Can install where you want (such as standard / well-known locations)

Disadvantages of manually installing NextCloud:
* Will not automatically update the system via "apt-get update" (although you are not guaranteed you get the latest this way either...just the latest in the repository)
* Not as easy to install (thus this step-by-step guide)

Tools utilized in this process
Helpful links

The list below are sources of information that was helpful in the creation of this document.
Assumptions

This documentation will need to make use of some very-specific information that will most-likely be different for each person / location. And as such, this information will be noted in this section. They will be highlighted in red throughout the document as a reminder that you should plug-in your own value rather than actually using these "place-holder" values.

Under no circumstance should you use the actual values listed below. They are place-holders for the real thing. This is just a checklist template you need to have answered before you start the install process.

Wherever you see RED in this document, you need to substitute it for you will use in your environment.
  • Internet domain: nextcloud.mydomain.com
  • Ubuntu Server name: srv-nextcloud
  • Ubuntu Server IP address: 192.168.107.9
  • Ubuntu Admin ID: administrator
  • Ubuntu Admin Password: myadminpass
  • Database Server Name (remote): srv-database
  • Database Server IP (remote): 192.168.107.20
  • Database Admin ID: root
  • Database Admin Password: rootpass
  • Database ID: nextclouduser
  • Database Password: nextclouduserpass
  • Email Server Name (remote): srv-mail
  • Email Server IP (remote): 192.168.107.25
  • NextCloud Admin ID: NextCloudAdmin
  • NextCloud Admin Password: nextcloudadminpass
NextCloud Ubuntu Server - Setup an Ubuntu server for use as the NextCloud server. This tutorial assumes the server was configured according to this tutorial: How to install and configure Ubuntu Server

MySQL/MariaDB server - Setup a separate and dedicated database server. This tutorial assumes the server was configured according to this tutorial: How to install and configure MariaDB

It is also assumed the reader knows how to use the VI editor. If not, you will need to beef up your skill set or use a different editor in place of it.

User avatar
LHammonds
Site Admin
Site Admin
Posts: 712
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Prior to install

Post: # 687Post LHammonds
Fri Aug 31, 2018 9:33 am

Firewall Rules for Web Server

Code: Select all

vi /var/scripts/prod/en-firewall.sh
Find and uncomment the following lines (remove the hashtag "#") to enable port 80 and 443:

Code: Select all

echo "Adding Web Server rules"
ufw allow proto tcp to any port 80 comment 'Web Service' 1>/dev/null 2>&1
ufw allow proto tcp to any port 443 comment 'Web Service' 1>/dev/null 2>&1
Now run the script to update the firewall to open up access to the web server.

Name Resolution

Add your NextCloud domain(s) so they point to the local loopback (127.0.0.1)
Add your other remote servers such as your mail and database server IPs so you can reference them by name.

Code: Select all

vi /etc/hosts

Code: Select all

127.0.0.1       localhost
127.0.1.1       srv-nextcloud
127.0.0.1	nextcloud.mydomain.com
192.168.107.25  srv-mail
192.168.107.20  srv-database
Prerequisites

Install Apache web server:

Code: Select all

apt-get -y install apache2
Install PHP for Apache with MySQL/MariaDB support

Code: Select all

apt-get -y install php7.2 libapache2-mod-php7.2 php7.2-mysql
TIP: You can search available PHP packages names by typing this:

Code: Select all

apt-cache search php7.2
TIP: You can see which PHP modules are installed by typing this:

Code: Select all

php -m
There are various required, recommended, app-specific modules listed on the requirements section of the manual.

The below will show what is already installed by default and what will be needed as a complete list. You can customize to your needs.

PHP modules:

Code: Select all

bz2
ctype
curl - Missing (contained in php7.2-curl)
dom - Missing (contained in php7.2-xml)
exif
fileinfo
ftp
gd - Missing (contained in php7.2-gd)
iconv
imagick - Missing (contained in php-imagick)
intl - Missing (contained in php7.2-intl)
gmp - Missing (contained in php7.2-gmp)
json
libxml
mbstring - Missing (contained in php7.2-mbstring)
mcrypt - No longer available (now contained in PECL repository)
openssl
pdo_mysql
posix
simplexml - Missing (contained in php7.2-xml)
smbclient - Missing (contained in php-smbclient)
xmlreader - Missing (contained in php7.2-xml)
xmlwriter - Missing (contained in php7.2-xml)
zip - Missing (contained in php7.2-zip)
zlib
Install the missing PHP modules with these packages:

Code: Select all

apt-get -y install php7.2-gd php7.2-zip php7.2-xml php7.2-mbstring php7.2-curl php7.2-intl php7.2-gmp php-imagick php-smbclient
To install the mcrypt module, you need to install mcrypt for the operating system, then install the module that interfaces with mcrypt in the PECL repository.

??????

Code: Select all

apt-get -y mcrypt
NOTE: Need to research how to install / configure / enable LibreOffice and video previews.

Enable various options in Apache:

Code: Select all

a2enmod rewrite
a2enmod headers
a2enmod env (probably already enabled)
a2enmod dir (probably already enabled)
a2enmod mime (probably already enabled)
Modify PHP to allow uploading of larger files and correct OPcache settings. In the below example, it allows 2GB uploads.

Code: Select all

vi /etc/php/7.2/apache2/php.ini

Code: Select all

default_charset = "UTF-8"
post_max_size = 2058M
upload_max_filesize = 2048M
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=1
opcache.save_comments=1
Reload Apache for changes to the config to take affect:

Code: Select all

systemctl reload apache2
PHP Information

To verify Apache, PHP and modules are installed and enabled, lets create the famous phpinfo page.

Code: Select all

touch /var/www/html/phpinfo.php
chown www-data:www-data /var/www/html/phpinfo.php
chmod 0644 /var/www/html/phpinfo.php
echo "<?php phpinfo(); ?>" >> /var/www/html/phpinfo.php
Open a browser and load up the phpinfo page: http://192.168.107.9/phpinfo.php

You should be able to scroll down and see sections for each module we wanted enabled. If you don't see a dedicated section, then that module is not installed/enabled.

When done, do not forget to remove the info file:

Code: Select all

rm /var/www/html/phpinfo.php

User avatar
LHammonds
Site Admin
Site Admin
Posts: 712
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Database Configuration

Post: # 688Post LHammonds
Fri Aug 31, 2018 11:03 am

Configure MariaDB / MySQL

In this scenario, a dedicated and general-purpose database server already exists and it will be used to hold the application's database.
  1. Connect to the MariaDB/MySQL server using PuTTY.
  2. At the login prompt, login with your administrator account (administrator / myadminpass) and then temporarily grant yourself super user privileges by typing sudo su
  3. Type the following commands:
    mysql -u root -p Enter password: rootpass
    CREATE DATABASE nextcloud CHARACTER SET utf8 COLLATE utf8_bin; CREATE USER 'nextclouduser'@'%' IDENTIFIED BY 'nextclouduserpass'; GRANT ALL ON nextcloud.* TO 'nextclouduser'@'%'; FLUSH PRIVILEGES; exit
    The above commands will allow the database account to connect from any machine from anywhere in the world. This might be OK if your database is not accessible outsite your local network or if your machine name changes or you have multiple servers that connect to the same database that use the same ID. You can make this more secure by specifying your application server when granting access. Make sure the database server will recognize the server name (via hosts file or DNS) or just use the IP address:
    CREATE USER 'nextclouduser'@'srv-nextcloud' IDENTIFIED BY 'nextclouduserpass'; GRANT ALL ON nextcloud.* TO 'nextclouduser'@'srv-nextcloud';
    or
    CREATE USER 'nextclouduser'@'192.168.107.9' IDENTIFIED BY 'nextclouduserpass'; GRANT ALL ON nextcloud.* TO 'nextclouduser'@'192.168.107.9';
    This will prevent anyone knowing the credentials from logging into the database from any other remote machine not specified in the grant command.

    If your application is running on the database server (typical on a developer machine / non-production scenario), create the user like this:
    CREATE USER 'nextclouduser'@'localhost' IDENTIFIED BY 'nextclouduserpass'; GRANT ALL ON nextcloud.* TO 'nextclouduser'@'localhost';
    This will prevent anyone knowing the credentials from logging into the database from any other remote machine.

    If you mess anything up, you can remove the database and user by issuing these commands:
    DROP USER nextclouduser; FLUSH PRIVILEGES; DROP DATABASE nextcloud;
  4. To avoid the "impossible to write to binary log since BINLOG_FORMAT = STATEMENT" error message when accessing the NextCloud page the 1st time which creates the database tables/data, you need to edit the "my.cnf" on the MySQL/MariaDB server to include the following setting:

    Code: Select all

    binlog-format=MIXED
    Then restart the database service:

    Code: Select all

    service mysql restart

User avatar
LHammonds
Site Admin
Site Admin
Posts: 712
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

NextCloud Installation

Post: # 689Post LHammonds
Fri Aug 31, 2018 11:07 am

NextCloud

We are installing manually instead of using the package manager for the following reasons:
  • Can obtain the newer version straight from NextCloud's website
  • Don't want MySQL installed on the same server since I have a dedicate DB server (and also would rather use MariaDB)
  • Want to use my own paths rather than the path Ubuntu uses which is different than everyone else.
Multiple web sites - This documentation assumes NextCloud will be an additional web site running on this server and as such will configure its own .conf files and manage each site separately.

Code: Select all

cd /tmp
wget https://download.nextcloud.com/server/releases/nextcloud-13.0.6.zip.md5
wget https://download.nextcloud.com/server/releases/nextcloud-13.0.6.zip
Verify the file integrity of the download. Compare both numbers and insure they are identical:

Code: Select all

md5sum /tmp/nextcloud-13.0.6.zip
432caeb725dd1a329cc9684d1d841140  /tmp/nextcloud-13.0.6.zip

cat /tmp/nextcloud-13.0.6.zip.md5
432caeb725dd1a329cc9684d1d841140  nextcloud-13.0.6.zip
Extract the archive:

Code: Select all

cd /tmp
unzip /tmp/nextcloud-13.0.6.zip
chown www-data:www-data -R /tmp/nextcloud/
mv /tmp/nextcloud /var/www/nextcloud
rm /tmp/nextcloud*.zip
rm /tmp/nextcloud*.md5
Create the data repository location. It is recommended to keep this "Data" folder from being anywhere inside the web root folder to ensure users cannot simply browse it.

Code: Select all

mkdir -p /var/www/nextcloud-data
chown www-data:www-data -R /var/www/nextcloud-data
Install NextCloud (create database)

Code: Select all

cd /var/www/nextcloud/
sudo -u www-data php occ  maintenance:install --database "mysql" --database-host="srv-mysql" --database-name "nextcloud" --database-table-prefix "nc_" --database-user "nextclouduser" --database-pass "nextclouduserpass" --data-dir "/var/www/nextcloud-data" --admin-user "nextcloudadmin" --admin-pass "nextcloudadminpass"
NextCloud Configuration File

Make sure your config looks similar to this but substituting your actual values and adding any missing lines:

Code: Select all

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

Code: Select all

<?php
$CONFIG = array (
  'instanceid' => 'ocndnnro5l72',
  'passwordsalt' => 'bhiABCw6D7Ed3IF+mHpIzJF06vKLMN',
  'secret' => 'abcdefghijklmnopqrstuvwxyz123456790',
  'trusted_domains' =>
  array (
    0 => 'nextcloud.mydomain.com',
    1 => '192.168.107.10',
    2 => 'localhost',
  ),
  'datadirectory' => '/var/www/nextcloud-data',
  'overwrite.cli.url' => 'http://nextcloud.mydomain.com',
  'htaccess.RewriteBase' => '/',
  'dbtype' => 'mysql',
  'version' => '12.0.4.3',
  'dbname' => 'nextcloud',
  'dbhost' => 'srv-mysql',
  'dbport' => '',
  'dbtableprefix' => 'nc_',
  'dbuser' => 'nextclouduser',
  'dbpassword' => 'nextclouduserpass!',
  'auth.bruteforce.protection.enabled' => true,
  'installed' => true,
);
Create Apache Config for NextCloud

Code: Select all

vi /etc/apache2/sites-available/nextcloud.conf
<VirtualHost *:80> ServerAdmin webmaster@localhost ServerName nextcloud.mydomain.com DocumentRoot /var/www/nextcloud ErrorLog ${APACHE_LOG_DIR}/nc-error.log CustomLog ${APACHE_LOG_DIR}/nc-access.log combined <Directory /var/www/nextcloud/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all <IfModule mod_dav.c> Dav off </IfModule> SetEnv HOME /var/www/nextcloud SetEnv HTTP_HOME /var/www/nextcloud </Directory> </VirtualHost>
Enable the site configuration:

Code: Select all

a2ensite nextcloud
If you need to disable the site in the future:

Code: Select all

a2dissite nextcloud
Reload the Apache config so it is aware of the modified virtual host

Code: Select all

service apache2 reload
NextCloud Login

Now, go to your IP address or domain name in your browser:
Example: http://192.168.107.9/ or http://nextcloud.mydomain.com/
Make sure you can login with your admin account.

User avatar
LHammonds
Site Admin
Site Admin
Posts: 712
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Post-Installation

Post: # 690Post LHammonds
Fri Aug 31, 2018 11:09 am

Directory Security

During install, you should have set the user/group ownership to match your web server (www-data for Apache on Ubuntu).

These are the default permissions for your NextCloud directories and files:
  • All files should be read-write for the file owner, read-only for the group owner, and zero for the world (640)
  • All directories should be executable (because directories always need the executable bit set), read-write for the directory owner, and read-only for the group owner (750)
  • The .htaccess files are read-write for the file owner, read-only group and world (644)
  • The .htaccess files should be owned by root:www-data
Let's create the script that will enforce the recommended permissions/ownership.

Code: Select all

mkdir -p /var/scripts/prod
touch /var/scripts/prod/nextcloud-secure.sh
chown root:root /var/scripts/prod/nextcloud-secure.sh
chmod 0755 /var/scripts/prod/nextcloud-secure.sh
vi /var/scripts/prod/nextcloud-secure.sh

Code: Select all

#!/bin/bash
#############################################
## Name          : nextcloud-secure.sh
## Version       : 1.1
## Date          : 2018-01-11
## Author        : LHammonds
## Compatibility : Ubuntu Server 16.04 LTS, NextCloud 13.0.1
## Purpose       : Ensures ownership and permissions are set correctly.
## Run Frequency : Manual as needed or via crontab schedule.
## NOTE: These settings will prevent the updater from working.
## The only thing needed to change in order for the updater to
## work is to change the rootuser to be the same as webuser.
################ CHANGE LOG #################
## DATE       WHO WHAT WAS CHANGED
## ---------- --- ----------------------------
## 2018-01-11 LTH Created script.
## 2018-03-29 LTH Improvments.
#############################################
wwwdir='/var/www/nextcloud'
datadir='/var/www/nextcloud-data'
webuser='www-data'
webgrp='www-data'
rootuser='root'

if [ ! -f ${wwwdir}/.htaccess ]; then
  echo "ERROR: Missing critical file: ${wwwdir}/.htaccess"
  echo "This file should have been included in the app archive"
fi
if [ ! -f ${wwwdir}/config/.htaccess ]; then
  echo "ERROR: Missing critical file: ${wwwdir}/config/.htaccess"
  echo "This file should have been included in the app archive"
fi
if [ ! -f ${datadir}/.htaccess ]; then
  echo "WARNING: Missing potentially critical file: ${datadir}/.htaccess"
  echo "If the data folder is not directly inside the"
  echo "www folder, then it is not an issue."
fi
echo "Making folders if they are missing..."
if [ ! -d ${wwwdir}/apps ]; then
  mkdir -p ${wwwdir}/apps
fi
if [ ! -d ${wwwdir}/config ]; then
  mkdir -p ${wwwdir}/config
fi
if [ ! -d ${wwwdir}/themes ]; then
  mkdir -p ${wwwdir}/themes
fi
if [ ! -d ${datadir} ]; then
  mkdir -p ${datadir}
fi
echo "Setting Ownership..."
chown -R ${webuser}:${webgrp} ${wwwdir}/
chown -R ${webuser}:${webgrp} ${wwwdir}/apps/
chown -R ${webuser}:${webgrp} ${wwwdir}/config/
chown -R ${webuser}:${webgrp} ${wwwdir}/themes/
chown ${rootuser}:${webgrp} ${wwwdir}/.htaccess
chown ${rootuser}:${webgrp} ${wwwdir}/config/.htaccess
chown ${rootuser}:${webgrp} ${datadir}/.htaccess
echo "Setting Folder Permissions..."
find ${wwwdir}/ -type d -print0 | xargs -0 chmod 0750
find ${datadir}/ -type d -print0 | xargs -0 chmod 0750
echo "Setting File Permissions..."
find ${wwwdir}/ -type f -print0 | xargs -0 chmod 0640
find ${datadir}/ -type f -print0 | xargs -0 chmod 0640
chmod 0644 ${wwwdir}/.htaccess
chmod 0644 ${wwwdir}/config/.htaccess
chmod 0644 ${datadir}/.htaccess
echo "Permission change complete."
Now just run the script

Code: Select all

/var/scripts/prod/nextcloud-secure.sh
You can also schedule the script via crontab to run on a regular basis to make sure the permissions never stay out of whack for long.

If you want to enable the updater to work, simply change the value of "rootuser" from "root" to "www-data"

Configure for secure (SSL) access

NEED TO CHANGE THIS TO LETS ENCRYPT

This will create a self-signed certificate that will expire 1,095 days (3 years) from the date it was created. Web browsers will balk about it being untrusted. It will still work but end-users will have to allow this exception unless you pay > $200 for an official SSL certificate issued by a trusted/known authority.

Code: Select all

a2enmod ssl
mkdir -p /etc/apache2/ssl/certs
mkdir -p /etc/apache2/ssl/private
openssl req -x509 -nodes -days 1095 -newkey rsa:2048 -keyout /etc/apache2/ssl/private/nextcloud.key -out /etc/apache2/ssl/certs/nextcloud.crt
  Country Name: US
  State: MyState
  Locality Name: MyCity
  Organication Name: MyCompany
  Organizational Unit Name: MyDepartment
  Common Name: nextcloud.mycompany.com
  Email Address: webmaster@mycompany.com
To verify the certificate:

Code: Select all

openssl x509 -in /etc/apache2/ssl/certs/nextcloud.crt -text -noout
To verify the private key:

Code: Select all

openssl rsa -in /etc/apache2/ssl/private/nextcloud.key -check
Create the SSL web config

Code: Select all

vi /etc/apache2/sites-available/nextcloud-ssl.conf
Set these values:

Code: Select all

<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
                ServerName nextcloud.mydomain.com:443
                ServerAdmin webmaster@localhost
                DocumentRoot /var/www/nextcloud
                ErrorLog ${APACHE_LOG_DIR}/nc-error.log
                CustomLog ${APACHE_LOG_DIR}/nc-access.log combined
                SSLEngine on
                SSLCertificateFile /etc/apache2/ssl/certs/nextcloud.crt
                SSLCertificateKeyFile /etc/apache2/ssl/private/nextcloud.key
                <FilesMatch "\.(cgi|shtml|phtml|php)$">
                                SSLOptions +StdEnvVars
                </FilesMatch>
                <Directory /usr/lib/cgi-bin>
                                SSLOptions +StdEnvVars
                </Directory>
                <IfModule mod_headers.c>
                                Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
                </IfModule>
                BrowserMatch "MSIE [2-6]" \
                                nokeepalive ssl-unclean-shutdown \
                                downgrade-1.0 force-response-1.0
                BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
        </VirtualHost>
</IfModule>
Now we need to enable the SSL site configuration:

Code: Select all

a2ensite nextcloud-ssl
service apache2 reload
Force users to use SSL for enhanced security

Code: Select all

a2enmod rewrite

Code: Select all

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

Code: Select all

<VirtualHost *:80>
        #### Redirect to port 443 ###
        RewriteEngine on
        ReWriteCond %{SERVER_PORT} !^443$
        RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
        #### End of Redirection configuration ###

        ServerAdmin webmaster@localhost
        ServerName nextcloud.mydomain.com
        DocumentRoot /var/www/nextcloud
        ErrorLog ${APACHE_LOG_DIR}/nc-error.log
        CustomLog ${APACHE_LOG_DIR}/nc-access.log combined
        <Directory /var/www/nextcloud/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
                <IfModule mod_dav.c>
                  Dav off
                 </IfModule>
                SetEnv HOME /var/www/nextcloud
                SetEnv HTTP_HOME /var/www/nextcloud
        </Directory>
</VirtualHost>
Reload the updated configuration for Apache:

Code: Select all

service apache2 reload
Configure NextCloud Settings

Now, go to your IP address or domain name in your browser:
Example: http://192.168.107.9/ or http://nextcloud.mydomain.com/

It should automatically re-direct to https:// for secured SSL connection.

Login with your admin account and click the gear icon on top-right side, then click Admin

When the configuration check is complete, it should say "No problems found" if you did everything right (e.g. using SSL, .htaccess, etc.)

Email Server - Setup your mail sending capability here (choices vary depending on your mail server):
Send mode: smtp Encryption: SSL From address: nextcloud@mydomain.com Authentication method: Login Check: Authentication required Server address: mail.mydomain.com : 25 Credentials: smtpuser Password: smtppassword
On top-right side, click on the gear icon, then +Apps and then find and enable the following:
  • Office and Text -> Calendar
  • Office and Text -> Contacts
Add Users

While logged in with your admin user, click gear icon on top-right side and then Users
Click the "gear" icon on the lower-left corner to display settings.
Note the default space quota is set to Unlimited. You can configure the default here.
It would also be a good idea to place checkmarks beside "Send email to new user" and "Show email address"
In the empty "Username" "Password" and "Email" fields, add a user account and click "Create"
Repeat for each user you want added.

NextCloud comes with one default group: admin. When you create users, they will not belong to any group. If you need to create other groups, click the "+ Add group" link on the top-left and type in a name.

You can assign space limitations by setting the quota for each individual or just let it use the system-wide default quota.

Configure New User Folder Skeleton

When a new user is created, the following folder/files are copied to the new user's folder:

/var/www/nextcloud/core/skeleton/*

You can remove the example files and/or create new folders/files so it looks a certain way when a new person logs in.

Install New Apps

You can install other apps not listed with the default installation.
Visit this site: https://apps.nextcloud.com/?xsortmode=high

Post Reply