feketerigo

技術の話だったりオタク話だったり日常話だったりできたらいいなぁ

CentOS7にNextCloud15を立てる

この記事はmohikanz Advent Calendar 2018 21日目の記事です。
20日目 | 22日目 >

CentOS7にNextCloudを立てる

目的

ローカル内で完結できる共有ストレージが欲しかった。
NASサーバーを買うのも検討したがPCが1セット余ってるので使いまわしできないかなということで、NextCloudを検討。

但書

・普段はMS系のSIやっててLinuxとかとはほぼ無縁の人間です。
たぶんあまりよろしくないことしてると思うけど許して。
・いわゆるやってみた系の記事です悪しからず。
・忙しくてあんま触れる時間なくて仕事合間にやってたので雑。

とりあえずNextCloudを建てる

■環境の用意
どんなものかを見たいだけなので、Hyper-VにCentOS7が入ったVMを立てました。
クライアントとVMがうまく疎通できなくてここですでに疲れた

基本は公式のドキュメント見つつ立てます。わかんないとことはググって解決。

SSHVMにつなぐ。
Windows 10 Fall Creator UpdateからSSHクライアントが内蔵されるようになったのでそれでつなぎます。
PowerShell立ち上げてsshコマンド打つだけです。便利な世の中だ。

ssh feke@10.0.0.2

ここからはめんどうなのでsuでrootユーザーになって作業します。

・EPELリポジトリを追加
NginxとPHPをインストールするのに必要なので最初に追加します。

[root@localhost feke]# yum install -y epel-release

・nginxをインストール
Apacheでも良いみたいですが、折角なので触ったことないnginxを入れてみます。
ついでに自動起動設定もしておきます。

[root@localhost feke]# yum install nginx

#自動起動設定
[root@localhost feke]# systemctl enable nginx
#nginx起動
[root@localhost feke]# systemctl start nginx

PHPを入れる
nginxからphpが使えるようにPHP-FPMをインストールする
そのためにremiリポジトリが必要なので追加

#remiリポジトリ
[root@localhost feke]# rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-7.rpm
#PHP-FPMをインストール
[root@localhost feke]# yum -y install yum-utils
[root@localhost feke]# yum-config-manager enable remi-php70
[root@localhost feke]# yum install --enablerepo=remi,remi-php70 php php-mysql php-pecl-zip php-xml php-mbstring php-gd php-fpm php-intl

PHPのConfigを弄る
vim使うマン。というかvimしか使い方が分からない(

[root@localhost feke]# vim /etc/php-fpm.d/www.conf

25行目辺りのuserとgroup[apache]から[nginx]に変更

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache user chosen to provide access to the same directories as httpd
user = apache
; RPM: Keep a group allowed to write in log dir.
group = apache

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache user chosen to provide access to the same directories as httpd
user = nginx
; RPM: Keep a group allowed to write in log dir.
group = nginx

ディレクトリの所有権を変更

[root@localhost feke]# chown -R root:nginx /var/lib/php/session/

・設定反映のためPHP再起動

#再起動
[root@localhost feke]# systemctl restart php-fpm
#自動起動設定
[root@localhost feke]# systemctl enable php-fpm

MariaDBのインストール
SQLLiteでも良いみたいだけどパフォーマンスに不安があるのでちゃんとDBを用意します。

#リポジトリ
[root@localhost feke]# curl -sS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | bash
#インストール
[root@localhost feke]# yum install MariaDB-server MariaDB-client

MariaDB起動
自動起動も設定

#起動
[root@localhost feke]# systemctl start mariadb
#自動起動設定
[root@localhost feke]# systemctl enable mariadb

セットアップの実行

[root@localhost feke]# mysql_secure_installation

流れに沿って設定を行っていく。
基本全部[Y]でよさそう。

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

#初回なので何も入力しない
Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

#ルートパスワード設定
Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB 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? [Y/n] 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? [Y/n] y
 ... Success!

By default, MariaDB 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? [Y/n] 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? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

一応ログインできるかチェックしておく。

[root@localhost feke]# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.3.11-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

NextCloudで使うデータベースとユーザーを作成。
ここで作成したテーブルとユーザーは後で使うのでメモっておく。

#データベース作成
[root@localhost feke]# mysql -uroot -p -e "CREATE DATABASE nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"
#ユーザー作成
[root@localhost feke]# mysql -uroot -p -e "GRANT ALL on nextcloud.* to nextcloud@localhost identified by 'Password'"
#権限の変更をデータベースに反映
[root@localhost feke]# mysql -uroot -p -e "FLUSH privileges"

・nginxの設定ファイル作成

[root@localhost feke]# vim /etc/nginx/conf.d/nextcloud.conf

設定内容はこんな感じ。
検証目的なのでHTTPSをOffにしてるけど、普通はOnにすべきだと思う。

upstream php {
    server 127.0.0.1:9000;
    }

server {
    server_name 10.0.0.2;

    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;

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

        location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location = /.well-known/carddav {
        return 301 $scheme://$host/remote.php/dav;
    }

    location = /.well-known/caldav {
        return 301 $scheme://$host/remote.php/dav;
    }

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

    location / {
        rewrite ^ /index.php$request_uri;
    }

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

    location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+)\.php(?:$|/) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        #HTTPSはOff
        fastcgi_param HTTPS off;
        #Avoid sending the security headers twice
        fastcgi_param modHeadersAvailable true;
        fastcgi_param front_controller_active true;
        fastcgi_pass php;

        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;
    }

    location ~ ^/(?:updater|ocs-provider)(?:$|/) {
        try_files $uri/ =404;
        index index.php;
    }

    # Adding the cache control header for js and css files
    # Make sure it is BELOW the PHP block
    location ~ \.(?:css|js|woff|svg|gif)$ {
        try_files $uri /index.php$request_uri;
        add_header Cache-Control "public, max-age=15778463";

        add_header X-Content-Type-Options nosniff;
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Robots-Tag none;
        add_header X-Download-Options noopen;
        add_header X-Permitted-Cross-Domain-Policies none;
        # Optional: Don’t log access to assets
        access_log off;
    }

    location ~ \.(?:png|html|ttf|ico|jpg|jpeg)$ {
        try_files $uri /index.php$request_uri;
        # Optional: Don’t log access to other assets
        access_log off;
    }
}

正しく設定できているかチェック

[root@localhost feke]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

サービス再起動

[root@localhost feke]# systemctl restart nginx

・NextCloud本体の準備
最初に調べてた頃バージョン14だったのにいつの間にか15になってた
せっかくなのでバージョン15を用意する

[root@localhost feke]# curl -O https://download.nextcloud.com/server/releases/nextcloud-15.0.0.zip

ダウンロードしたzipを/var/www/に解凍する。

[root@localhost feke]# unzip nextcloud-15.0.0.zip -d /var/www/

データディレクトリの作成

[root@localhost feke]# mkdir /var/www/nextcloud/data

nextcloudのディレクトリに権限付与

[root@localhost feke]# chown -R nginx: /var/www/nextcloud

 
これでNextCloudの利用準備完了。

ブラウザでアクセスしてみる。
この画面が出たらOK。
f:id:feketerigo725:20181220181301p:plain

管理者アカウントは任意のものを設定。
データフォルダーは
/var/www/nextcloud/data

データベースはMySQL/MariaDBを選択。
上のほうで作ったデータベースとユーザーを設定。

無事NextCloudが利用できるようになりました。
f:id:feketerigo725:20181220181319p:plain  
まだあまり使えてないのですが、ローカルフォルダと同期したりWebDAVも使えるし
プラグインでいろいろ拡張もできそうなので十分実用に耐えれそうな感じでよさそうでした。  
 

おまけ

NextCloud立てたもののなぜかアクセスできずこのあたり確認した。
・ポート開放の確認
いわゆる初歩ミス

[root@localhost feke]# firewall-cmd --info-zone public
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eth0
  sources:
  services: ssh dhcpv6-client
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

HTTP(80番ポート)を開ける。

[root@localhost feke]# firewall-cmd --zone=public --add-service=http --permanent
[root@localhost feke]# firewall-cmd --reload

httpのポート開いてるの確認。

[root@localhost feke]# firewall-cmd --info-zone public
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eth0
  sources:
  services: ssh dhcpv6-client http
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

 
 
SELinux
これが原因でずっとエラー画面が出てた。

[root@localhost feke]# vim /etc/selinux/config

SELinuxの無効化

SELINUX=enforcing

SELINUX=disabled

この2点設定したら無事アクセスできるようになりました。