Turenas core 12 Jail Nextcloud安装

(1)获取jail模板

#FreeNas的命令行中运行
iocage fetch 12.1-RELEASE -r

查看当前所有的jail

root@Xinew-FreeNas:~ # jls
   JID  IP Address      Hostname                      Path
     11                  TestJail1                     /mnt/iocage/jails/TestJail1/root
     12                  TestJail2                     /mnt/iocage/jails/TestJail2/root
#进入jail
jexec 2 csh

创建所需挂载文件夹

#在Jail的命令行中运行
mkdir /mnt/data
mkdir /var/db/mysql
mkdir -p /usr/local/www/nextcloud

创建数据集(非jail)

1.创建数据库数据集

在UserData存储池下,创建一个新数据集NextCloudDataBase,注意其中atime值设置为off,这与默认值不同。这样可防止在读取文件时产生日志流量,并显着提高性能,这对于我们的数据文件夹而言很好。

20201027204116473.md.png

2.创建nextcloud数据集

在UserData存储池下,创建一个新数据集nextcloud,配置和NextCloudDataBase数据集相比,只需打开ATime即可。

(2)初始化jail

# 开启SSH访问
# 先安装nano编辑器
$ pkg install nano

# 编辑系统配置文件,设置开机自启
$ nano /etc/rc.conf
#在最后加一行:sshd_enable=”YES”,按ctrl+O保存,ctrl+X退出文本编辑器

# 编辑ssh配置文件
$ nano /etc/ssh/sshd_config
# 找到并删除 Port 22 前面的#号;
# 删除 PermitRootLogin no 前面的#号,并将no修改为yes,修改后为PermitRootLogin yes;
# 删除 UseDNS yes 前面的#号。

# 启动ssh服务
$ service sshd start

# 设置root用户密码
$ passwd root

# 更改pkg安装源为中科大的源
$ nano /etc/pkg/FreeBSD.conf
url: "pkg+http://mirrors.ustc.edu.cn/freebsd-pkg/${ABI}/quarterly",
mirror_type: "srv",
signature_type: "none",
fingerprints: "/usr/share/keys/pkg",
enabled: yes

# 应用新的源
$ pkg update -f
Updating FreeBSD repository catalogue...
pkg: Repository FreeBSD has a wrong packagesite, need to re-create database
[nc] Fetching meta.txz: 100%    916 B   0.9kB/s    00:01  
[nc] Fetching packagesite.txz: 100%    6 MiB   1.1MB/s    00:06  
Processing entries:   0%
Newer FreeBSD version for package glew:
To ignore this error set IGNORE_OSVERSION=yes
- package: 1202000
- running kernel: 1201000
Ignore the mismatch and continue? [y/N]: y
Processing entries: 100%
FreeBSD repository update completed. 30174 packages processed.
All repositories are up to date.

# 更改系统语言,解决中文乱码问题
$ nano /.cshrc
# 在 setenv  BLOCKSIZE后
setenv LANG         zh_CN.UTF-8
setenv LC_CTYPE     zh_CN.UTF-8
setenv LC_ALL       zh_CN.UTF-8

(3)安装FNMPR环境

mysql
# 查看mysql-server最新版本
$ pkg search mysql
# 
$ pkg install mysql80-server-8.0.23
# 添加开机自动启动
$ nano /etc/rc.conf
mysql_enable="YES"
# 启动mysql服务
$ service mysql-server start
# 进入mysql
mysql -uroot -p
# 默认密码为空,直接按“ENTET”键进入
# 设置密码
SET PASSWORD FOR 'root'@'localhost' = '**';  //**为你设置的密码

nginx
$ pkg install nginx
$ nano /etc/rc.conf
nginx_enable="YES"

redis
$ pkg install redis
$ nano /etc/rc.conf
redis_enable="YES"

(4)设置数据库MYSQL(MARIADB)

在继续之前,我们需要修改MySQL配置以在正确的位置创建一个套接字。打开/usr/local/etc/mysql/my.cnf如下:

$ nano /usr/local/etc/mysql/my.cnf
# 找到
socket  = /var/run/mysql/mysql.sock
# 修改
socket  = /tmp/mysql.sock

