Nextcloud Setup Guide - ajgillis04/GillisDockerDepot GitHub Wiki

Nextcloud Containerized Setup Guide

Note for QNAP: Do not host Nextcloud user data inside their NAS home folders. Permissions will conflict with containerized Nextcloud. Instead, move user data to a dedicated folder (e.g., /share/CACHEDEV2_DATA/nextcloud/$user) and symlink if needed.


Introduction

This guide provides steps to set up a Nextcloud instance using a regular containerized setup. It is ideal if you require full control over the deployment or if you’ve migrated from Nextcloud AIO.


Prerequisites

  • Docker and docker-compose installed
  • NAS storage or a local directory for external storage
  • Environment variables for modular configuration
  • MariaDB (for self-hosting databases)

Configuration steps

Step 1: Prepare the Docker environment

  1. Create or update the .env file to manage configurations:
NEXTCLOUD_HOMES=/path/to/homes  # Avoid using symlinks; Nextcloud does not handle them well
NEXTCLOUD_EXSTORAGE=/share
  1. Create a blank database in MariaDB for Nextcloud to use:
docker exec -it mariadb.${HOST_NAME} /usr/bin/mariadb -u root -p
CREATE DATABASE nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER 'nextclouduser'@'%' IDENTIFIED BY 'yourpassword';
GRANT ALL PRIVILEGES ON nextcloud.* TO 'nextclouduser'@'%';
FLUSH PRIVILEGES;
EXIT;
  1. Test if the database is set up correctly:
docker exec -it mariadb.${HOST_NAME} mysql -u nextclouduser -p --password={your password} -e "SHOW DATABASES;"

Step 2: First-time setup

  1. Open your browser and navigate to http://<your-server-ip>:8080.
  2. Select Storage & Database.
  3. Enter a new admin account name and specify the database connection:
    • Database account: contents of secrets/nextcloud_mysql_user
    • Database password: contents of secrets/nextcloud_mysql_password
    • Database name: nextcloud
    • Database host: mariadb.${HOST_NAME}

NextCloud Initial1 NextCloud Initial


Step 3: Optional Apps and Why They’re Useful

  • Brute-force settings
    Helps protect your Nextcloud instance by limiting repeated failed login attempts. This reduces the risk of brute-force attacks and keeps accounts secure.

  • Calendar
    Provides a shared calendar system directly inside Nextcloud. Great for personal scheduling, team coordination, and syncing with other calendar clients.

  • Configurable Share Links
    Lets you customize how file and folder share links behave (expiry dates, permissions, etc.). This gives you more control over how data is shared externally.

  • Contacts
    Centralizes contact management. You can sync contacts across devices and integrate them with other apps like Mail or Calendar.

  • External storage support
    Enables mounting external storage sources (NAS shares, S3, SMB, etc.) into Nextcloud. This is essential for integrating your NAS directories with Nextcloud.

  • Mail
    A built-in email client that connects to your existing mail accounts. Useful for consolidating communication within Nextcloud.

  • Nextcloud Office
    Provides collaborative document editing (based on Collabora or OnlyOffice). Allows multiple users to work on text documents, spreadsheets, and presentations in real time.

  • Notes
    A simple note-taking app that syncs across devices. Handy for jotting down ideas, tasks, or documentation directly in Nextcloud.

  • Two-Factor Email
    Adds email-based two-factor authentication. This strengthens account security by requiring a one-time code sent via email in addition to the password.


Step 4: Configure basic settings

  1. Set up external storage:
    • Enable the External Storage Support app under Settings → Apps.
    • Go to Settings → Administration → External storages and add your storage volumes (e.g., /homes).

NextCloud ExternalStorage

  1. Modify config.php
sudo nano /path/to/files/GillisDockerDepot/appdata/nextcloud/var/www/html/config/config.php

Add or adjust the following entries:

'trusted_domains' => [
  'localhost',
  'nextcloud.example.com',  // your public-facing domain
  '192.168.1.100',
  '127.0.0.1',
  '::1',
],

