Настройка memcached ubuntu nextcloud

Обновлено: 05.07.2024

Но, если вам хочется большей производительности, а также не хочется видеть предупреждение о текущей конфигурации, которое будет видно каждый раз при заходе в административную панель, то следующие советы для вас.

После внесения изменений не забываем перезапускать php-fpm. Или можете после применения всех изменений перезапустить его один раз.

Содержание:

Убираем первое предупреждение:

Ищем такие строки:

И раскомментируем их.

Или, если побыстрее

Не забываем перезапустить php-fpm

Готово. Идём дальше.

Убираем второе предупреждение

opcache.enable=1
opcache.enable_cli=1
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.memory_consumption=128
opcache.save_comments=1
opcache.revalidate_freq=1

Убираем третье предупреждение

Некоторые индексы базы данных не были преобразованы в тип big int


Так как преобразование таких индексов может занять продолжительное время, оно должно быть запущенно вручную. Чтобы выполнить преобразование, необходимо включить режим обслуживания и запустить в терминале команду «occ db:convert-filecache-bigint». Дополнительные сведения приведены на соответствующей странице документации.filecache.mtime
filecache.storage_mtime

Для того, чтобы не потерять данные, или чтобы не было ошибок на клиентах, или просто для спокойствия нервной системы введите Nextcloud в режим обслуживания.

В браузере вы можете увидеть, что система находится в режиме обслуживания. Теперь в консоли выполните следующее:

Затем выключите режим обслуживания.

Убираем предупреждение о php

Разрешённое максимальное значение использования памяти PHP ниже рекомендуемого значения в 512 МБ.

Ищем memory_limit и вводим, например, 512M вместо 128M. И перезапускаем php-fpm

или если хотим побыстрее

Убираем предупреждение о кешировании.

Не настроена система кеширования

Для увеличения производительности сервера, по возможности, настройте memcache. Более подробная информация доступна в документации

Поэтому прикручиваем систему кэширования, состоящую из локальной системы кэширования на основе APCu и системы распределённого кеширования Redis.

Ставим APCu

В файле php.ini включаем apcu

вставив в начало

Сохраняем файл и перезапускаем php-fpm.

Редактируем файл config/config.php в директории установки Nextсloud

Ставим Redis.

Проверяем, что он запустился

В тот же файл config/config.php

Сохраняем файл. Перезапускаем php-fpm, если вы это ещё не сделали и наслаждаемся ускоренной работе Nextcloud.

Убираем ошибку отсутствия индексов

В базе данных отсутствуют некоторые индексы.

Так как создание таких индексов может занять достаточно продолжительное время, оно должно быть запущено вручную. Для создания индексов необходимо запустить команду «occ db:add-missing-indices» во время работы сервера Nextcloud. При созданных индексах, как правило, запросы к базе данных выполняются значительно быстрее.

При успешном индексировании будет следующий текст:

Некоторые индексы базы данных не были преобразованы в тип big int.

Так как преобразование таких индексов может занять продолжительное время, оно должно быть запущенно вручную. Чтобы выполнить преобразование, необходимо включить режим обслуживания и запустить в терминале команду «occ db:convert-filecache-bigint». Дополнительные сведения приведены на соответствующей странице документации.

Вводим сервер в режим обслуживания и выполняем преобразование

И выводим из режима обслуживания

Убираем предупреждение о 4-х байтовых символах

MySQL используется в качестве базы данных, но не поддерживает 4-байтовые символы.

Чтобы иметь возможность обрабатывать 4-байтовые символы (например, смайлики) без проблем в именах файлов или комментариях, рекомендуется включить 4-байтовую поддержку в MySQL. Для получения более подробной информации обратитесь к документации.

Так как первоначально Nextcloud я ставил на базе MariaDB, то по ссылке выше для возможности обработки ошибки я не заметил продолжение про MariaDB, а сразу стал применять шаги для MySQL. Не надо так. Поэтому распишу по шагам, что и как надо делать.

P.S. Убедитесь, что MariaDB версии выше 10.2. У меня была версия 15.1