# 在 [mysqld] 模块下面添加一句(mysql8.0需要)
default_authentication_plugin = mysql_native_password
# 针对mysql8.0需要更改认证
ALTER USER 'nxadmin'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Tlbj@VOo3JuO';
FLUSH PRIVILEGES;
# 查询
select user,host,plugin from mysql.user;

配置mysql

$ mysql_secure_installation --socket=/tmp/mysql.sock
mysql_secure_installation: [ERROR] unknown variable 'prompt=\u@\h [\d]>\_'.

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?

Press y|Y for Yes, any other key for No: y

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 0
Please set the password for root here.

New password: 

Re-enter new password: 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.

All done! 

(5)创建nextcloud数据库及用户

CREATE DATABASE nextcloud;
CREATE USER 'nxadmin'@'localhost' IDENTIFIED BY 'qazQAZqaz123';
GRANT ALL ON nextcloud.* TO 'nxadmin'@'localhost';
FLUSH PRIVILEGES;
exit

(6)安装并配置PHP

安装PHP7.4

$ pkg install php74 php74-bz2 php74-ctype php74-curl php74-dom php74-exif php74-fileinfo php74-filter php74-gd php74-iconv php74-intl php74-json php74-ldap php74-mbstring php74-opcache php74-openssl php74-pdo php74-pdo_mysql php74-pecl-APCu php74-pecl-imagick php74-pecl-redis php74-posix php74-session php74-simplexml php74-xml php74-xmlreader php74-xmlwriter php74-xsl php74-zip php74-zlib php74-bcmath php74-gmp php74-ftp