'default_phone_region' => 'CA',

'trusted_proxies' => [
  '172.30.0.0/24',   // container subnet
  '192.168.1.0/24',  // LAN subnet
  '127.0.0.1',
  '::1',
],

'memcache.local'    => '\\OC\\Memcache\\APCu',
'memcache.locking'  => '\\OC\\Memcache\\APCu',

'overwrite.cli.url' => 'https://nextcloud.example.com',
'overwritehost'     => 'nextcloud.example.com',
'overwriteprotocol' => 'https',
'overwritewebroot'  => '/',

'maintenance_window_start' => '03:00',

Additional Notes

  • Match your Cloudflare application URL:
    Set overwritehost and overwriteprotocol to the public Cloudflare domain (e.g., nextcloud.example.com with https).

  • Split applications if needed:
    If you use separate subdomains for browser SSO and sync clients, include both in trusted_domains and document which endpoint each client should use.

  • Validate from outside your LAN:
    Run:

    curl -I https://nextcloud.example.com
    

    to confirm headers are passed correctly through Cloudflare.


Why add your domains?

  • Prevents Nextcloud from rejecting proxied requests.
  • Ensures both browser logins (nextcloud.example.com) and sync clients (sync.example.com) are trusted.
  • Keeps your setup consistent when splitting apps (browser SSO vs sync endpoints).
  • Combined with Cloudflare ranges, ensures Nextcloud logs the real client IP and avoids session issues.

Restart the container:

docker restart nextcloud.$<HOST_NAME>

Step 5: Other settings

  1. Whitelist your IP under Security → Brute-force IP whitelist. Add your ISP IP with a /24 mask.

NextCloud Config2 NextCloud Config3

  1. Set password policy as required. NextCloud Config4

  2. Configure email server under Basic settings → Email server. NextCloud Config6

  3. Set up users and groups. NextCloud Config5

Example script:

export OC_PASS=whateverpassword
/var/www/html/occ user:add --password-from-env --display-name="Test User" --group="users" [email protected]
  1. Configure external storage under Administration → External storages. NextCloud Config7

🌐 Step 6: Cloudflare Integration for Nextcloud

1. Cloudflare Access Application & Policy

  • In Cloudflare Zero Trust, go to Access → Applications → Add an Application.
  • Choose Self‑hosted and enter your Nextcloud domain (e.g., nextcloud.example.com).
  • Under Access → Policies, create a Bypass policy for your sync client endpoint:
    • Action: Bypass
    • Include: sync.example.com (or whichever subdomain you use for the desktop/mobile sync client)
    • Exclude: none (unless you want to block specific ranges)
  • This ensures browser logins go through Cloudflare Access, but sync clients can connect directly.
  • Save the application and policy.

2. DNS Setup

  • In Cloudflare DNS, create CNAME records for:
    • sync.example.com → <TUNNEL_ID>.cfargotunnel.com
  • Ensure Proxy status is enabled (orange cloud).

3. Nextcloud config.php Adjustments

Open your Nextcloud config file:

sudo nano /path/to/files/GillisDockerDepot/appdata/nextcloud/var/www/html/config/config.php

Add or adjust:

'trusted_domains' => [
  'localhost',
  'nextcloud.example.com',
  'sync.example.com',
  '127.0.0.1',
  '::1',
],

'default_phone_region' => 'CA',

'trusted_proxies' => [
  // Internal ranges
  '172.30.0.0/24',   // container subnet
  '192.168.1.0/24',  // LAN subnet
  '127.0.0.1',
  '::1',

  // Cloudflare IPv4 ranges
  '173.245.48.0/20',
  '103.21.244.0/22',
  '103.22.200.0/22',
  '103.31.4.0/22',
  '141.101.64.0/18',
  '108.162.192.0/18',
  '190.93.240.0/20',
  '188.114.96.0/20',
  '197.234.240.0/22',
  '198.41.128.0/17',
  '162.158.0.0/15',
  '104.16.0.0/13',
  '104.24.0.0/14',
  '172.64.0.0/13',
  '131.0.72.0/22',

  // Cloudflare IPv6 ranges
  '2400:cb00::/32',
  '2606:4700::/32',
  '2803:f800::/32',
  '2405:b500::/32',
  '2405:8100::/32',
  '2a06:98c0::/29',
  '2c0f:f248::/32',
],

