Guide: Setting Up Nextcloud on Raspberry Pi: SSL, Advanced App Support, High-Performance PostgreSQL, and Cloudflare Zero Trust Integration!


Unlock the Full Power of Nextcloud on Raspberry Pi: SSL, Advanced App Support, High-Performance PostgreSQL, and Cloudflare Zero Trust Integration!

Changelog:
08/24/2024 - Added Script for easier setup of SSL certificates, Nginx configuration, and Docker environment preparation.

03/20/2024 - Initial

Prerequisites:

  1. 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.
  1. 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.
  1. 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.
  1. Installing Docker Compose:
  • Follow the official Docker Compose installation guide to install Docker Compose on your Raspberry Pi OS.

    File Structure:

    /root/nextcloud/

    ├── Dockerfile.app
    ├── docker-compose.yml
    ├── db.env
    ├── .env
    ├── nginx.conf
    └── certs/
    ├── myCA.pem
    ├── mycloud.example.com.crt
    ├── mycloud.example.com.key
    └── dhparam.pem

Quick Setup Instructions

Follow these steps for a quick setup of your Nextcloud environment. This script will automatically generate necessary certificates, configure Nginx, create essential environment files, and set up required directories.

  1. Create the Docker Volume
    Run the following command to create the Docker volume named nextcloud_sslcerts:
sudo docker volume create nextcloud_sslcerts

This command creates a Docker volume where your SSL/TLS certificates will be stored.

  1. Save the Setup Script
    Save the following script as setup-nextcloud.sh:
#!/bin/bash

# Determine the home directory
HOME_DIR="$HOME"

# Define the Docker volume name (assumes 'nextcloud_sslcerts' volume exists)
VOLUME_NAME="nextcloud_sslcerts"

# Get the Docker volume path
DOCKER_VOLUME_PATH=$(docker volume inspect "$VOLUME_NAME" --format '{{ .Mountpoint }}')

# Check if the Docker volume path was obtained successfully
if [ -z "$DOCKER_VOLUME_PATH" ]; then
    echo "Error: Docker volume '$VOLUME_NAME' not found. Please create the volume before running this script."
    exit 1
fi

# Define directories and files
CERTS_DIR="$HOME_DIR/nextcloud/certs"
NGINX_CONF="$HOME_DIR/nextcloud/nginx.conf"
DOCKERFILE_APP="$HOME_DIR/nextcloud/Dockerfile.app"
DB_ENV="$HOME_DIR/nextcloud/db.env"
ENV_FILE="$HOME_DIR/nextcloud/.env"
DOCKER_VOLUME_CERTS_DIR="$DOCKER_VOLUME_PATH"

# Create directories if they do not exist
mkdir -p "$CERTS_DIR"
mkdir -p "$HOME_DIR/nextcloud"
mkdir -p "$DOCKER_VOLUME_CERTS_DIR"

# Generate SSL/TLS Certificates and Diffie-Hellman Parameters
cd "$CERTS_DIR" || exit

# Generate RSA private key if it doesn't already exist
if [ ! -f "mycloud.example.com.key" ]; then
    openssl genrsa -out mycloud.example.com.key 2048
    echo "Generated RSA private key: mycloud.example.com.key"
else
    echo "RSA private key already exists: mycloud.example.com.key"
fi

# Generate self-signed CA certificate if it doesn't already exist
if [ ! -f "myCA.pem" ]; then
    openssl req -x509 -new -nodes -key mycloud.example.com.key -sha256 -days 365 -out myCA.pem -subj "/C=US/ST=State/L=City/O=Organization/OU=Unit/CN=MyCA"
    echo "Generated self-signed CA certificate: myCA.pem"
else
    echo "Self-signed CA certificate already exists: myCA.pem"
fi

