LoginSignup
3
2

More than 1 year has passed since last update.

Nextcloud18.0.4+Nginx+MariaDB+RedisをCentOS8にセットアップ

Last updated at Posted at 2020-05-02

はじめに

Nextcloudは、自前のサーバを使って手軽にセキュアなファイル共有環境を実現できるオンラインストレージです。
先日よりいくつかのパターンの環境でのNextcloudインストール手順をご紹介しておりますが、今回は、OSとしてCentOS8を利用し、WebサーバとしてNginxを利用した場合のインストールする手順となります。

今回構築する環境

構成イメージ

こんな感じで、いたってシンプルです。インターネットに出ない環境で試してみます。
image.png

利用するOS、ミドルウェア

サーバOS(CentOS)

今回はCentOS8を利用します。VirtualBoxやVagrantなどで準備いただいても問題ありません。
ここで展開している手順の環境は以下のとおりです。

$ cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core)  
$ uname -a
Linux localhost.localdomain 4.18.0-147.el8.x86_64 #1 SMP Wed Dec 4 21:51:45 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

Nextcloud本体

もちろんこれがないとNextcloudが使えません。
Nextcloudのバージョンはいろいろありますが、2020/5/2時点の最新版である 18.0.4 を使います。

Webサーバ(Nginx)

NextcloudはWebベースで動作しますので、Webサーバが動作する環境が必要です。今回はNginxを使います。
ここで展開している手順でのNginxのバージョンは以下のとおりです。

$ nginx -v
nginx version: nginx/1.18.0

PHP

NextcloudはPHPで動作します。今回はWebサーバとしてNginxを使うので、PHP-FPMも利用します。
ここで展開している手順でのPHPのバージョンは以下のとおりです。

$ php -v
PHP 7.4.5 (cli) (built: Apr 14 2020 12:54:33) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.5, Copyright (c), by Zend Technologies
$ php-fpm -v
PHP 7.4.5 (fpm-fcgi) (built: Apr 14 2020 12:54:33)
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.5, Copyright (c), by Zend Technologies

データベース(MariaDB)

Nextcloudではデータベースを利用します。本格的な運用ではMariaDB/MySQLといったデータベースを利用することが推奨されます。今回はMariaDBを利用します。
ここで展開している手順でのMariaDBのバージョンは以下のとおりです。

$ mysql --version
mysql  Ver 15.1 Distrib 10.4.12-MariaDB, for Linux (x86_64) using readline 5.1

インメモリキャッシュサーバ(Redis)

Nextcloudではセッションを管理したりファイルのロック管理をしたりしておりますが、このデータ管理にインメモリキャッシュサーバを使うことによりパフォーマンス向上が期待できます。今回はRedisを利用します。
ここで展開している手順でのRedisのバージョンは以下のとおりです。

$ redis-server --version
Redis server v=5.0.3 sha=00000000:0 malloc=jemalloc-5.1.0 bits=64 build=8c0bf22bfba82c8f

構築手順

ほぼほぼNextcloud公式ドキュメントにのっている内容です。これに基づいて進めていきます。

①インストール作業に必要なパッケージをインストールします。

sudo dnf install dnf-utils unzip curl wget bash-completion -y

sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm -y

②システムを最新状態にアップデートします。

sudo dnf upgrade -y

③Webサーバ(Nginx)の最新版をインストールするため、公式リポジトリを定義します。

sudo bash -c "echo '[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key' >  /etc/yum.repos.d/nginx.repo"

④Webサーバ(Nginx)をインストールします。

sudo dnf --disablerepo=AppStream install nginx -y

⑤Nginxの追加設定ファイルを作成します。設定ファイルの内容は、Nextcloud公式サイト:Nginx configurationをもとに、HTTPアクセス向けに若干アレンジしております。

sudo vi /etc/nginx/conf.d/nextcloud.conf

※内容※

upstream php-handler {
    server unix:/var/run/php-fpm/php-fpm.sock;
}

