Setting Up Nextcloud on Raspberry Pi with Advanced Features
Prerequisites:
- Raspberry Pi Hardware:
- Raspberry Pi board (e.g., Raspberry Pi 4 Model B).
- MicroSD card (preferably 16GB or larger) for Raspberry Pi OS installation.
- Power supply compatible with your Raspberry Pi model.
- Raspberry Pi OS Installation:
- Download the latest Raspberry Pi OS Lite or Raspberry Pi OS with a desktop from the official Raspberry Pi website.
- Flash the Raspberry Pi OS image onto the microSD card using a tool like Raspberry Pi Imager or balenaEtcher.
- Insert the microSD card into your Raspberry Pi board and power it on.
- Follow the on-screen instructions to complete the initial setup of Raspberry Pi OS, including setting up Wi-Fi, expanding the filesystem, and configuring localization settings if necessary.
- Ensure your Raspberry Pi is connected to the internet via Ethernet or Wi-Fi.
- Installing Docker:
- Follow the official Docker installation guide for Raspberry Pi to install Docker on your Raspberry Pi OS. This typically involves adding Dockerβs official repository to your package manager and installing Docker packages using apt.
- Installing Docker Compose:
-
Follow the official Docker Compose installation guide to install Docker Compose on your Raspberry Pi OS.
File Structure:
/home/pi/nextcloud/
β
βββ Dockerfile.app
βββ Dockerfile.cron
βββ docker-compose.yml
βββ db.env
βββ nginx.conf
βββ certs/
βββ myCA.pem
βββ mycloud.example.com.crt
βββ mycloud.example.com.key
βββ dhparam.pem
Step 1: Docker Compose Configuration
First, create a docker-compose.yml
file with the following configuration:
Here /mnt/ad/nextcloud is the folder path of the external HDD in my Raspberry Pi. You can change this path.
version: '3'
services:
db:
image: postgres:alpine
restart: always
volumes:
- db:/var/lib/postgresql/data:Z
env_file:
- db.env
environment:
- PUID=109
- PGID=65534
networks:
- proxy-tier
cache:
image: redis:6.2-alpine
restart: always
ports:
- '6379:6379'
command: redis-server --save 20 1
volumes:
- cache:/data
networks:
- proxy-tier
app:
#image: nextcloud:fpm-alpine
build:
context: .
dockerfile: Dockerfile.app
container_name: nextcloud
restart: always
volumes:
- nextcloud:/var/www/html:z
- /mnt/ad/nextcloud:/extdata
- php-fpm:/usr/local/etc
- type: tmpfs
target: /tmp:exec
environment:
- POSTGRES_HOST=db
- REDIS_HOST=cache
- PHP_MEMORY_LIMIT=2048M
env_file:
- db.env
depends_on:
- db
- cache
devices:
- /dev/video10:/dev/video10
- /dev/video11:/dev/video11
- /dev/video12:/dev/video12
networks:
- proxy-tier
cron:
#image: nextcloud:fpm-alpine
build:
context: .
dockerfile: Dockerfile.cron
restart: always
volumes:
- nextcloud:/var/www/html:z
- /mnt/ad/nextcloud:/extdata
- php-fpm:/usr/local/etc
- type: tmpfs
target: /tmp:exec
entrypoint: /cron.sh
depends_on:
- db
- cache
devices:
- /dev/video10:/dev/video10
- /dev/video11:/dev/video11
- /dev/video12:/dev/video12
environment:
- PHP_MEMORY_LIMIT=2048M
networks:
- proxy-tier
imaginary:
image: ghcr.io/italypaleale/imaginary:master
container_name: imaginary
restart: always
ports:
- '9000:9000'
command: -enable-url-source
nginx-proxy:
image: nginx:alpine
container_name: nginx-proxy
ports:
- "8443:443"
volumes:
- sslcerts:/etc/nginx/ssl
- ./nginx.conf:/etc/nginx/nginx.conf
- nextcloud:/var/www/html:z,ro
networks:
- proxy-tier
depends_on:
- app
volumes:
db:
php-fpm:
nextcloud:
sslcerts:
cache:
driver: local
networks:
proxy-tier:
Step 2: Dockerfile Configuration [Dockerfile.app]
Create a Dockerfile.app
with the following content:
# Use the official Nextcloud image as a base image
FROM nextcloud:stable-fpm-alpine
# Install build essentials
RUN apk update && \
apk add --no-cache build-base
# Install imagemagick-common and ffmpeg
RUN apk add --no-cache ffmpeg \
&& apk add --no-cache nodejs npm \
&& apk add --no-cache util-linux \
&& apk add --no-cache git g++ cmake ghostscript libx11-dev sudo nano
# Set the NODE_PATH environment variable to point to the Node.js binary
ENV NODE_PATH /usr/bin/node
ENV NICE_CMD /usr/bin/nice
RUN git clone https://github.com/davisking/dlib.git \
&& cd dlib/dlib \
&& mkdir build \
&& cd build \
&& cmake -DBUILD_SHARED_LIBS=ON .. \
&& make \
&& make install
RUN git clone https://github.com/goodspb/pdlib.git /usr/src/php/ext/pdlib
RUN docker-php-ext-install pdlib
# Install BZip2 library and development files
RUN apk add --no-cache bzip2-dev
# Install php-bz2
RUN docker-php-ext-install bz2
# Install smbclient
RUN apk add --no-cache samba-client
# Clean up unnecessary build dependencies
RUN apk del build-base cmake git
Step 3: Dockerfile Configuration [Dockerfile.cron]
Create a Dockerfile.cron
with the following content:
# Use the official Nextcloud image as a base image
FROM nextcloud:stable-fpm-alpine
# Install build essentials
RUN apk update && \
apk add --no-cache build-base
# Install imagemagick-common and ffmpeg
RUN apk add --no-cache ffmpeg \
&& apk add --no-cache nodejs npm \
&& apk add --no-cache util-linux \
&& apk add --no-cache git g++ cmake ghostscript libx11-dev sudo nano
# Set the NODE_PATH environment variable to point to the Node.js binary
ENV NODE_PATH /usr/bin/node
ENV NICE_CMD /usr/bin/nice
RUN git clone https://github.com/davisking/dlib.git \
&& cd dlib/dlib \
&& mkdir build \
&& cd build \
&& cmake -DBUILD_SHARED_LIBS=ON .. \
&& make \
&& make install
RUN git clone https://github.com/goodspb/pdlib.git /usr/src/php/ext/pdlib
RUN docker-php-ext-install pdlib
# Install BZip2 library and development files
RUN apk add --no-cache bzip2-dev
# Install php-bz2
RUN docker-php-ext-install bz2
# Install smbclient
RUN apk add --no-cache samba-client
# Clean up unnecessary build dependencies
RUN apk del build-base cmake git
Step 4: Generating SSL/TLS Certificates and Diffie-Hellman Parameters
Execute the following commands in your terminal to generate SSL/TLS certificates and Diffie-Hellman parameters:
You donβt have to write anything for the certificate generation, just press the enter key
cd ~
sudo mkdir nextcloud/certs
cd nextcloud/certs
sudo su
openssl genrsa -out mycloud.example.com.key 2048
openssl req -x509 -new -nodes -key mycloud.example.com.key -sha256 -days 365 -out myCA.pem
openssl req -new -key mycloud.example.com.key -out mycloud.example.com.csr
openssl x509 -req -in mycloud.example.com.csr -CA myCA.pem -CAkey mycloud.example.com.key -CAcreateserial -out mycloud.example.com.crt -days 365 -sha256
openssl dhparam -out dhparam.pem 2048
Step 5: Create a db.env file at /home/pi/nextcloud
POSTGRES_PASSWORD=somesecurepassword
POSTGRES_DB=nextcloud
POSTGRES_USER=nextcloud
Step 6: Create nginx.conf file at /home/pi/nextcloud
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 10024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
# Prevent nginx HTTP Server Detection
server_tokens off;
keepalive_timeout 65;
#gzip on;
upstream php-handler {
server app:9000;
}
server {
listen 80;
# HSTS settings
# WARNING: Only add the preload option once you read about
# the consequences in https://hstspreload.org/. This option
# will add the domain to a hardcoded list that is shipped
# in all major browsers and getting removed from this list
# could take several months.
#add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;" always;
# set max upload size
client_max_body_size 512M;
fastcgi_buffers 64 4K;
# Enable gzip but do not remove ETag headers
gzip on;
gzip_vary on;
gzip_comp_level 4;
gzip_min_length 256;
gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;
# Pagespeed is not supported by Nextcloud, so if your server is built
# with the `ngx_pagespeed` module, uncomment this line to disable it.
#pagespeed off;
# HTTP response headers borrowed from Nextcloud `.htaccess`
add_header Referrer-Policy "no-referrer" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Download-Options "noopen" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Permitted-Cross-Domain-Policies "none" always;
add_header X-Robots-Tag "noindex, nofollow" always;
add_header X-XSS-Protection "1; mode=block" always;
# Remove X-Powered-By, which is an information leak
fastcgi_hide_header X-Powered-By;
# Path to the root of your installation
root /var/www/html;
# Specify how to handle directories -- specifying `/index.php$request_uri`
# here as the fallback means that Nginx always exhibits the desired behaviour
# when a client requests a path that corresponds to a directory that exists
# on the server. In particular, if that directory contains an index.php file,
# that file is correctly served; if it doesn't, then the request is passed to
# the front-end controller. This consistent behaviour means that we don't need
# to specify custom rules for certain paths (e.g. images and other assets,
# `/updater`, `/ocm-provider`, `/ocs-provider`), and thus
# `try_files $uri $uri/ /index.php$request_uri`
# always provides the desired behaviour.
index index.php index.html /index.php$request_uri;
# Rule borrowed from `.htaccess` to handle Microsoft DAV clients
location = / {
if ( $http_user_agent ~ ^DavClnt ) {
return 302 /remote.php/webdav/$is_args$args;
}
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# Make a regex exception for `/.well-known` so that clients can still
# access it despite the existence of the regex rule
# `location ~ /(\.|autotest|...)` which would otherwise handle requests
# for `/.well-known`.
location ^~ /.well-known {
# The rules in this block are an adaptation of the rules
# in `.htaccess` that concern `/.well-known`.
location = /.well-known/carddav { return 301 /remote.php/dav/; }
location = /.well-known/caldav { return 301 /remote.php/dav/; }
location /.well-known/acme-challenge { try_files $uri $uri/ =404; }
location /.well-known/pki-validation { try_files $uri $uri/ =404; }
# Let Nextcloud's API for `/.well-known` URIs handle all other
# requests by passing them to the front-end controller.
return 301 /index.php$request_uri;
}
# Rules borrowed from `.htaccess` to hide certain paths from clients
location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/) { return 404; }
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) { return 404; }
# Ensure this block, which passes PHP files to the PHP process, is above the blocks
# which handle static assets (as seen below). If this block is not declared first,
# then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
# to the URI, resulting in a HTTP 500 error response.
location ~ \.php(?:$|/) {
# Required for legacy support
rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+|.+\/richdocumentscode\/proxy) /index.php$request_uri;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
set $path_info $fastcgi_path_info;
try_files $fastcgi_script_name =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $path_info;
#fastcgi_param HTTPS on;
fastcgi_param modHeadersAvailable true; # Avoid sending the security headers twice
fastcgi_param front_controller_active true; # Enable pretty urls
fastcgi_pass php-handler;
fastcgi_intercept_errors on;
fastcgi_request_buffering off;
}
location ~ \.(?:css|js|svg|gif)$ {
try_files $uri /index.php$request_uri;
expires 6M; # Cache-Control policy borrowed from `.htaccess`
access_log off; # Optional: Don't log access to assets
}
location ~ \.woff2?$ {
try_files $uri /index.php$request_uri;
expires 7d; # Cache-Control policy borrowed from `.htaccess`
access_log off; # Optional: Don't log access to assets
}
# Rule borrowed from `.htaccess`
location /remote {
return 301 /remote.php$request_uri;
}
location / {
try_files $uri $uri/ /index.php$request_uri;
}
}
server {
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
ssl_ciphers TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256;
ssl_ecdh_curve secp384r1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
# HSTS settings
# WARNING: Only add the preload option once you read about
# the consequences in https://hstspreload.org/. This option
# will add the domain to a hardcoded list that is shipped
# in all major browsers and getting removed from this list
# could take several months.
#add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;" always;
# set max upload size
client_max_body_size 512M;
fastcgi_buffers 64 4K;
# Enable gzip but do not remove ETag headers
gzip on;
gzip_vary on;
gzip_comp_level 4;
gzip_min_length 256;
gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;
# Pagespeed is not supported by Nextcloud, so if your server is built
# with the `ngx_pagespeed` module, uncomment this line to disable it.
#pagespeed off;
# HTTP response headers borrowed from Nextcloud `.htaccess`
add_header Referrer-Policy "no-referrer" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Download-Options "noopen" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Permitted-Cross-Domain-Policies "none" always;
add_header X-Robots-Tag "noindex, nofollow" always;
add_header X-XSS-Protection "1; mode=block" always;
# Remove X-Powered-By, which is an information leak
fastcgi_hide_header X-Powered-By;
# Path to the root of your installation
root /var/www/html;
# Specify how to handle directories -- specifying `/index.php$request_uri`
# here as the fallback means that Nginx always exhibits the desired behaviour
# when a client requests a path that corresponds to a directory that exists
# on the server. In particular, if that directory contains an index.php file,
# that file is correctly served; if it doesn't, then the request is passed to
# the front-end controller. This consistent behaviour means that we don't need
# to specify custom rules for certain paths (e.g. images and other assets,
# `/updater`, `/ocm-provider`, `/ocs-provider`), and thus
# `try_files $uri $uri/ /index.php$request_uri`
# always provides the desired behaviour.
index index.php index.html /index.php$request_uri;
# Rule borrowed from `.htaccess` to handle Microsoft DAV clients
location = / {
if ( $http_user_agent ~ ^DavClnt ) {
return 302 /remote.php/webdav/$is_args$args;
}
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# Make a regex exception for `/.well-known` so that clients can still
# access it despite the existence of the regex rule
# `location ~ /(\.|autotest|...)` which would otherwise handle requests
# for `/.well-known`.
location ^~ /.well-known {
# The rules in this block are an adaptation of the rules
# in `.htaccess` that concern `/.well-known`.
location = /.well-known/carddav { return 301 /remote.php/dav/; }
location = /.well-known/caldav { return 301 /remote.php/dav/; }
location /.well-known/acme-challenge { try_files $uri $uri/ =404; }
location /.well-known/pki-validation { try_files $uri $uri/ =404; }
# Let Nextcloud's API for `/.well-known` URIs handle all other
# requests by passing them to the front-end controller.
return 301 /index.php$request_uri;
}
# Rules borrowed from `.htaccess` to hide certain paths from clients
location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/) { return 404; }
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) { return 404; }
# Ensure this block, which passes PHP files to the PHP process, is above the blocks
# which handle static assets (as seen below). If this block is not declared first,
# then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
# to the URI, resulting in a HTTP 500 error response.
location ~ \.php(?:$|/) {
# Required for legacy support
rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+|.+\/richdocumentscode\/proxy) /index.php$request_uri;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
set $path_info $fastcgi_path_info;
try_files $fastcgi_script_name =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $path_info;
#fastcgi_param HTTPS on;
fastcgi_param modHeadersAvailable true; # Avoid sending the security headers twice
fastcgi_param front_controller_active true; # Enable pretty urls
fastcgi_pass php-handler;
fastcgi_intercept_errors on;
fastcgi_request_buffering off;
}
location ~ \.(?:css|js|svg|gif)$ {
try_files $uri /index.php$request_uri;
expires 6M; # Cache-Control policy borrowed from `.htaccess`
access_log off; # Optional: Don't log access to assets
}
location ~ \.woff2?$ {
try_files $uri /index.php$request_uri;
expires 7d; # Cache-Control policy borrowed from `.htaccess`
access_log off; # Optional: Don't log access to assets
}
# Rule borrowed from `.htaccess`
location /remote {
return 301 /remote.php$request_uri;
}
location / {
try_files $uri $uri/ /index.php$request_uri;
}
}
}
Step 7: Copy/Create files at /var/lib/docker/volumes/nextcloud_sslcerts/_data
-
Create 3 files key.pem, cert.pem and dhparam.pem at /var/lib/docker/volumes/nextcloud_sslcerts/_data
-
Copy /home/ankit/nextcloud/certs/dhparam.pem β dhparam.pem
-
Copy /home/ankit/nextcloud/certs/mycloud.example.com.key β key.pem
-
Copy /home/ankit/nextcloud/certs/myCA.pem β cert.pem
Step 8: This is the second last step, trust me.
Please be patient as this task will consume some time. Take a break and enjoy a cup of coffee while waiting.
You can access nextcloud at https://raspberrypi.local:8443
sudo docker-compose up -d
Step 9: Compare with your config.php file add/remove as per your requirement
file path: /var/lib/docker/volumes/nextcloud_nextcloud/_data/config/config.php
<?php
$CONFIG = array (
'memcache.local' => '\\OC\\Memcache\\APCu',
'apps_paths' =>
array (
0 =>
array (
'path' => '/var/www/html/apps',
'url' => '/apps',
'writable' => false,
),
1 =>
array (
'path' => '/var/www/html/custom_apps',
'url' => '/custom_apps',
'writable' => true,
),
),
'htaccess.RewriteBase' => '/',
'memcache.distributed' => '\\OC\\Memcache\\Redis',
'memcache.locking' => '\\OC\\Memcache\\Redis',
'redis' =>
array (
'host' => 'cache',
'password' => '',
'port' => 6379,
),
'instanceid' => 'occbpdq8sz8g',
'passwordsalt' => 'fgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfg',
'secret' => 'fgfgfgfgfgfgfgfgfgfgfgfgfg',
'trusted_domains' =>
array (
0 => '192.168.1.111',
1 => 'mycloud.example.com',
),
'datadirectory' => '/extdata',
'dbtype' => 'pgsql',
'version' => '27.1.3.2',
'trusted_proxies' =>
array (
0 => '172.17.0.6',
1 => '172.17.0.9',
3 => '172.17.0.10',
4 => '172.17.0.11',
5 => '172.17.0.12',
6 => '172.17.0.13',
7 => '172.17.0.14',
8 => '172.28.0.1',
9 => '172.28.0.6',
),
'default_phone_region' => 'IN',
'auth.bruteforce.protection.enabled' => true,
'allow_local_remote_servers' => true,
'config_is_read_only' => false,
'overwrite.cli.url' => 'https://mycloud.example.com',
'dbname' => 'nextcloud',
'dbhost' => 'db',
'dbport' => '',
'dbtableprefix' => 'oc_',
'dbuser' => 'oc_dbuser',
'dbpassword' => 'fgfgfgfgfgfgfgfgfgf',
'installed' => true,
'preview_max_x' => '2048',
'preview_max_y' => '2048',
'jpeg_quality' => '60',
'enabledPreviewProviders' =>
array (
0 => 'OC\\Preview\\TXT',
1 => 'OC\\Preview\\MarkDown',
2 => 'OC\\Preview\\PDF',
3 => 'OC\\Preview\\MSOfficeDoc',
4 => 'OC\\Preview\\JPEG',
5 => 'OC\\Preview\\PNG',
6 => 'OC\\Preview\\GIF',
7 => 'OC\\Preview\\BMP',
8 => 'OC\\Preview\\XBitmap',
9 => 'OC\\Preview\\MP3',
10 => 'OC\\Preview\\HEIC',
11 => 'OC\\Preview\\Movie',
12 => 'OC\\Preview\\MKV',
13 => 'OC\\Preview\\MP4',
14 => 'OC\\Preview\\AVI',
),
'enable_previews' => true,
'preview_imaginary_url' => 'http://192.168.1.111:9000',
'maintenance' => false,
'knowledgebaseenabled' => false,
'mail_from_address' => 'support',
'mail_smtpmode' => 'smtp',
'mail_sendmailmode' => 'smtp',
'mail_domain' => 'example.com',
'mail_smtpauth' => 1,
'mail_smtpname' => 'support@example.com',
'mail_smtppassword' => 'fgfgfgfgfgfgfgf',
'mail_smtphost' => 'smtp.zoho.in',
'mail_smtpport' => '465',
'twofactor_enforced' => 'true',
'twofactor_enforced_groups' =>
array (
0 => 'admin',
),
'twofactor_enforced_excluded_groups' =>
array (
),
'loglevel' => 2,
);
Step 10 [Optional]: Adding Cloudflare Zero Trust Reverse Proxy
Coming soon