# 这个不用安装
php74-pecl-smbclient
# 可能用到的命令,一般不用执行
pkg clean # cleans /var/cache/pkg/
rm -rf /var/cache/pkg/* # just remove it all
pkg update -f # forces update of repository catalog
rm /var/db/pkg/repo-*.sqlite # removes all remote repository catalogs
pkg bootstrap -f # forces reinstall of pkg

添加启动项

$ nano /etc/rc.conf
sysrc php_fpm_enable=yes
$ service php-fpm start

配置PHP.INI

$ cd /usr/local/etc/
$ cp php.ini-production php.ini
$ nano /usr/local/etc/php.ini

在nano(Ctrl + W)中使用搜索命令取消注释,并确保以下参数具有这些值。删除在该行的开头的“;”即可删除注释:

cgi.fix_pathinfo=1
date.timezone ="Asia/Shanghai"
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=1
opcache.save_comments=1

这些值与上传文件有关,根据自己需要设定:

memory_limit = 1024M
post_max_size = 10240M
upload_max_filesize = 10240M
# 需要注释掉
;output_buffering = 4096

另外,配置文件/usr/local/etc/php-fpm.d/www.conf,取消下面项的注释

clear_env = no

重新启动php-fpm

$ service php-fpm restart

(7)设置Nginx和SSL证书

$ nano /usr/local/etc/nginx/nextcloud.conf
upstream php-handler {
    server 127.0.0.1:9000;
    #server unix:/var/run/php/php7.4-fpm.sock;
}

server {
    listen 80;
    listen [::]:80;
    server_name clouldtest.com;  # 域名

    # Enforce HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443      ssl http2;
    listen [::]:443 ssl http2;
    server_name clouldtest.com;  # 域名

    # Use Mozilla's guidelines for SSL/TLS settings
    # https://mozilla.github.io/server-side-tls/ssl-config-generator/
    ssl_certificate     /mnt/cr/server.crt;   # 证书地址
    ssl_certificate_key /mnt/cr/server.key;

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

    # Path to the root of your installation
    root /usr/local/www/nextcloud;

    # 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 following 6 rules are borrowed from `.htaccess`

        location = /.well-known/carddav     { return 301 /remote.php/dav/; }
        location = /.well-known/caldav      { return 301 /remote.php/dav/; }
        # Anything else is dynamically handled by Nextcloud
        location ^~ /.well-known            { return 301 /index.php$uri; }

        try_files $uri $uri/ =404;
    }

    # 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(?:$|/) {
        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
    }

    location / {
        try_files $uri $uri/ /index.php$request_uri;
    }
}
# 没有https,使用http这样写,其他与上面一样,不推荐
server {
    listen 80;
    server_name _;
    ...
     #fastcgi_param HTTPS on; 

然后在同目录下的nginx.conf中包含该文件

$ nano /usr/local/etc/nginx/nginx.conf
....
http {
    include       nextcloud.conf;   # 这里
    include       mime.types;
    default_type  application/octet-stream;
....

保存,并重启Nginx

$ service nginx restart

(8)复制nextcloud文件到www目录

$ mv nextcloud-21.0.0/nextcloud/* /usr/local/www/nextcloud/
$ chmod -R www:www /usr/local/www/nextcloud

(9)设置NextCloud

image-20210309094229575.md.png

localhost:/tmp/mysql.sock
# 如果遇到这个错误:
# Error while trying to create admin user: Failed to connect to the database: An exception occurred in the driver: SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client
# MySQL 8默认使用了新的密码验证插件:caching_sha2_password ,而有些 PHP 版本不支持这个问题造成的
# 解决方法  修改登录用户的 plugin 为 mysql_native_password
mysql -uroot -p
use nextcloud;
ALTER USER 'nxadmin'@'localhost' IDENTIFIED WITH mysql_native_password BY '密码';
FLUSH PRIVILEGES;

# 确保新添加的用户可以正常使用,需要把配置文件修改了
$ nano /usr/local/etc/mysql/my.cnf
在 [mysqld] 模块下面添加一句
default_authentication_plugin = mysql_native_password

(9)配置缓存REDIS

将REDIS设置为本地监听。

$ nano /usr/local/etc/redis.conf
port 0
# 并删除“#”,来取消注释,并修改对应的值
unixsocket /var/run/redis/redis.sock
unixsocketperm 770
bind 127.0.0.1

重启redis

$ service redis restart

确认Redis配置正确

$ ls -al /var/run/redis
drwxr-xr-x   2 redis  redis   4  3月 17 14:53 .
drwxr-xr-x  12 root   wheel  25  3月 17 14:48 ..
-rw-r--r--   1 redis  redis   5  3月 17 14:53 redis.pid
srwxrwx---   1 redis  redis   0  3月 17 14:53 redis.sock

然后将redis应用到NextCloud上

su -m www -c 'php /usr/local/www/nextcloud/occ config:system:set redis host --value="/var/run/redis/redis.sock"'
su -m www -c 'php /usr/local/www/nextcloud/occ config:system:set redis port --value=0 --type=integer'
su -m www -c 'php /usr/local/www/nextcloud/occ config:system:set memcache.local --value="\OC\Memcache\APCu"'
su -m www -c 'php /usr/local/www/nextcloud/occ config:system:set memcache.locking --value="\OC\Memcache\Redis"'

这些命令将用户切换到用户“ www”,其中su标志-m使环境保持不变。 -c标志指定要在新用户外壳程序中运行的命令。 在这种情况下,它将运行程序“ occ”,并将一些配置选项作为参数传递。 有关更多信息,请参见su手册页。

将www用户添加到redis组以允许其访问redis:

$ pw usermod www -G redis

重启Nginx

$ service nginx restart

优化NextCloud

(1)配置Cron文件

先将环境编辑器更改为nano,然后配置“ www”用户的crontab,

$ setenv EDITOR nano
$ crontab -u www -e

写入以下内容来运行nextcloud cron脚本。

# minute (0-59),
# |     hour (0-23),
# |     |       day of the month (1-31),
# |     |       |       month of the year (1-12),
# |     |       |       |       day of the week (0-6 with 0=Sunday).
# |     |       |       |       |       commands
  */15      *       *       *       *       /usr/local/bin/php -f /usr/local/www/nextcloud/cron.php

然后在NextCloud中选择Cron作为后台任务

Last modification:November 5, 2022
如果觉得我的文章对你有用就点个赞吧ε≡٩(๑>₃<)۶ 无需登录