Убедитесь, что на вашем сервере MySQL установлены следующие параметры InnoDB в файле:

и если их нет, то вставьте в конец файла.

Перезапустите сервер MariaDB

Выясните был ли изменён формат файла на Barracuda

Таблицы должны быть перенесены в “barracuda” вручную, одна за другой. Однако команды SQL можно легко создавать:

После всего проделанного формат файла должен поменяться на Barracuda. Проверим.

Инструкции для MySQL

Вводим в режим обслуживания.

Должен быть такой результат

Отключаем режим обслуживания.

Режим шифрования

Задействован устаревший режим шифрования файлов на стороне сервера.

Рекомендуется отключить такое шифрование. Более подробные сведения содержатся в документации.

Как я понял, устаревший режим шифрования был введён в ранних версиях Nextcloud и впоследствии заменён на новый. Однако в хранилище могли остаться файлы со старым (legacy) типом шифрования.

В документации сказано, что найти эти файлы можно командой

или более полный вариант

Такие файлы я просто заменил копиями тех, у кого есть нужные заголовки. Так как таких файлов у меня просто не было.

После этого в файле config.php можно отключить поддержку устаревшего формата шифрования, удалив строку

или, выставив значение false вместо true

С самими файлами в хранилище ничего не произойдёт, они так же будут зашифрованы как и раньше. В данном случае, мы просто отключили поддержку старого режима шифрования.

Настройка обратного прокси для доступа

В файле nextcloud/config/config.php

Для этого добавьте в файл конфигурации nginx на стороне nextcloud следующее содержимое в секцию server

Веб-сервер не настроен должным образом для разрешения «/.well-known/caldav». .

Дополнительная информация может быть найдена в нашей документации

В конфиге nextcloud в статье есть строки с настройкой доступа к этому пути. Для удобства повторю тут

Новый dashboard

Следующая опция для тех, кто обновился до 20 версии и при заходе на главную облака видит новый dashboard вместо знакомого списка файлов.

Исправляется просто добавлением в файл config.php следующей строки

Модуль php-imagick и SVG

Модуль php-imagick в этом случае не поддерживает SVG.

Для лучшей совместимости рекомендуется установить его

Регион размещения сервера

Не указан регион размещения этого сервера Nextcloud, что требуется для возможности проверки номеров телефонов без указания кода страны.

Чтобы разрешить пользователям сервера указывать номера телефонов без указания кода страны, добавьте параметр «default_phone_region» с соответствующим кодом страны в соответствии с ISO 3166-1↗.

Открывает файл config.php, расположенный в директории Nextcloud по пути config/config.php и внизу вставляем строку

Не знаю для чего вообще понадилось разработчикам из Nextcloud вставлять в код такое требование (а это требование, потому что иначе бы не было предупреждения на странице проверки конфигурации), но пока обновляться до 21 версии не стоит. Хотя, возможно, это из-за многочисленных требований регуляторов многих стран, в государственных учреждениях которых используется Nextcloud. Всё может быть. Со временем такое категоричное непринятие 21 версии у меня пропадёт. 🙂

You can significantly improve your Nextcloud server performance with memory caching, where frequently-requested objects are stored in memory for faster retrieval. There are two types of caches to use: a PHP opcode cache, which is commonly called opcache, and data caching for your Web server. If you do not install and enable a local memcache you will see a warning on your Nextcloud admin page. A memcache is not required and you may safely ignore the warning if you prefer.

If you enable only a distributed cache in your config.php ( memcache.distributed ) and not a local cache ( memcache.local ) you will still see the cache warning.

A PHP opcache stores compiled PHP scripts so they don’t need to be re-compiled every time they are called. PHP bundles the Zend OPcache in core since version 5.5, so you don’t need to install an opcache manually.

Data caching is supplied by the user (APCu), Memcached or Redis.

    APCu, APCu 4.0.6 and up required.

A local cache for systems.

For local and distributed caching as well as transactional file locking.

For distributed caching.

Memcaches must be explicitly configured in Nextcloud by installing and enabling your desired cache, and then adding the appropriate entry to config.php (See Configuration Parameters for an overview of all possible config parameters).

