- Настройка NextCloud + ONLYOFFICE на одном сервере с помощью Docker
- Шаг 1: контейнер nginx
- Шаг 2: сервис документов
- Шаг 3: NextCloud
- Шаг 4: соединение NextCloud и ONLYOFFICE
- Завершающий шаг: где искать редактор
- How to Install Nextcloud with Docker on Your Linux Server
- Prerequisites
- Deploying Nextcloud server with Docker in reverse proxy
- Step 1: Set up reverse proxy
- Step 2: Deploy Nextcloud
- 1. NCDatabase
- 2. NCFrontend
- Volumes
- Networks
- Finally, deploying Nextcloud
- Post deployment
Настройка NextCloud + ONLYOFFICE на одном сервере с помощью Docker
Сложно недооценивать пользу онлайновых пакетов офисных приложений наподобие Google Docs и облачных хранилищ в жизни технически ориентированных людей (tech-oriented people). Технологии получили настолько широкое распространение, что даже компания Microsoft, уже длительное время доминирующая на рынке офисных приложений, в последнее время сосредоточилась на разработке веб-приложения Office 365 и убеждении пользователей перейти на подписную модель использования собственных сервисов. Тех, кого интересует процесс установки и настройки собственного хранилища приглашаем под кат.
Некоторое время назад мы ознакомились с решениями для облачного хранения и пакетами офисных веб-приложений с открытым ресурсным кодом, которые достаточно легко могли бы быть внедрены для использования в микропредприятии. Основная мотивация хранения всей документации онлайн — это сведение объема бумажного документооборота к минимуму, и внедрение положительных бизнес-практик, не смотря на малый объем операций. Обратная сторона монеты в том, что аренда облачного сервера для предоставления данного сервиса менее безопасна, чем хранение непосредственно на территории предприятия, так как у вас нет никаких средств аудита физического доступа к вашему серверу или трафику. Следовательно, также требуется шифрование end-to-end и программное обеспечение с открытым ресурсным кодом.
Приняв во внимание всю доступную информацию о решениях с открытым ресурсным кодом, мы нашли два действующих проекта (с коммитами в git репозитории за прошедшие 12 месяцев), разработанных для облачного хранения: NextCloud и OwnCloud, и единственный активный пакет офисных приложений ONLYOFFICE. У обоих средств для облачного хранения функционал примерно одинаков, и решение выбрать NextCloud было основано на существовании доказательств, того, что оно может быть интегрировано с ONLYOFFICE для комфортного взаимодействия пользователя с ПО. Однако, когда мы начали развертывание сервисов, дефицит информации по интеграции вышеупомянутых сервисов стал очевидным. Мы нашли 3 обучающих видео о том, как произвести интеграцию:
- www.youtube.com/watch?v=GAd-x_sP6ng
- www.youtube.com/watch?v=ceOld6P16wI
- www.youtube.com/watch?v=DvTXyl-OOZA
Ни одно из трех видео не ответило на вопрос установки сервиса документов ONLYOFFICE на том же физическом сервере, что и NextCloud с общим nginx. Вместо этого, они использовали такие технологии разделения, как использование раздельных портов для api сервиса документов. Другим предложенным вариантом было развертывание отдельного сервера для сервиса документов с ручной настройкой конфигурации встроенного в сервис документов инстанса nginx для установки ключа доступа (предварительно известный ключ доступа, подтверждающий право доступа к облаку данных) и сертификатов TLS. Вышеописанные подходы были признаны не безопасными и не достаточно эффективными, поэтому мы произвели интеграцию NextCloud, ONLYOFFICE и общего nginx, который разделяет запросы по доменным именам, с помощью docker-compose. Здесь приведена пошаговая информация о том, как это сделать.
Шаг 1: контейнер nginx
Это очень простая установка, но этот шаг требует самого большого количества работы, для конфигурации обратного прокси сервера. Сначала мы создали конфигурацию docker-compose для образа nginx:stable.
Это создает контейнер с портами 80 и 443, открытыми для публичного доступа, делает мэппинг конфигурации на nginx/nginx-vhost.conf и определяет хранилище для сертификатов, сгенерированных как самоподписанные сертификаты или с использованием Сertbot от Let’s encrypt в /nginx/certificates. В этом месте должны находиться папки для office.yourdomain.com и cloud.yourdomain.com с файлами fullchain1.pem и privkey1.pem в каждой для цепочки сертификатов и частного ключа сервера соответственно. Вы можете прочитать больше о том, как сгенерировать самоподписанный сертификат здесь www.akadia.com/services/ssh_test_certificate.html (переименование .key и .crt в .pem работает без конвертации файловой структуры для nginx).
После этого мы определили файл vhost. Сначала мы определяем поведение порта 80 как простое перенаправление на https, т.к. мы не хотим разрешать никакой http трафик
Затем мы создали два виртуальных сервера на порту 443 для наших сервисов:
Шаг 2: сервис документов
Теперь нам нужно добавить контейнер сервиса документов в наш docker-compose.yml. Конфигурировать здесь особо нечего.
Но не забудьте связать контейнер nginx с сервисом документов:
Шаг 3: NextCloud
Сначала добавляем новые сервисы:
и добавляем ссылку на nginx:
Теперь пора загрузить контейнеры.
Через некоторое время, nginx начнет переадресовывать вас на внешний интерфейс NextCloud, который по умолчанию является станицей конфигурации. Вам необходимо будет ввести имя пользователя и пароль для вашего первого администрирующего пользователя и учетные данные базы данных, которые вы указали в docker-compose.yml После того, как настройка окончена, вы сможете залогиниться. В нашем случае ожидание заняло почти минуту и потребовало дополнительного обновления страницы входа, перед тем, как мы смогли зайти в облачный сервис.
Шаг 4: соединение NextCloud и ONLYOFFICE
На этом шаге вам будет необходимо установить приложение для NextCloud, которое подключает функционал ONLYOFFICE. Начнем с панели управления приложениями в верхнем правом углу меню. Найдите приложение ONLYOFFICE (в разделе “Офис и текст” (Office & text) или с использованием поиска), установите и активируйте его.
После этого направляйтесь в Установки (Settings) через меню в правом верхнем углу, и вы должны будете найти элемент ONLYOFFICE в левом меню. Зайдите в него. Вам будет необходимо прописать адреса, как указано ниже.
Первый адрес используется для ссылки на некоторые файлы js и css напрямую из запущенного в браузере приложения (это то, для чего нам необходимо открыть доступ к сервису ONLYOFFICE через nginx). Секретный ключ не используется, потому что мы доверяем слою изоляции Docker больше, чем постоянному ключу аутентификации. Третий адрес используется контейнером NextCloud для прямого подключения к ONLYOFFICE API, и он использует внутреннее имя хоста по умолчанию из Docker. Ну и последнее поле используется для того, чтобы ONLYOFFICE смог делать запросы обратно к NextCloud API, используя внешний IP-адрес или внутренний адрес Docker, если вы используете сети Docker, но в нашем случае это не используется. Удостоверьтесь, что настройки вашего фаервола позволяют данные виды взаимодействий.
После сохранения, NextCloud протестирует соединение и, если все верно, покажет вам настройки, связанные с интеграцией — например, какие типы файлов могут редактироваться данной интеграцией. Настройте так, как считаете нужным.
Завершающий шаг: где искать редактор
Если вы вернетесь в папки вашего облачного хранилища и нажмете на “+” для создания нового файла, то вам будет доступна новая опция создания документа, таблицы или презентации. С их помощью вы создадите и сразу сможете редактировать данные типы файлов, используя ONLYOFFICE.
Источник
How to Install Nextcloud with Docker on Your Linux Server
Nextcloud is the perfect solution for a self-hosted Google Drive or Dropbox alternative.
I am not going to tell you why you should use Nextcloud. Instead, I am going to show you how to install Nextcloud server with Docker containers.
The tutorial uses Ngnix reverse proxy set up so that you can deploy your Nextcloud instance with SSL. This way, your Nextcloud deployment URL will be using HTTPS and you’ll be transferring files securely.
Towards the end of the tutorial, I’ll share some tips for Linode cloud users for reducing the effort on Nextcloud deployment.
Prerequisites
Before moving forward, some things need to be taken care of. Here’s what you need:
- A Linux server either a physical one, a virtual machine or in a cloud server.
- Docker and Docker Compose installed on your Linux server. If you need help follow docker installation guide on Ubuntu and CentOS. Similarly, you can follow the docker-compose installation tutorials on Ubuntu and CentOS.
- Some knowledge of Docker and Docker Compose is good to have.
- A domain name. This deployment, like all the other ones from Linux Handbook, is done under an actual domain name with HTTPS.
- Some experience with shell and Linux commands since there’s a lot of movement in there.
- Access to an SMTP service like Sendgrid. You’ll need it for sending email notifications, password reset etc.
- Time and patience.
Deploying Nextcloud server with Docker in reverse proxy
Let’s see the steps one by one.
Step 1: Set up reverse proxy
With reverse proxy, you can deploy several web services on the same server. This is not optional because you need let’s Encrypt container for SSL.
There are two ways you can set the Ngnix reverse proxy..
If you’re not using Linode, please go through my article on how to set up nginx-reverse-proxy with Docker.
If you are using Linode, I recommend you use our reverse-proxy-jwilder StackScript to easily deploy your server with everything already set up for you.
The reverse proxy deployment should be done using a separate Compose file so that you can restart or update web-services without disturbing your reverse proxy setup.
I have already prepared the compose files in our public GitHub repository. Since this is not a detailed article about the reverse-proxy deployment, I shall not go into the Compose file details.
You can either use git , or wget to download the files. If using git , clone the whole repository:
Otherwise, just download the necessary files:
There are three files here:
- env.example: Rename it to .env and change the value of DEFAULT_EMAIL to your email
- max_upload_size.conf: This file makes sure that you can upload files as big as 1 GB in size (the default is 2 MB).
- docker-compose.yaml: Biggest of them all. Discussed in brief in the next paragraph.
Create a docker network named net . This is used in the docker-compose.yaml file.
The docker-compose file looks like this:
Finally, deploy the containers
On a successful deployment, you should get a 503 when trying to visit the IP address of the server that is hosting this reverse-proxy. That’s okay. You don’t have a web service running on it just yet.
Step 2: Deploy Nextcloud
There are two components here: one is the database, another is Nextcloud itself, or rather let’s call it the frontend.
For the backend database, any MySQL-based database will work. I’m going with MariaDB, especially the image tag (or version) 10.5.9.
For Nextcloud, I’ll use the version 21.0.0, this is the latest at the time of writing this article.
Therefore, the images used are
The skeleton files, i.e. the compose file and the env files are already uploaded to our public GitHub repository. You can either download that or rewrite them while reading the explanations.
I recommend you download the files, and then go through everything to understand what’s going on, there’s no need for you to rewrite everything from scratch.
You can either clone our whole GitHub repository, or just download the necessary files.
If you cloned the «tutorial-snippets» repository while deploying the reverse-proxy, just change your current directory to tutorial-snippets/Nextcloud .
The working git command is as follows:
Otherwise, use the following shell code to create a directory named «Nextcloud» and download the files in there.
Copy the env.example file to .env . You’ll be editing this file later for the environment variables. Keeping the original file is just for the sake of backup, nothing else.
Now, let me go through the services definitions:
1. NCDatabase
The NCDatabase service looks like this:
This is the database service, and as stated previously, it uses the mariadb:10.5.9 image as its blueprint.
For persistent storage, I’m using a volume named NCMariaDB , it is mounted at /var/lib/mysql , where MariaDB stores its data.
The environment variables are handled using a .env file, I’ll talk about that in a moment.
I like the on-failure restart policy, but you’re free to choose unless-stopped or always . You may want to read more on restart policy in Docker.
The common network is common between this and the frontend service, it is there to make sure communication is possible between these containers.
Environment Variables
This is a Docker-based deployment, you are bound to set up some environment variables. Now open this .env file in your favorite text editor and start changing the values as the following:
MYSQL_ROOT_PASSWORD or MYSQL_RANDOM_ROOT_PASSWORD : Either set MYSQL_RANDOM_ROOT_PASSWORD to 1 or set a strong root password for MariaDB. Use openssl to generate a random password.
MYSQL_DATABASE & MYSQL_USER : There are some defaults set, but you can change these if necessary. Set these to your preferred database name and user name respectively.
MYSQL_PASSWORD : Password for the user ( MYSQL_USER ) that will have access to the main MariaDB database ( MYSQL_DATABASE ).
MYSQL_HOST : This is the service name of the database container. If you’re not going to change the service name in the Compose File, leave this as it is.
2. NCFrontend
This is the Nextcloud frontend service. This service is as simple as the previous one. Take a look:
Image used is nextcloud:21.0.0 , as I previously said, is the latest version at the time of this writing.
To make sure you keep your data safe, and don’t lose it in an unfortunate event of a simple container restart, data must be persisted. Nextcloud saves its data/information in /var/www/html , so this location is made persistent using a volume named NCData .
The depends_on array is an interesting one. It makes sure that the values, i.e. the services mentioned in it are deployed first before the current one starts.
Here, I’m making sure that the database is starting before Nextcloud itself, to avoid any connection issues.
There are two networks. The first one is net , which was also part of the reverse-proxy deployment. This is necessary because the reverse-proxy needs to be able to communicate with the proxied services, i.e. Nextcloud. The common network is for the nextcloud and database containers to be able to communicate successfully.
Environment Variables
Open the .env file (the same one you used for MariaDB) in your favorite text editor and start changing the values as the following:
LETSENCRYPT_HOST , VIRTUAL_HOST & NEXTCLOUD_TRUSTED_DOMAINS : Set these to the domain/subdomain you want to host your Nextcloud instance on.
TRUSTED_PROXIES : The subnet of the network, shared by the reverse proxy and this frontend. You can get the subnet using the following command (make sure jq is installed)
OVERWRITEPROTOCOL : The overwriteprotocol parameter is used to set the protocol of the proxy. As we’re using HTTPS, set this to HTTPS.
SMTP_HOST & SMTP_PORT : The SMTP server address and the port it’ll be listening on, for SendGrid it is smtp.sendgrid.net and port 587 for automatic TLS.
SMTP_NAME & SMTP_PASSWORD : The username & password for authentication. For SendGrid the value of the username is very consistent. It is apikey . For the password, it’s going to be your API key.
MAIL_FROM_ADDRESS : The value of the From SMTP header. Set this to something like [email protected] .
NEXTCLOUD_ADMIN_USER & NEXTCLOUD_ADMIN_PASSWORD : Instead of using the web UI the first time to create the admin user, you can instead create that right at the deployment stage through these variables. Set these to your admin user’s username and password. If you left it, you’ll be prompted to create an account the first time you launch Nextcloud.
Volumes
I have two internal volumes defined in this network, NCMariaDB for MariaDB and NCData for Nextcloud. Whether to keep these internal or external is up to you.
Many will say it’s risky to keep these internal since you can easily make the mistake of using docker-compose down -v and remove the volumes along with the containers. At the same time, with external volumes, you can make the mistake of docker volume prune and delete all your data.
Decide which one is going to be safer for you. If you decide to make them external, open the Compose file and change the volumes definition to something like this:-
Afterward, create the volumes:
Networks
There’s not much here. You’ll notice there are two networks defined. One is for the frontend and reverse-proxy, and the other one is for the frontend and the backend to be able to communicate.
The database container and nextcloud frontend have a common network named «common», this is there for these two containers to be able to communicate with each other. You can make this internal, which will limit the database container from accessing the public internet, but I am not sure what advantage[s] you might get from this.
Still if you want to do this, it should look like this:
Finally, deploying Nextcloud
There’s nothing else left to do. Just run the following command
The necessary images are going to be pulled and then deployed.
Once deployed, there should be a total of four containers running on your server.
You may have more containers running as well if there were containers running previously. The bottom line is this Nextcloud deployment consists of four containers, the nginx container, the letsencrypt companion container, mariadb container and finally the actual nextcloud container.
Post deployment
Before wrapping this up, I wanted to mention one quick thing you may wanna know post deployment.
First open your browser and head over to the domain this Nextcloud instance is hosted on ( VIRTUAL_HOST ). You should see a screen similar to this, if you did not set the admin user using the compose file
Since the database environment variables are shared through the common .env file, you won’t see the more common web install UI that asks for the database information like hostname, port, database username password.
A similar checkbox can be seen there as well. I recommend you uncheck this box and install whichever apps you need later on from the app list.
For more post deployment tips, read this awesome article written by my colleague Avimanyu:
That’s it. I hope this detailed tutorial helps you with your Nextcloud server installation with Docker. If you have questions or suggestions, please let me know in the comment section and I’ll be glad to help you out.
Источник