# Generate Certificate Signing Request if it doesn't already exist
if [ ! -f "mycloud.example.com.csr" ]; then
    openssl req -new -key mycloud.example.com.key -out mycloud.example.com.csr -subj "/C=US/ST=State/L=City/O=Organization/OU=Unit/CN=mycloud.example.com"
    echo "Generated Certificate Signing Request: mycloud.example.com.csr"
else
    echo "Certificate Signing Request already exists: mycloud.example.com.csr"
fi

# Sign the certificate with the CA certificate if it doesn't already exist
if [ ! -f "mycloud.example.com.crt" ]; then
    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
    echo "Signed certificate with CA: mycloud.example.com.crt"
else
    echo "Signed certificate already exists: mycloud.example.com.crt"
fi

# Generate Diffie-Hellman parameters if it doesn't already exist
if [ ! -f "dhparam.pem" ]; then
    openssl dhparam -out dhparam.pem 2048
    echo "Generated Diffie-Hellman parameters: dhparam.pem"
else
    echo "Diffie-Hellman parameters already exist: dhparam.pem"
fi

# Create nginx.conf file if it doesn't already exist
if [ ! -f "$NGINX_CONF" ]; then
    cat <<EOF > "$NGINX_CONF"
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;

    server_tokens   off;

    keepalive_timeout  65;

    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;

    upstream php-handler {
        server app:9000;
    }

    server {
        listen 80;

        client_max_body_size 512M;
        fastcgi_buffers 64 4K;

        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;

        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;

        fastcgi_hide_header X-Powered-By;

        root /var/www/html;

        index index.php index.html /index.php\$request_uri;

        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;
        }

        location ^~ /.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; }

            return 301 /index.php\$request_uri;
        }

        location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
        location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

        location ~ \.php(?:$|/) {
            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 modHeadersAvailable true;
            fastcgi_param front_controller_active true;
            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;
            access_log off;
        }

        location ~ \.woff2?$ {
            try_files \$uri /index.php\$request_uri;
            expires 7d;
            access_log off;
        }

        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_dhparam /etc/nginx/ssl/dhparam.pem;

        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-XSS-Protection "1; mode=block" always;

        client_max_body_size 512M;
        fastcgi_buffers 64 4K;

        root /var/www/html;

        index index.php index.html /index.php\$request_uri;

        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;
        }

        location ^~ /.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; }

            return 301 /index.php\$request_uri;
        }

        location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
        location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

        location ~ \.php(?:$|/) {
            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 modHeadersAvailable true;
            fastcgi_param front_controller_active true;
            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;
            access_log off;
        }

        location ~ \.woff2?$ {
            try_files \$uri /index.php\$request_uri;
            expires 7d;
            access_log off;
        }

        location /remote {
            return 301 /remote.php\$request_uri;
        }

        location / {
            try_files \$uri \$uri/ /index.php\$request_uri;
        }
    }
}
EOF
    echo "Created nginx configuration file: $NGINX_CONF"
else
    echo "nginx configuration file already exists: $NGINX_CONF"
fi

# Create Dockerfile.app file if it doesn't already exist
if [ ! -f "$DOCKERFILE_APP" ]; then
    cat <<EOF > "$DOCKERFILE_APP"
# Use the official Nextcloud image as a base image
FROM nextcloud:stable-fpm-alpine

# Install dependencies, including necessary development libraries
RUN apk update && \
    apk add --no-cache \
    build-base \
    cmake \
    git \
    imagemagick-dev \
    ffmpeg \
    nodejs \
    npm \
    util-linux \
    git \
    g++ \
    ghostscript \
    libx11-dev \
    sudo \
    nano \
    samba-client \
    bzip2-dev \
    zlib-dev \
    libjpeg-turbo-dev \
    libpng-dev \
    libwebp-dev \
    freetype-dev

# Install PHP extensions
RUN docker-php-ext-configure gd --with-jpeg --with-freetype --with-webp && \
    docker-php-ext-install gd mysqli pdo pdo_mysql opcache bz2

# Install imagick using pecl only if it's not already installed
RUN if ! pecl list | grep -q imagick; then \
        pecl install imagick && \
        docker-php-ext-enable imagick; \
    fi