You may use both a local and a distributed cache. Recommended caches are APCu and Redis. After installing and enabling your chosen memcache, verify that it is active by running PHP version and information .

If you run multiple web servers and enable a distributed cache in your config.php ( memcache.distributed ) or a file locking provider ( memcache.locking ) you need to make sure that they are referring to the very same memcache server and not to localhost or a unix socket.

APCu is a data cache, and it is available in most Linux distributions. On Red Hat/CentOS/Fedora systems install php-pecl-apcu . On Debian/Ubuntu/Mint systems install php-apcu .

After restarting your Web server, add this line to your config.php file:

Refresh your Nextcloud admin page, and the cache warning should disappear.

APCu is disabled by default on CLI which could cause issues with nextcloud’s cron jobs. Please make sure you set the apc.enable_cli to 1 on your php.ini config file or append --define apc.enable_cli=1 to the cron job call.

Redis

Redis is an excellent modern memcache to use for distributed caching, and as a key-value store for Transactional File Locking because it guarantees that cached objects are available for as long as they are needed.

The Redis PHP module must be version 2.2.6+. If you are running a Linux distribution that does not package the supported versions of this module, or does not package Redis at all, see Additional Redis installation help .

On Debian/Ubuntu/Mint install redis-server and php-redis . The installer will automatically launch redis-server and configure it to launch at startup.

On CentOS and Fedora install redis and php-pecl-redis . It will not start automatically, so you must use your service manager to start redis , and to launch it at boot as a daemon.

You can verify that the Redis daemon is running with ps ax :

Restart your Web server, add the appropriate entries to your config.php , and refresh your Nextcloud admin page. This example config.php configuration uses Redis for the distributed server cache:

For best performance, use Redis for file locking by adding this:

If you want to connect to Redis configured to listen on an Unix socket (which is recommended if Redis is running on the same system as Nextcloud) use this example config.php configuration:

Only “host” and “port” variables are required, the other ones are optional.

Update the redis configuration in /etc/redis/redis.conf accordingly: uncomment Unix socket options and ensure the “socket” and “port” settings match your Nextcloud configuration.

Be sure to set the right permissions on redis.sock so that your webserver can read and write to it. For this you typically have to add the webserver user to the redis group:

You might need to restart apache for the changes to take effect:

Redis is very configurable; consult the Redis documentation to learn more.

Using the Redis session handler: If you are using Redis for locking and/or caching, you may also wish to use Redis for session management. Redis can be used for centralized session management across multiple Nextcloud application servers, unlike the standard files handler. If you use the Redis handler, though, you MUST ensure that session locking is enabled. As of this writing, the Redis session handler does NOT enable session locking by default, which can lead to session corruption in some Nextcloud apps that make heavy use of session writes such as Talk. In addition, even when session locking is enabled, if the application fails to acquire a lock, the Redis session handler does not currently return an error. Adding the following settings in your php.ini file will prevent session corruption when using Redis as your session handler:

More information on configuration of phpredis session handler can be found on the PhpRedis GitHub page

Memcached

Memcached is a reliable oldtimer for shared caching on distributed servers, and performs well with Nextcloud with one exception: it is not suitable to use with Transactional File Locking because it does not store locks, and data can disappear from the cache at any time (Redis is the best memcache for this).

Be sure to install the memcached PHP module, and not memcache, as in the following examples. Nextcloud supports only the memcached PHP module.

Setting up Memcached is easy. On Debian/Ubuntu/Mint install memcached and php-memcached . The installer will automatically start memcached and configure it to launch at startup.

On Red Hat/CentOS/Fedora install memcached and php-pecl-memcached . It will not start automatically, so you must use your service manager to start memcached , and to launch it at boot as a daemon.

You can significantly improve your Nextcloud server performance with memory caching, where frequently-requested objects are stored in memory for faster retrieval. There are two types of caches to use: a PHP opcode cache, which is commonly called opcache, and data caching for your Web server. If you do not install and enable a local memcache you will see a warning on your Nextcloud admin page. A memcache is not required and you may safely ignore the warning if you prefer.