'memcache.local'    => '\\OC\\Memcache\\APCu',
'memcache.locking'  => '\\OC\\Memcache\\APCu',

'overwrite.cli.url' => 'https://nextcloud.example.com',
'overwritehost'     => 'nextcloud.example.com',
'overwriteprotocol' => 'https',
'overwritewebroot'  => '/',

'maintenance_window_start' => '03:00',

4. Validation

  • Access https://nextcloud.example.com externally — you should reach the Nextcloud UI.
  • Test sync client with https://sync.example.com.
  • Run:
curl -I https://nextcloud.example.com

to confirm headers are passed correctly through Cloudflare.

  • Check Nextcloud logs to confirm real client IPs are logged (thanks to trusted_proxies).

Step 7: Setting up phone for auto backups

  1. Open the Nextcloud app and enter the server address (https://sync.example.com).
  2. Connect and grant access.
  3. Create a Photos folder under Documents.
  4. Configure Auto upload in app settings to point to this folder.

NextCloud Phone1 NextCloud Phone2 NextCloud Phone3


Step 8: Maintenance and logs

  1. Clear logs:
docker exec -it nextcloud.<host> bash -c "echo '' > /var/www/html/data/nextcloud.log"
  1. Monitor resource usage:
docker stats
  1. Disable file versioning (recommended if syncing large files like Outlook PSTs). Nextcloud’s versioning feature automatically keeps historical copies of files in file_versions/.
docker exec -it nextcloud.<host> bash -c "su -s /bin/bash www-data -c 'php occ app:disable files_versions'"

Keeping Nextcloud Updated

  • Pin the major version in compose, for example image: nextcloud:34-apache, rather than latest. Watchtower can then apply the 34.x patch releases monthly, and Nextcloud upgrades itself on start.
  • Nextcloud only allows one major version per step: 31 → 32 → 33 → 34. Jumping further fails with "upgrading from 31 to 33 is not supported".
  • Before a major upgrade: turn on maintenance mode, dump the database, and copy the html folder without data/:
    docker exec -u www-data nextcloud.<host> php occ maintenance:mode --on
    docker exec -e MYSQL_PWD=<db password> mariadb.<host> mariadb-dump -u <db user> --single-transaction nextcloud | gzip > nextcloud-db.sql.gz
    tar -czf html-without-data.tgz --exclude=html/data -C /path/to/appdata/nextcloud/var/www html
    docker exec -u www-data nextcloud.<host> php occ maintenance:mode --off
  • Step through each major: change the tag, up -d, wait until occ status shows the new version, then do the next one. Afterwards:
    docker exec -u www-data nextcloud.<host> php occ db:add-missing-indices
    docker exec -u www-data nextcloud.<host> php occ maintenance:repair --include-expensive
    docker exec -u www-data nextcloud.<host> php occ app:update --all
  • Apps without a version for the new major are disabled during the upgrade; app:update --all brings back the ones that have caught up.

Background Jobs (Cron Container)

Nextcloud's background jobs clean up expired file locks, versions and trash, generate previews and send notifications. With background jobs set to Cron, something must run cron.php every 5 minutes; the official image doesn't do it itself. If Administration → Overview says the last job ran days or months ago, nothing is running it, and you'll see errors like "file is locked".

Add a second container from the same image, sharing the same volumes, that only runs cron:

  nextcloud-cron:
    container_name: nextcloud-cron.${HOST_NAME}
    image: nextcloud:34-apache          # keep in step with the main container
    entrypoint: /cron.sh
    environment:
      TZ: ${TZ}
      PHP_MEMORY_LIMIT: 2G              # photo metadata jobs can exceed the 512M default
    depends_on:
      - nextcloud
    volumes:
      - ${DOCKERDIR}/nextcloud/var/www/html:/var/www/html
      - ${NEXTCLOUD_EXSTORAGE}:/nasshares
      - ${NEXTCLOUD_HOMES}:/homes
    restart: always

After months without cron, the first run works through a big backlog. Run it once by hand and watch for memory errors:

docker exec -u www-data nextcloud-cron.<host> php -f /var/www/html/cron.php

Security Headers and PHP Settings

  • HSTS: mount a small Apache config so Nextcloud sends Strict-Transport-Security:
    <IfModule mod_headers.c>
        Header always set Strict-Transport-Security "max-age=15552000"
    </IfModule>
        volumes:
          - ${BASE_DIR}/compose/nextcloud/hsts.conf:/etc/apache2/conf-enabled/zz-hsts.conf:ro
    Behind Cloudflare, the admin page's check sees Cloudflare's own HSTS header, so it may still warn until HSTS is also enabled in Cloudflare (SSL/TLS → Edge Certificates).
  • Real client IPs through a tunnel: add Cloudflare's headers so brute-force protection sees real addresses:
    docker exec -u www-data nextcloud.<host> php occ config:system:set forwarded_for_headers 0 --value=HTTP_CF_CONNECTING_IP
    docker exec -u www-data nextcloud.<host> php occ config:system:set forwarded_for_headers 1 --value=HTTP_X_FORWARDED_FOR
  • Shared PHP settings: an .ini file mounted into /usr/local/etc/php/conf.d/ applies to every PHP container that mounts it, which is handy for security settings such as session.upload_progress.enabled = 0 when PHP advises it.

Permissions model for NAS + Nextcloud

  1. Create per-user directories on NAS (outside home folders):

    • /share/CACHEDEV2_DATA/nextcloud/$user
  2. Set ownership to NAS user UID and Nextcloud group (GID 33 = www-data), with perms 770:

# Examples
sudo chown -R 1001:33 /share/CACHEDEV2_DATA/nextcloud/user1 && sudo chmod -R 770 /share/CACHEDEV2_DATA/nextcloud/user1
sudo chown -R 1002:33 /share/CACHEDEV2_DATA/nextcloud/user2 && sudo chmod -R 770 /share/CACHEDEV2_DATA/nextcloud/user2
sudo chown -R 1003:33 /share/CACHEDEV2_DATA/nextcloud/user3 && sudo chmod -R 770 /share/CACHEDEV2_DATA/nextcloud/user3
  1. Validate:
ls -ld /share/CACHEDEV2_DATA/nextcloud/*

Expect: drwxrwx--- and group = www-data

📌 Granting Users Read/Write Access to Nextcloud

Each Nextcloud user has a personal directory under:

/share/CACHEDEV2_DATA/nextcloud/$user

Ownership & Permissions

  • Owner: the NAS user account (UID).
  • Group: www-data (GID 33).
  • Permissions: 770 → owner + www-data full access, others none.

Example setup:

sudo chown -R <UID>:33 /share/CACHEDEV2_DATA/nextcloud/<user>
sudo chmod -R 770 /share/CACHEDEV2_DATA/nextcloud/<user>

Validate with:

ls -ld /share/CACHEDEV2_DATA/nextcloud/*

Expect: drwxrwx--- user www-data

QNAP GUI Privileges

  • In Control Panel → Privilege Settings → Shared Folders → nextcloud, grant each user Read/Write access to the nextcloud share.
  • Combined with POSIX 770, this ensures:
    • ✅ Users can fully manage their own files.
    • ✅ Nextcloud services (www-data) can sync and maintain data.
    • ❌ Users cannot read or write in other users’ directories.
⚠️ **GitHub.com Fallback** ⚠️