# Set environment variables
ENV NODE_PATH /usr/bin/node
ENV NICE_CMD /usr/bin/nice

# Install dlib and pdlib
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 && \
    docker-php-ext-install pdlib

# Cleanup unnecessary packages
RUN apk del build-base cmake git && \
    rm -rf /var/cache/apk/*
EOF
    echo "Created Dockerfile.app: $DOCKERFILE_APP"
else
    echo "Dockerfile.app already exists: $DOCKERFILE_APP"
fi

# Create db.env file if it doesn't already exist
if [ ! -f "$DB_ENV" ]; then
    cat <<EOF > "$DB_ENV"
POSTGRES_PASSWORD=securepassword
POSTGRES_DB=nextcloud
POSTGRES_USER=nextcloud
EOF
    echo "Created db.env file: $DB_ENV"
else
    echo "db.env file already exists: $DB_ENV"
fi

# Create .env file if it doesn't already exist
if [ ! -f "$ENV_FILE" ]; then
    cat <<EOF > "$ENV_FILE"
POSTGRES_VERSION=14-alpine
REDIS_VERSION=6.2-alpine
NGINX_VERSION=alpine
REDIS_PORT=6379
NGINX_PORT=8443
NEXTCLOUD_EXTDATA=/mnt/ad/nextcloud
PHP_MEMORY_LIMIT=2048M
EOF
    echo "Created .env file: $ENV_FILE"
else
    echo ".env file already exists: $ENV_FILE"
fi

# Copy SSL/TLS certificate files if they do not already exist
if [ ! -f "$DOCKER_VOLUME_CERTS_DIR/key.pem" ]; then
    cp "$CERTS_DIR/mycloud.example.com.key" "$DOCKER_VOLUME_CERTS_DIR/key.pem"
    echo "Copied key.pem to Docker volume path: $DOCKER_VOLUME_CERTS_DIR/key.pem"
else
    echo "key.pem already exists in Docker volume path: $DOCKER_VOLUME_CERTS_DIR/key.pem"
fi

if [ ! -f "$DOCKER_VOLUME_CERTS_DIR/cert.pem" ]; then
    cp "$CERTS_DIR/myCA.pem" "$DOCKER_VOLUME_CERTS_DIR/cert.pem"
    echo "Copied cert.pem to Docker volume path: $DOCKER_VOLUME_CERTS_DIR/cert.pem"
else
    echo "cert.pem already exists in Docker volume path: $DOCKER_VOLUME_CERTS_DIR/cert.pem"
fi

if [ ! -f "$DOCKER_VOLUME_CERTS_DIR/dhparam.pem" ]; then
    cp "$CERTS_DIR/dhparam.pem" "$DOCKER_VOLUME_CERTS_DIR/dhparam.pem"
    echo "Copied dhparam.pem to Docker volume path: $DOCKER_VOLUME_CERTS_DIR/dhparam.pem"
else
    echo "dhparam.pem already exists in Docker volume path: $DOCKER_VOLUME_CERTS_DIR/dhparam.pem"
fi

  1. Make the Script Executable
    Run the following command to make the setup-nextcloud.sh script executable:
chmod +x /root/nextcloud/setup-nextcloud.sh
  1. Run the Script
    Execute the script to complete the setup:
/root/nextcloud/setup-nextcloud.sh

This script will automatically create the required directories, generate SSL certificates, configure Nginx, and prepare the environment for running Nextcloud.

Check the .env and db.env file and update NEXTCLOUD_EXTDATA variable with your external storage path if needed

  1. Create a docker-compose.yml File
    To simplify the management of your Nextcloud environment, create a docker-compose.yml file in the /root/nextcloud directory:
version: '3'

services:
  db:
    image: postgres:${POSTGRES_VERSION:-alpine}
    restart: always
    volumes:
      - db:/var/lib/postgresql/data:Z
    env_file:
      - db.env
    environment:
      - PUID=${PUID:-109}
      - PGID=${PGID:-65534}
    networks:
      - proxy-tier

  cache:
    image: redis:${REDIS_VERSION:-6.2-alpine}
    restart: always
    ports:
      - '${REDIS_PORT:-6379}:6379'
    command: redis-server --save 20 1
    volumes: 
      - cache:/data
    networks:
      - proxy-tier

  app:
    build:
      context: .
      dockerfile: ${APP_DOCKERFILE:-Dockerfile.app}
    container_name: ${APP_CONTAINER_NAME:-nextcloud}
    restart: always
    volumes:
      - nextcloud:/var/www/html:z
      - ${NEXTCLOUD_EXTDATA:-/mnt/ad/nextcloud}:/extdata
      - php-fpm:/usr/local/etc
      - type: tmpfs
        target: /tmp:exec
    environment:
      - POSTGRES_HOST=db
      - REDIS_HOST=cache
      - PHP_MEMORY_LIMIT=${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:
    build:
      context: .
      dockerfile: ${APP_DOCKERFILE:-Dockerfile.app}
    restart: always
    volumes:
      - nextcloud:/var/www/html:z
      - ${NEXTCLOUD_EXTDATA:-/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=${PHP_MEMORY_LIMIT:-2048M}
    networks:
      - proxy-tier

  imaginary:
    image: ${IMAGINARY_IMAGE:-ghcr.io/italypaleale/imaginary:master}
    container_name: imaginary
    restart: always
    ports:
      - '${IMAGINARY_PORT:-9000}:9000'
    command: -enable-url-source
    networks:
      - proxy-tier

  nginx-proxy:
    image: nginx:${NGINX_VERSION:-alpine}
    container_name: nginx-proxy
    restart: always
    ports:
      - "${NGINX_PORT:-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:

  • This docker-compose.yml file sets up services for Nextcloud, PostgreSQL, and Redis. It also uses Docker volumes to persist data and SSL certificates.
  1. Ignore Manual Setup Steps [1-7] Below if you have used the script above.
Manual Setup Steps [Hidden]

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' => 'sfsdfsfssfbbr',
  'passwordsalt' => 'sdfsdfssdfsdfsdf/sdfsfsdfsdfsdfsfsdf',
  'secret' => 'sdfsdfsdfsdfsdfsfsdfsdfsdf+sdfsdfsfsdfsdfsdfsdfsfd/u',
  'trusted_domains' => 
  array (
    0 => '192.168.0.111',
    1 => 'mycloud.example.com',
    2 => '127.0.0.1',
  ),
  'datadirectory' => '/extdata',
  'dbtype' => 'pgsql',
  'version' => '28.0.4.1',
  'trusted_proxies' => 
  array (
    0 => '172.18.0.1',
    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_example@gmail.com',
  'dbpassword' => 'sdfsfsdfsdfsdfsdfsdfsdfsdfsdfsdf',
  'installed' => true,
  'preview_max_x' => 1024,
  'preview_max_y' => 1024,
  'jpeg_quality' => 85,
  'preview_max_memory' => 2048,
  'enabledPreviewProviders' => 
  array (
    0 => 'OC\\Preview\\TXT',
    1 => 'OC\\Preview\\Krita',
    2 => 'OC\\Preview\\OpenDocument',
    3 => 'OC\\Preview\\JPEG',
    4 => 'OC\\Preview\\PNG',
    5 => 'OC\\Preview\\GIF',
    6 => 'OC\\Preview\\BMP',
    7 => 'OC\\Preview\\MP3',
    8 => 'OC\\Preview\\MarkDown',
    9 => 'OC\\Preview\\MP4',
    10 => 'OC\\Preview\\HEIC',
    11 => 'OC\\Preview\\Image',
    12 => 'OC\\Preview\\Movie',
  ),
  'preview_imaginary_url' => 'http://192.168.0.111:9000',
  'enable_previews' => true,
  'preview_ffmpeg_path' => '/usr/bin/ffmpeg',
  'preview_concurrency_all' => 8,
  'maintenance' => false,
  'maintenance_window_start' => 1,
  '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' => 'dfgdfgdfgdfgdfg',
  'mail_smtphost' => 'smtp.zoho.in',
  'mail_smtpport' => '465',
  'twofactor_enforced' => 'true',
  'twofactor_enforced_groups' => 
  array (
    0 => 'admin',
  ),
  'twofactor_enforced_excluded_groups' => 
  array (
  ),
  'loglevel' => 2,
  'theme' => '',
  'defaultapp' => 'files,photos',
  'app_install_overwrite' => 
  array (
    0 => 'facerecognition',
  ),
  'data-fingerprint' => '3715582310f7720e5c45650636e297d',
  'memories.db.triggers.fcu' => true,
  'memories.exiftool' => '/var/www/html/custom_apps/memories/bin-ext/exiftool-aarch64-musl',
  'memories.vod.path' => '/var/www/html/custom_apps/memories/bin-ext/go-vod-aarch64',
  'memories.vod.ffmpeg' => '/usr/bin/ffmpeg',
  'memories.vod.ffprobe' => '/usr/bin/ffprobe',
);

Step 10 [Optional]: Adding Cloudflare Zero Trust Reverse Proxy

Coming soon

Step 11 [Optional]: Install Nextcloud Memories App,

You should try this app

Download the Memories App
Visit the Nextcloud app store or GitHub repository to download the latest version of the Nextcloud Memories app. You can find it at Nextcloud Apps.

Extract the App Files
Extract the downloaded .tar.gz or .zip file to the /mnt/toshiba/docker/volumes/nextcloud_nextcloud/_data/custom_apps directory on your server. You can use the following command for extraction:

tar -xzvf /path/to/downloaded/memories-app.tar.gz -C /mnt/toshiba/docker/volumes/nextcloud_nextcloud/_data/custom_apps

Enable the App
Run the following command to enable the app using Docker:

docker exec -it -u www-data nextcloud_cron_1 /bin/sh -c "php occ app:enable memories"

Download the mobile app:

Troubleshooting:

If generating Diffie-Hellman parameters takes too much time, you can modify the script to use a shorter key size. Edit the script by changing the Diffie-Hellman parameters generation command as follows:

openssl dhparam -out dhparam.pem 512
1 Like

First and foremost, @Ankit_Das this tutorial is awesome! Lots of details. Thank you!!

I’m trying to run nextcloud on a Raspberry Pi 5 8GB with Raspberry OS.

Now, I’m facing a noob issue here. After I run docker compose up -d from /home/emburaman/Docker/nextcloud/docker-compose.yml I get the below error:

[+] Running 1/2
[+] Running 2/5cloud_proxy-tier  Created                                                                                                                                                                                                       0.1s
 ✔ Network nextcloud_proxy-tier  Created                                                                                                                                                                                                       0.1s
[+] Running 5/5cloud_default     Created                                                                                                                                                                                                       0.2s
[+] Running 6/8cloud_proxy-tier  Created                                                                                                                                                                                                       0.1s
 ✔ Network nextcloud_proxy-tier  Created                                                                                                                                                                                                       0.1s
 ✔ Network nextcloud_default     Created                                                                                                                                                                                                       0.2s
 ✔ Container nextcloud-db-1      Started                                                                                                                                                                                                       1.4s
 ✔ Container imaginary           Started                                                                                                                                                                                                       1.4s
 ✔ Container nextcloud-cache-1   Started                                                                                                                                                                                                       1.4s
 ⠦ Container nextcloud-cron-1    Starting                                                                                                                                                                                                      1.5s
 ⠦ Container nextcloud           Starting                                                                                                                                                                                                      1.5s
 ✔ Container nginx-proxy         Created                                                                                                                                                                                                       0.1s
Error response from daemon: error gathering device information while adding custom device "/dev/video10": no such file or directory
emburaman@emburaman:~/Docker/nextcloud $

Both nextcloud-cron-1 and nextcloud containers won’t start due to the error regarding /dev/video10.

The only way I can make it work is if I comment the /dev/video{n} from the docker-compose.yml file, which I believe is not ideal.

I’d appreciate any help and guidance you could provide… Thanks a lot.

@emburaman Can you install ‘sudo apt-get install v4l-utils’ and check if any hardware decoders are available? Use this command: ‘v4l2-ctl --list-devices’.

@Ankit_Das ,
Thanks for the quick response.

I did what you suggested and I got:

emburaman@emburaman:~/Docker/nextcloud $ v4l2-ctl --list-devices
pispbe (platform:1000880000.pisp_be):
        /dev/video20
        /dev/video21
        /dev/video22
        /dev/video23
        /dev/video24
        /dev/video25
        /dev/video26
        /dev/video27
        /dev/video28
        /dev/video29
        /dev/video30
        /dev/video31
        /dev/video32
        /dev/video33
        /dev/video34
        /dev/video35
        /dev/video36
        /dev/video37
        /dev/media0
        /dev/media1

rpivid (platform:rpivid):
        /dev/video19
        /dev/media2

Cannot open device /dev/video0, exiting.
emburaman@emburaman:~/Docker/nextcloud $

I don’t see video10, video11 or video12 on the list. So I changed the yml file to:

    devices:
      - /dev/video20:/dev/video20
      - /dev/video21:/dev/video21
      - /dev/video22:/dev/video22

And then Nextcloud container started with no error. But I honestly don’t know if my change will cause any unexpected/unwanted side effects. Will it?

Once again, thank you so much!!

In my case: ls /dev/video* output the available video devices are:

  • /dev/video19
  • /dev/video20
  • /dev/video21
  • /dev/video22
  • /dev/video23
  • /dev/video24
  • /dev/video25
  • /dev/video26
  • /dev/video27
  • /dev/video28
  • /dev/video29
  • /dev/video30
  • /dev/video31
  • /dev/video32
  • /dev/video33
  • /dev/video34
  • /dev/video35
  • /dev/video36
  • /dev/video37

None of the devices listed in your original configuration (/dev/video11, /dev/video12, and /dev/video10) exist on your system. Let’s update the docker-compose.yml file to use the existing devices. For demonstration, I’ll use /dev/video19, /dev/video20, and /dev/video21.

Here is the corrected docker-compose.yml file:

yaml

Copy code

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/video19:/dev/video19"
      - "/dev/video20:/dev/video20"
      - "/dev/video21:/dev/video21"
    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/video19:/dev/video19"
      - "/dev/video20:/dev/video20"
      - "/dev/video21:/dev/video21"
    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:

Validate and Restart Docker Compose:

  1. Validate Configuration:

sh

Copy code

docker-compose config
  1. Restart Services:

sh

Copy code

sudo docker-compose down
sudo docker-compose up -d

Verify Running Containers:

After starting the services, check that all containers are running correctly:

sh

Copy code

docker ps

This should list all running containers, and you should see nextcloud and nextcloud-cron running without errors.

1 Like

Did I miss something, or do Dockerfile.app and Dockefile.cron have the same content?

Need help!
Followed everything above, getting nginx:400

# 400 Bad Request

The plain HTTP request was sent to HTTPS port
---
nginx

You miss a redirect of http to https

Does that mean i have to setup redirect from http to https? if yes please point me to how i can do that.
if i try with https://mypi.local:8443 im getting following error

Internal Server Error

The server encountered an internal error and was unable to complete your request.
Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.
More details can be found in the server log.

got following the error in rpi with running sudo docker logs --tail 50 --follow --timestamps nextcloud

2024-08-08T15:13:05.385829665Z NOTICE: PHP message: {"reqId":"QtoIRYyvDsjQPEWx7bNg","level":3,"time":"2024-08-08T15:13:05+00:00","remoteAddr":"192.168.0.15","user":"--","app":"core","method":"GET","url":"/favicon.ico","message":"Exception thrown: Doctrine\\DBAL\\Exception","userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36","version":"27.1.3.2","exception":{"Exception":"Doctrine\\DBAL\\Exception","Message":"Failed to connect to the database: An exception occurred in the driver: SQLSTATE[08006] [7] connection to server at \"db\" (172.19.0.2), port 5432 failed: FATAL:  password authentication failed for user \"oc_dbuser\"","Code":7,"Trace":[{"file":"/var/www/html/3rdparty/doctrine/dbal/src/Connection.php","line":453,"function":"connect","class":"OC\\DB\\Connection","type":"->","args":[]},{"file":"/var/www/html/3rdparty/doctrine/dbal/src/Connection.php","line":411,"function":"getDatabasePlatformVersion","class":"Doctrine\\DBAL\\Connection","type":"->","args":[]},{"file":"/var/www/html/3rdparty/doctrine/dbal/src/Connection.php","line":318,"function":"detectDatabasePlatform","class":"Doctrine\\DBAL\\Connection","type":"->","args":[]},{"file":"/var/www/html/lib/private/DB/ConnectionAdapter.php","line":200,"function":"getDatabasePlatform","class":"Doctrine\\DBAL\\Connection","type":"->","args":[]},{"file":"/var/www/html/lib/private/DB/QueryBuilder/QueryBuilder.php","line":121,"function":"getDatabasePlatform","class":"OC\\DB\\ConnectionAdapter","type":"->","args":[]},{"file":"/var/www/html/lib/private/AppConfig.php","line":1239,"function":"expr","class":"OC\\DB\\QueryBuilder\\QueryBuilder","type":"->","args":[]},{"file":"/var/www/html/lib/private/AppConfig.php","line":264,"function":"loadConfig","class":"OC\\AppConfig","type":"->","args":[false]},{"file":"/var/www/html/lib/private/legacy/OC_App.php","line":736,"function":"searchValues","class":"OC\\AppConfig","type":"->","args":["installed_version"]},{"file":"/var/www/html/lib/private/TemplateLayout.php","line":237,"function":"getAppVersions","class":"OC_App","type":"::","args":[]},{"file":"/var/www/html/lib/private/legacy/OC_Template.php","line":145,"function":"__construct","class":"OC\\TemplateLayout","type":"->","args":["error",""]},{"file":"/var/www/html/lib/private/Template/Base.php","line":132,"function":"fetchPage","class":"OC_Template","type":"->","args":[]},{"file":"/var/www/html/lib/private/legacy/OC_Template.php","line":320,"function":"printPage","class":"OC\\Template\\Base","type":"->","args":[]},{"file":"/var/www/html/index.php","line":114,"function":"printExceptionErrorPage","class":"OC_Template","type":"::","args":[["Doctrine\\DBAL\\Exception"],500]}],"File":"/var/www/html/lib/private/DB/Connection.php","Line":163,"CustomMessage":"Exception thrown: Doctrine\\DBAL\\Exception"}}

And what if you try for example: http://mypi.local:8080 (or whatever port for http is setup on the NCP webserver itself)?

2024-08-08T15:13:05.385829665Z NOTICE: PHP message: {"reqId":"QtoIRYyvDsjQPEWx7bNg","level":3,"time":"2024-08-08T15:13:05+00:00","remoteAddr":"192.168.0.15","user":"--","app":"core","method":"GET","url":"/favicon.ico","message":"Exception thrown: Doctrine\\DBAL\\Exception","userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36","version":"27.1.3.2","exception":{"Exception":"Doctrine\\DBAL\\Exception","Message":"Failed to connect to the database: An exception occurred in the driver: SQLSTATE[08006] [7] connection to server at \"db\" (172.19.0.2), port 5432 failed: FATAL:  password authentication failed for user \"oc_dbuser\"","Code":7,"Trace":[{"file":"/var/www/html/3rdparty/doctrine/dbal/src/Connection.php","line":453,"function":"connect","class":"OC\\DB\\Connection","type":"->","args":[]},{"file":"/var/www/html/3rdparty/doctrine/dbal/src/Connection.php","line":411,"function":"getDatabasePlatformVersion","class":"Doctrine\\DBAL\\Connection","type":"->","args":[]},{"file":"/var/www/html/3rdparty/doctrine/dbal/src/Connection.php","line":318,"function":"detectDatabasePlatform","class":"Doctrine\\DBAL\\Connection","type":"->","args":[]},{"file":"/var/www/html/lib/private/DB/ConnectionAdapter.php","line":200,"function":"getDatabasePlatform","class":"Doctrine\\DBAL\\Connection","type":"->","args":[]},{"file":"/var/www/html/lib/private/DB/QueryBuilder/QueryBuilder.php","line":121,"function":"getDatabasePlatform","class":"OC\\DB\\ConnectionAdapter","type":"->","args":[]},{"file":"/var/www/html/lib/private/AppConfig.php","line":1239,"function":"expr","class":"OC\\DB\\QueryBuilder\\QueryBuilder","type":"->","args":[]},{"file":"/var/www/html/lib/private/AppConfig.php","line":264,"function":"loadConfig","class":"OC\\AppConfig","type":"->","args":[false]},{"file":"/var/www/html/lib/private/legacy/OC_App.php","line":736,"function":"searchValues","class":"OC\\AppConfig","type":"->","args":["installed_version"]},{"file":"/var/www/html/lib/private/TemplateLayout.php","line":237,"function":"getAppVersions","class":"OC_App","type":"::","args":[]},{"file":"/var/www/html/lib/private/legacy/OC_Template.php","line":145,"function":"__construct","class":"OC\\TemplateLayout","type":"->","args":["error",""]},{"file":"/var/www/html/lib/private/Template/Base.php","line":132,"function":"fetchPage","class":"OC_Template","type":"->","args":[]},{"file":"/var/www/html/lib/private/legacy/OC_Template.php","line":320,"function":"printPage","class":"OC\\Template\\Base","type":"->","args":[]},{"file":"/var/www/html/index.php","line":114,"function":"printExceptionErrorPage","class":"OC_Template","type":"::","args":[["Doctrine\\DBAL\\Exception"],500]}],"File":"/var/www/html/lib/private/DB/Connection.php","Line":163,"CustomMessage":"Exception thrown: Doctrine\\DBAL\\Exception"}}

This one actually holds a good clue:

"Message":"Failed to connect to the database: An exception occurred in the driver: SQLSTATE[08006] [7] connection to server at \"db\" (172.19.0.2), port 5432 failed: FATAL:  password authentication failed for user \"oc_dbuser\""

The password for the database user on the database itself, is not the same as in the config.php file.

Combined with the missing rewrite of the url to HTTPS when trying to hit the https port with HTTP (I actually believes that in this appliance, you should not try to connect to the 843 port because the appliance uses a reverse proxy, hence it is the reverse proxy that has the TLS certificates and it is proxying using HTTP downstream) and with the password missmatches, I think you have missed some steps.

Firstly, Thanks for the quick responses and sorry for my late replies!.

There should be something going wrong after step 8.
Previously i had copy pasted step 9 content into file path: /var/lib/docker/volumes/nextcloud_nextcloud/_data/config/config.php.
Now im seeing i should verify it and not to use it as it!.

So, I removed all docker volumes and started docker and found there is nothing in config.php (Also remembering it was empty for the first time installation as well)

I cannot help you further here. I do not use Docker myself for Nextcloud, so when it comes to the docker compose file - and where to fetch templates and provision commands - I cannot help you anymore. Sorry.

check the logs for the nextcloud container, the container should create the files on the first run

yes both are same, I have updated the guide.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.