If you enable only a distributed cache in your config.php ( memcache.distributed ) and not a local cache ( memcache.local ) you will still see the cache warning.

A PHP opcache stores compiled PHP scripts so they don’t need to be re-compiled every time they are called. PHP bundles the Zend OPcache in core since version 5.5, so you don’t need to install an opcache manually.

Data caching is supplied by the user (APCu), Memcached or Redis.

    APCu, APCu 4.0.6 and up required.

A local cache for systems.

For local and distributed caching as well as transactional file locking.

For distributed caching.

Memcaches must be explicitly configured in Nextcloud by installing and enabling your desired cache, and then adding the appropriate entry to config.php (See Configuration Parameters for an overview of all possible config parameters).

You may use both a local and a distributed cache. Recommended caches are APCu and Redis. After installing and enabling your chosen memcache, verify that it is active by running PHP version and information .

If you run multiple web servers and enable a distributed cache in your config.php ( memcache.distributed ) or a file locking provider ( memcache.locking ) you need to make sure that they are referring to the very same memcache server and not to localhost or a unix socket.

APCu is a data cache, and it is available in most Linux distributions. On Red Hat/CentOS/Fedora systems install php-pecl-apcu . On Debian/Ubuntu/Mint systems install php-apcu .

After restarting your Web server, add this line to your config.php file:

Refresh your Nextcloud admin page, and the cache warning should disappear.

APCu is disabled by default on CLI which could cause issues with nextcloud’s cron jobs. Please make sure you set the apc.enable_cli to 1 on your php.ini config file or append --define apc.enable_cli=1 to the cron job call.

Redis

Redis is an excellent modern memcache to use for distributed caching, and as a key-value store for Transactional File Locking because it guarantees that cached objects are available for as long as they are needed.

The Redis PHP module must be version 2.2.6+. If you are running a Linux distribution that does not package the supported versions of this module, or does not package Redis at all, see Additional Redis installation help .

On Debian/Ubuntu/Mint install redis-server and php-redis . The installer will automatically launch redis-server and configure it to launch at startup.

On CentOS and Fedora install redis and php-pecl-redis . It will not start automatically, so you must use your service manager to start redis , and to launch it at boot as a daemon.

You can verify that the Redis daemon is running with ps ax :

Restart your Web server, add the appropriate entries to your config.php , and refresh your Nextcloud admin page. This example config.php configuration uses Redis for the distributed server cache:

For best performance, use Redis for file locking by adding this:

If you want to connect to Redis configured to listen on an Unix socket (which is recommended if Redis is running on the same system as Nextcloud) use this example config.php configuration:

Only “host” and “port” variables are required, the other ones are optional.

Update the redis configuration in /etc/redis/redis.conf accordingly: uncomment Unix socket options and ensure the “socket” and “port” settings match your Nextcloud configuration.

Be sure to set the right permissions on redis.sock so that your webserver can read and write to it. For this you typically have to add the webserver user to the redis group:

You might need to restart apache for the changes to take effect:

Redis is very configurable; consult the Redis documentation to learn more.

Using the Redis session handler: If you are using Redis for locking and/or caching, you may also wish to use Redis for session management. Redis can be used for centralized session management across multiple Nextcloud application servers, unlike the standard files handler. If you use the Redis handler, though, you MUST ensure that session locking is enabled. As of this writing, the Redis session handler does NOT enable session locking by default, which can lead to session corruption in some Nextcloud apps that make heavy use of session writes such as Talk. In addition, even when session locking is enabled, if the application fails to acquire a lock, the Redis session handler does not currently return an error. Adding the following settings in your php.ini file will prevent session corruption when using Redis as your session handler:

More information on configuration of phpredis session handler can be found on the PhpRedis GitHub page

Memcached

Memcached is a reliable oldtimer for shared caching on distributed servers, and performs well with Nextcloud with one exception: it is not suitable to use with Transactional File Locking because it does not store locks, and data can disappear from the cache at any time (Redis is the best memcache for this).

Be sure to install the memcached PHP module, and not memcache, as in the following examples. Nextcloud supports only the memcached PHP module.

