为了可以把手机文件,相册,自动同步到NAS里。就折腾了一下个人网盘,挑来挑去最终选择nextcloud,主要是因为这个支持挂载其他目录以及扫描本地文件的功能,以下为搭建流程记录。之所以选择nginxwebui是因为其有自动申请证书,及友好的nginx管理界面功能,以后可以方便的使用nginx添加内网代理,外网一个端口就可以方便的访问家里的各种系统,你懂的😁

一,部署docker+portainer+汉化(前面文章有,此处略)

二,部署mysql8.0+redis

1,部署mysql8

1.1,/mnt/docker/mysql8/conf.d文件夹下创建my.cnf文件
###### [mysql]配置模块 ######
[mysql]
# 设置MySQL客户端默认字符集
default-character-set=utf8mb4
socket=/var/lib/mysql/mysql.sock

###### [mysqld]配置模块 ######
[mysqld]
port=3306
user=mysql

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

# MySQL8 的密码认证插件
default_authentication_plugin=mysql_native_password

# 禁用符号链接以防止各种安全风险
symbolic-links=0

# 允许最大连接数
max_connections=1000

# 服务端使用的字符集默认为8比特编码的latin1字符集
character-set-server=utf8mb4

# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB

# 表名存储在磁盘是小写的,但是比较的时候是不区分大小写
lower_case_table_names=0
max_allowed_packet=16M 

# 设置时区
default-time_zone='+8:00'

# binlog 配置
log-bin = /logs/mysql-bin.log
expire-logs-days = 90
max-binlog-size = 500M

# server-id 配置
server-id = 1


###### [client]配置模块 ######
[client]
default-character-set=utf8mb4

1.2,新建mysql堆栈,填写如下内容
version: '3'
services: 
  mysql: 
    restart: always
    privileged: true
    image: mysql:8.0
    container_name: mysql8
    volumes: 
      - /mnt/docker/mysql8/data:/var/lib/mysql   #映射数据存储目录
      - /mnt/docker/mysql8/conf.d:/etc/mysql/conf.d  #映射配置文件目录
      - /mnt/docker/mysql8/logs:/logs  #映射日志目录
    command: 
      --character-set-server=utf8mb4
      --collation-server=utf8mb4_general_ci
      --explicit_defaults_for_timestamp=true
    environment: 
      MYSQL_ROOT_PASSWORD: "123456"
      MYSQL_INITDB_SKIP_TZINFO: "Asia/Shanghai"
    ports: 
      - 3306:3306
    network_mode: "bridge"
1.3,开启mysql远程访问

在protainer容器中找到mysql容器,进入docker容器命令行运行


mysql -uroot -p123456  

use mysql;


update user set host = '%' where user = 'root';

flush privileges;

alter user 'root'@'%' identified with mysql_native_password by '123456';

image-1671285757039

1.3,navicat测试连接(略)

2,部署redis

2.1 同样创建堆栈填入如下内容
version: "3"
services:
  plex:
    image: redis:6.2.6
    container_name: docker-redis
    ports:
      - 6379:6379
    environment:
      - TZ=Aisa/Shanghai
    volumes:
      - /mnt/docker/redis/redis.conf:/etc/redis/redis.conf:ro   # redis配置文件
      - /mnt/docker/redis/data:/data			# redis数据持久化存放位置
      - /mnt/docker/redis/logs:/logs			#日志
    command: ["redis-server","/etc/redis/redis.conf"]  	#启动命令
    restart: unless-stopped
2.2 redis配置文件,仅供参考
#开启远程可连接
#bind 127.0.0.1
#自定义密码
requirepass 12345678
#指定 Redis 监听端口(默认:6379)
port 6379
#客户端闲置指定时长后关闭连接(单位:秒。0:关闭该功能)
timeout 0
# 900s内如果至少一次写操作则执行bgsave进行RDB持久化操作
save 900 1
# 在300s内,如果至少有10个key进行了修改,则进行持久化操作
save 300 10
#在60s内,如果至少有10000个key进行了修改,则进行持久化操作
save 60 10000
#是否压缩数据存储(默认:yes。Redis采用LZ 压缩,如果为了节省 CPU 时间,可以关闭该选项,但会导致数据库文件变的巨大)
rdbcompression yes
#指定本地数据文件名(默认:dump.rdb)
dbfilename dump.rdb
#指定本地数据文件存放目录
dir /data
#指定日志文件位置(如果是相对路径,redis会将日志存放到指定的dir目录下)
logfile "redis.log"

三,部署nextcloud+nginxwebui

1,创建堆栈

version: '3'
services:
  nextcloud:
    image: nextcloud:fpm		# fpm镜像
    container_name: nextcloud
    restart: unless-stopped
    ports:
      - 9001:9000        # fastcgi 端口,由于本机9000端口被portainer占用,所以改为9001
    volumes:
      - /mnt/docker/nextcloud/html:/var/www/html	# nextcloud php项目目录
      - /mnt:/mnt
    environment:
      - LANG=en_US.UTF-8
  nginxWebUi-server:
    container_name: nginxwebui        # 指定容器的名称
    image: cym1102/nginxwebui:latest
    volumes:
      - /mnt/docker/nginxwebui:/home/nginxWebUI 
      - /mnt/docker/nextcloud/html:/var/www/html	#与nextcloud php项目目录指向同一个
    volumes_from:
            - nextcloud  
    environment:
      BOOT_OPTIONS: "--server.port=8082"	# nginxwebui启动web端口
    privileged: true
    network_mode: "host"		# 由于是nginx服务,需要共享主机所有端口,所以设置网络为host
    restart: unless-stopped    

2,nginxwebui配置+证书申请

启动完上述堆栈后,web进入nginxwebui配置界面:ip:8082,第一次进入会设置用户名+密码。根据自身需求添加证书申请,并开启自动续签,证书路径抄下来,在下面nginx配置中要用

3,添加nextcloud nginx配置

到nginxwebui绑定目录中添加配置文件:fastcgi_params(nginx代理php需要用到),再添加一个文件夹用于存放自定义配置:proxy。

因为我把/mnt目录通过samb加到自己电脑盘中,所以我是直接在windows中访问添加的
proxy文件夹中加入nextcloud.conf

upstream php-handler {
    server 127.0.0.1:9001;
    #server unix:/var/run/php/php7.4-fpm.sock;
}

# Set the `immutable` cache control options only for assets with a cache busting `v` argument
map $arg_v $asset_immutable {
    "" "";
    default "immutable";
}

server {
    # 因为是家里的nas没有80和443端口,所以此666端口为我外网访问时统一的端口
    listen 666 ssl http2;
    # 自动跳转https
    if ($scheme = http) {
      return 301 https://$server_name:666$request_uri;
    }
    # 访问域名
    server_name file.codey.fun;  
    #error_page 497 301 https://$server_name:666$request_uri;
    
    # Path to the root of your installation
    root /var/www/html;

    # ssl证书
    ssl_certificate nginxwebui中申请的证书存放位置;
    ssl_certificate_key nginxwebui中申请的证书存放位置;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # 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 and increase upload timeout:
    client_max_body_size 512M;
    client_body_timeout 300s;
    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/wasm 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;

    # The settings allows you to optimize the HTTP2 bandwitdth.
    # See https://blog.cloudflare.com/delivering-http-2-upload-speed-improvements/
    # for tunning hints
    client_body_buffer_size 512k;

    # 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                         "none"          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;

    # 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 /home/nginxWebUI/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;

        fastcgi_max_temp_file_size 0;
    }

    location ~ \.(?:css|js|svg|gif|png|jpg|ico|wasm|tflite|map)$ {
        try_files $uri /index.php$request_uri;
        add_header Cache-Control "public, max-age=15778463, $asset_immutable";
        access_log off;     # Optional: Don't log access to assets

        location ~ \.wasm$ {
            default_type application/wasm;
        }
    }

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

4,回到nginxwebui配置界面,使配置生效

添加http参数includ自己新建的proxy文件夹下所有的conf文件,使porxy文件夹下所有配置生效,以后有其他自定义配置都可以放在里面

然后到启用配置中 校验文件 无误后 替换文件 重新装载 这样前面配置的nextcloud.conf文件就生效了

最后用域名(file.codey.fun:666)访问nextcloud

四,最后安装并优化nextcloud

安装不用多讲,配置账号密码,使用mysql(mysql账号root密码123456,前面安装时的默认,可以自己在navicat连接后自行更换)

1,nextcloud使用redis加速

找到nextcloud php程序目录(前面docker安装时自己映射的目录,此处为:/mnt/docker/nextcloud/html)找到里面的config/config.php编辑,添加redis配置;

  'memcache.local' => '\\OC\\Memcache\\APCu',
  'memcache.distributed' => '\OC\Memcache\Redis',
  'memcache.locking' => '\OC\Memcache\Redis',
  'filelocking.enabled' => 'true',
  'redis' => [
    'host' => '127.0.0.1',
    'port' => 6379,
    'password' => '12345678',
  ],

2,nextcloud添加外部存储插件

应用中心 ctrl+f 搜索:External storage support,启用后到管理设置中就能看到外部存储的配置,可以添加多种外部存储模式

3,nextcloud cron定时任务优化

基本设置中推荐使用cron模式执行任务,宿主机nextcloud 绑定目录中新建cron.sh文件,不要放到html目录里面,html为程序运行目录不要放任何自己添加的东西进去

cron.sh内容

#!/bin/bash
docker exec nextcloud /bin/bash -c "su www-data -s /bin/bash -c  'php cron.php'"

添加完之后赋予执行权限:

chmod +x cron.sh

宿主机启用定时任务

crontab -e

最下面增加一行,5分钟执行一次

*/5 * * * *  /bin/sh /mnt/docker/nextcloud/cron.sh