server {
    listen 80;
    listen [::]:80;
    server_name (サーバのIPアドレス);

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    # add_header Strict-Transport-Security "max-age=15768000;
    # includeSubDomains; preload;";
    #
    # 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 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/html/nextcloud/;

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

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
    #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json
    # last;

    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;

    # Uncomment if your server is build with the ngx_pagespeed module
    # This module is currently not supported.
    #pagespeed off;

    location / {
        rewrite ^ /index.php$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;
        #fastcgi_param HTTPS on;
        #Avoid sending the security headers twice
        fastcgi_param modHeadersAvailable true;
        fastcgi_param front_controller_active true;
        fastcgi_pass php-handler;
        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|mp4)$ {
        try_files $uri /index.php$uri$is_args$args;
        add_header Cache-Control "public, max-age=15778463";
        # Add headers to serve security related headers (It is intended to
        # have those duplicated to the ones above)
        # Before enabling Strict-Transport-Security headers please read into
        # this topic first.
        # add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
        #
        # 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 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$uri$is_args$args;
        # Optional: Don't log access to other assets
        access_log off;
    }
}

⑥Nextcloudの動作に必要なPHPモジュールをインストールします。

sudo dnf install http://rpms.famillecollet.com/enterprise/remi-release-8.rpm -y

sudo dnf module install php:remi-7.4 -y

sudo dnf install php-gd php-mysqlnd php-process php-opcache php-pecl-apcu php-intl php-pecl-redis php-pecl-zip php-pear -y

⑦PHP-FPMの設定ファイルを修正します。修正箇所が若干多いので、修正ポイントのみ挙げておきます。

sudo cp -pi /etc/php-fpm.d/www.conf{,.orig}

sudo vi /etc/php-fpm.d/www.conf

修正箇所

$ diff /etc/php-fpm.d/www.conf{.orig,}
24c24
< user = apache
---
> user = nginx
26c26
< group = apache
---
> group = nginx
38c38
< listen = /run/php-fpm/www.sock
---
> listen = /var/run/php-fpm/php-fpm.sock
48,50c48,50
< ;listen.owner = nobody
< ;listen.group = nobody
< ;listen.mode = 0660
---
> listen.owner = nginx
> listen.group = nginx
> listen.mode = 0666
396,400c396,400
< ;env[HOSTNAME] = $HOSTNAME
< ;env[PATH] = /usr/local/bin:/usr/bin:/bin
< ;env[TMP] = /tmp
< ;env[TMPDIR] = /tmp
< ;env[TEMP] = /tmp
---
> env[HOSTNAME] = $HOSTNAME
> env[PATH] = /usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
> env[TMP] = /tmp
> env[TMPDIR] = /tmp
> env[TEMP] = /tmp

※env[PATH]には、以下のコマンドを実行した結果をそのままコピーペーストしてください。

$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin

⑧PHPセッションディレクトリのグループ情報を変更します。

sudo chown -R root:nginx /var/lib/php/session

⑨PHP-FPMとNginxをそれぞれ自動起動するように設定し、PHP-FPMとNginxを起動します。

sudo systemctl enable php-fpm

sudo systemctl start php-fpm

sudo systemctl enable nginx

sudo systemctl start nginx

⑩Nextcloudパッケージ本体とチェックサムファイル(Nextcloudパッケージ本体が正しくダウンロードされているかをチェックするためのファイル)をダウンロードします。

wget https://download.nextcloud.com/server/releases/nextcloud-18.0.4.tar.bz2

wget https://download.nextcloud.com/server/releases/nextcloud-18.0.4.tar.bz2.md5

⑪チェックサムファイルを利用してNextcloudパッケージが正しくダウンロードされているか確認します。

md5sum -c nextcloud-18.0.4.tar.bz2.md5 < nextcloud-18.0.4.tar.bz2

nextcloud-18.0.4.tar.bz2: OK または nextcloud-18.0.4.tar.bz2: 完了 と表示されれば OK です

⑫ダウンロードしたNextcloudパッケージを展開します。

tar xf nextcloud-18.0.4.tar.bz2

⑬展開したNextcloudをWebサーバのドキュメントルート(今回は /var/www/html )にコピーします。

sudo cp -R nextcloud/ /var/www/html/

⑭Nextcloudのデータディレクトリを作成します。

sudo mkdir /var/www/html/nextcloud/data

⑮Nextcloudのディレクトリ全体で読み書きができるように所有者情報を変更します。

sudo chown -R nginx:nginx /var/www/html/nextcloud

⑯PHP-FPMを再起動します。

sudo systemctl restart php-fpm

⑰データベース(MariaDB)をインストールします。

curl -sS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash

sudo dnf install MariaDB-server MariaDB-client -y

⑱MariaDBを自動起動するように設定し、MariaDBを起動します。

sudo systemctl enable mariadb.service

sudo systemctl start mariadb.service

⑲MariaDBの基本セットアップを行います。いくつか質問されますが New password:Re-enter new password:で rootユーザのパスワードを設定する以外は全て[Enter]キーを押しておきます。

sudo mysql_secure_installation

※実行例※

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
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

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

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] 
Enabled successfully!
Reloading privilege tables..
 ... Success!


You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] 
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!
#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
      5 # See the examples of server my.cnf files in /usr/share/mysql/


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] 
 ... 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] 
 ... 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] 
 - 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] 
 ... 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!

⑳MariaDBで扱う文字コードの設定をするため、MariaDB設定ファイルを編集します。

sudo cp -pi /etc/my.cnf.d/server.cnf{,.orig}

sudo vi /etc/my.cnf.d/server.cnf

※修正箇所※ [mariadb] 行の下の4行を追加します。

$ cat /etc/my.cnf.d/server.cnf
#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]

# this is only for the mysqld standalone daemon
[mysqld]

#
# * Galera-related settings
#
[galera]
# Mandatory settings
#wsrep_on=ON
#wsrep_provider=
#wsrep_cluster_address=
#binlog_format=row
#default_storage_engine=InnoDB
#innodb_autoinc_lock_mode=2
#
# Allow server to accept connections on all interfaces.
#
#bind-address=0.0.0.0
#
# Optional setting
#wsrep_slave_threads=1
#innodb_flush_log_at_trx_commit=0

# this is only for embedded server
[embedded]

# This group is only read by MariaDB servers, not by MySQL.
# If you use the same .cnf file for MySQL and MariaDB,
# you can put MariaDB-only options here
[mariadb]
character-set-server = utf8mb4

[client-mariadb]
default-character-set = utf8mb4

# This group is only read by MariaDB-10.4 servers.
# If you use the same .cnf file for MariaDB of different versions,
# use this group for options that older servers don't understand
[mariadb-10.4]

㉑設定を反映させるためにMariaDBを再起動します。

sudo systemctl restart mariadb.service

㉒MariaDBコンソールに接続し、文字コードの設定がutf8mb4になっていることを確認します。

sudo mysql -u root -p
show variables like "chara%";

※下のように表示されることを確認します。

+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

㉓MariaDBコンソールを使い、引き続きNextcloudで使用するユーザ、データベース、権限の追加をします。ここではそれぞれ以下のとおり設定します。
- ユーザ: nextcloud
- データベース名: nextcloud

CREATE DATABASE nextcloud DEFAULT CHARACTER SET utf8mb4;

CREATE USER 'nextcloud'@'localhost' IDENTIFIED BY '[nextcloudユーザに対して設定したいパスワード]';

GRANT ALL ON nextcloud.* TO "nextcloud"@"localhost";

SHOW GRANTS FOR 'nextcloud'@'localhost';

SHOW GRANTS~ の実行結果

+------------------------------------------------------------------------------------------------------------------+
| Grants for nextcloud@localhost                                                                                   |
+------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'nextcloud'@'localhost' IDENTIFIED BY PASSWORD 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' |
| GRANT ALL PRIVILEGES ON `nextcloud`.* TO 'nextcloud'@'localhost'                                                 |
+------------------------------------------------------------------------------------------------------------------+

㉔MariaDB コンソールを抜けます。

quit;

㉕このサーバーに外部から http でアクセスできるようにファイアウォール等の設定を行います。

sudo setenforce 0

sudo sed -i s/SELINUX=enforcing/SELINUX=disabled/ /etc/selinux/config

sudo firewall-cmd --permanent --zone public --add-service http

sudo firewall-cmd --reload

㉖ブラウザで http://(サーバのIPアドレス)/ にアクセスします。下のような画面が出ればOKです。この画面で「ストレージとデータベース」をクリックします。
image.png

㉗さらに「MySQL/MariaDB」をクリックします。
image.png

㉘Nextcloudの管理者向けのユーザー名、パスワードを決めて入力します。さらに、「データベースを設定してください」で「MySQL/MariaDB」をクリックするとデータベース関連の設定入力フォームが現れるので、以下のとおり設定値を入力します。

  • データベースのユーザ名: <MariaDBに作成したユーザ>
  • データベースのパスワード: <MariaDBに作成したユーザに対するパスワード>
  • データベース名: <MariaDBに作成したデータベース名>
  • データベースのホスト名: localhost:3306 image.png 終わったら「推奨アプリをインストール」のチェックを外し、「セットアップを完了します」をクリックします。

㉙データベースに必要なテーブルなどが自動作成され、このような画面が表示され、Nextcloudが動作します。
image.png
image.png

㉚データベースにテーブルができていることを確認します。これでデータベース周りの設定は終わりです。

sudo mysql -u nextcloud -p nextcloud
SHOW TABLES;

SHOW TABLES; の実行結果

+-----------------------------+
| Tables_in_nextcloud         |
+-----------------------------+
| oc_accounts                 |
| oc_activity                 |
| oc_activity_mq              |

~~~ (中略) ~~~

| oc_vcategory                |
| oc_vcategory_to_object      |
| oc_whats_new                |
+-----------------------------+

㉛MariaDB コンソールを抜けます。

quit;

㉜インメモリキャッシュサーバーのRedisをインストールします。

sudo dnf install redis -y

㉝Redisを自動起動するように設定し、Redisを起動します。

sudo systemctl enable redis.service

sudo systemctl start redis.service

㉞NextcloudでRedisを使うようにNexcloud設定ファイルを編集します。

sudo cp -pi /var/www/html/nextcloud/config/config.php{,.orig}

sudo vi /var/www/html/nextcloud/config/config.php

※修正箇所※ memcache.〜行と redis 行を追加します。

$ sudo cat /var/www/html/nextcloud/config/config.php  # 'memcache.〜'行と'redis'行を追加します。 
<?php
$CONFIG = array (
  'instanceid' => 'xxxxxxxxxxxx',
  'passwordsalt' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  'trusted_domains' => 
  array (
    0 => '<サーバのIPアドレス>',
  ),
  'datadirectory' => '/var/www/html/nextcloud/data',
  'dbtype' => 'mysql',
  'version' => '18.0.4.0',
  'overwrite.cli.url' => 'http://<サーバのIPアドレス>/nextcloud',
  'dbname' => 'nextcloud',
  'dbhost' => 'localhost:3306',
  'dbport' => '',
  'dbtableprefix' => 'oc_',
  'dbuser' => 'nextcloud',
  'dbpassword' => 'xxxxxxxx',
  'installed' => true,
  'memcache.distributed' => '\\OC\\Memcache\\Redis',
  'memcache.locking' => '\\OC\\Memcache\\Redis',
  'memcache.local' => '\\OC\\Memcache\\APCu',
  'redis' => 
  array (
    'host' => 'localhost',
    'port' => 6379,
  ),
);

㉟PHP-FPMを再起動します。

sudo systemctl restart php-fpm

㊱NextcloudでRedisが利用されているかどうかを確認するため、Redisのモニタリング機能を起動します。

redis-cli monitor

㊲この状態でNextcloudをログインするなど適当に触ってみます。この時に次のようにアクセスログが出力されればRedisが正しく設定されています。確認できたら Ctrl-C で中断します。

・・・
1588398915.377855 [0 127.0.0.1:35132] "SET" "0b69aefe7669c191b2be94ca6e74512f/SCSS-cached-708abb2df7e6ae0802cee0fbe308b3ea18.0.4.2/text/d233-708a-icons.css" "1588399215"
1588398915.378487 [0 127.0.0.1:35132] "GET" "0b69aefe7669c191b2be94ca6e74512f/SCSS-cached-708abb2df7e6ae0802cee0fbe308b3ea18.0.4.2/files_sharing/c5f2-708a-icons.css"
1588398915.378698 [0 127.0.0.1:35132] "EXISTS" "0b69aefe7669c191b2be94ca6e74512f/SCSS-cached-708abb2df7e6ae0802cee0fbe308b3ea18.0.4.2/files_sharing/c5f2-708a-icons.css"
・・・

あとがき

Nextcloudはサーバー1つあれば気軽に試せますので、使い勝手とかいろいろ試してみてください。
基本的なインストール方法はこの数回の記事である程度網羅できているかと思いますので、Web/APサーバとDB/セッションサーバの分離などいろいろ試してみてください。

更新履歴

  • 2019/5/2: 初版。
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2