Setting up Memcached is easy. On Debian/Ubuntu/Mint install memcached and php-memcached . The installer will automatically start memcached and configure it to launch at startup.

On Red Hat/CentOS/Fedora install memcached and php-pecl-memcached . It will not start automatically, so you must use your service manager to start memcached , and to launch it at boot as a daemon.

Прежде чем ставить Nextcloud по этой инструкции, вначале установите LEMP-стек. Если он не установлен, и вы хотите знать как это сделать, то проследуйте по ссылке.

Данная статья создана с небольшой переработкой из статьи про установку Nextcloud для Ubuntu 18

Шаг 1: Скачиваем Nextcloud


Опция -C указывает путь, куда распакуется Nextcloud. Для его работы понадобится изменить владельца файлов.

Шаг 2. Создаём базу данных для Nextcloud

Логинимся на сервер MariaDB нижеследующей командой. С тех пор как MariaDB стала использовать плагин unix_socket для аутентификации, необходимость вводить root пароль отпала. Просто запустим оболочку под sudo.

Запуститься оболочка MySQL сервера MariaDB. Начнём процесс установки.

Создадим базу данных для Nextcloud

Создадим пользователя, у которого будут права на эту базу и который будет ей управлять. Имя можно выбрать любое, главное запомнить его. Вместо your-password подставьте свой придуманный пароль.

Выдайте новому пользователю права на новую базу данных

Шаг 3. Создаём конфигурационный файл nginx для Nextcloud.

Создайте файл nexcloud.conf в директории /etc/nginx/conf.d/

Вставьте нижеследующий текст в новый файл. Жирным начертанием выделены строки на замену

Но если кратко, то рекомендую создать в папке nginx самоподписные сертификаты

Не забудьте перезапустить nginx

Шаг 4. Установка php-модулей.

Выполните нижеприведённую команду, чтобы установить требуемые или рекомендованные модули php для Nextcloud.

Финиш. Заключительные штрихи

Для большей безопасности поменяем папку с данными и не будем хранить их в корне веб-сервера. Расположим их, например, в
/usr/share/nginx/nextcloud-data, используя следующую команду

Сделаем владельцем этого каталога пользователя www-data

P.S. Если вы следовали советам статьи по установке LEMP, то удалите файл default.conf. Если его не удалить, то будет показываться окно приветственной страницы nginx.


Установка завершена. Как видно, заметных отличий от установки в 18 убунте нет. Но для быстрой установки, чтобы не путаться в версиях php-fpm я написал данную статью.


Nextcloud has become one of the most widely-used on-premises cloud solutions on the planet. There’s a reason for that. This cloud software is not only open source, but it’s also scalable, extendible, and reliable. But for larger companies, looking to get as much performance as possible, Nextcloud might need a bit of tweaking out of the box. Why? Because by default Nextcloud does not enable caching.

Why would you need caching? As you probably already know, caching increases performance by storing frequently-requested objects in memory. By doing this the retrieval of those objects is considerably faster. Since we’re talking about the cloud, you could have hundreds (even thousands) of users hitting that server simultaneously. Without caching enabled, that server is going to take a significant hit as each user retrieves objects.

Fortunately, with Nextcloud, enabling caching isn’t all that challenging. It’s not as simple as clicking a checkbox in the Settings, but you can add this feature without having to jump through too many hoops.

Let’s do just that. We’ll enable caching on Nextcloud 16, running on the Ubuntu Server 18.04 platform, to help make your Nextcloud server run like a champ.

What You’ll Need

Obviously, you’ll need a running instance of Ubuntu Server. I will also assume you’ve already installed Nextcloud. If not, check out “How to Install Nextcloud 16 on Ubuntu Server 18.04”. You will also need a user with sudo privileges. That’s it. You’re ready to tune Nextcloud.

Installing Redis

Before you can configure Nextcloud caching, you must first install a caching service. We’ll use the in-memory data structure store, Redis (as Redis is also open source, scalable, and integrates well with Nextcloud).

To install Redis, log into your Nextcloud server, open a terminal (if your server has a GUI), and issue the command:

Читайте также: