[How to] Install Nextcloud on a VM Ubuntu 20.04 virtualized with KVM in OMV

    • Offizieller Beitrag

    EDIT:

    This is nonsense. To install Nextcloud in OMV follow this guide. [How-To] Nextcloud with swag (Letsencrypt) using OMV and docker-compose

    I leave it posted in case some of what is here helps someone.



    TRANSLATED INTO ENGLISH WITH AN AUTOMATIC TRANSLATOR ... ORIGINAL GUIDE IN SPANISH IN THE FOLLOWING POST

    (TRADUCIDO AL INGLÉS CON TRADUCTOR AUTOMÁTICO ... GUIA ORIGINAL EN ESPAÑOL EN EL SIGUIENTE POST)



    0. INDEX


    1. INTRODUCTION.

    1.1 Hardware requirements

    1.2 Keyboard configuration in the VM

    1.3 Network configuration


    2. CREATION OF THE VIRTUAL MACHINE IN OPENMEDIAVAULT KVM

    2.1 Previous steps

    2.2 Creating the VM in the OMV GUI

    2.3 Viewers and VM startup


    3. INSTALLATION AND INITIAL CONFIGURATION OF UBUNTU 20.04 LTS

    3.1 Ubuntu Desktop 20.04 LTS

    3.2 Ubuntu Server 20.04 LTS

    3.3 Network configuration. Fixed IP.

    3.4 Complete installation of Ubuntu Desktop to Ubuntu Server

    3.5 Initial Ubuntu Server configuration. User, OpenSSH and Firewall

    3.5.1 User

    3.5.2 OpenSSH

    3.5.3 Firewall

    3.5.4 Set the host domain

    3.6 Disabling or uninstalling the graphical interface.

    3.6.1 Disable graphical interface in Ubuntu 20.04 LTS

    3.6.2 Uninstall graphical interface in Ubuntu 20.04 LTS


    4. BACKUP COPY, RESTORATION AND DUPLICATION OF VM.

    4.1 VM backup

    4.2 Restore VM backup

    4.3 VM duplication


    5. INSTALLATION OF NEXTCLOUD SERVER IN UBUNTU 20.04 LTS THROUGH SNAP

    5.1 Installing the Nextcloud Server snap on Ubuntu 20.04 LTS

    5.2 Initial configuration of the Nextcloud Server snap in Ubuntu 20.04 LTS

    5.3 Installation of Certificate for HTTPS secure browsing in Nextcloud snap.

    5.4 Manual replacement of self-signed certificate by Let's Encrypt certificate in Nextcloud snap.


    6. INSTALLATION AND MANUAL CONFIGURATION OF NEXTCLOUD SERVER IN UBUNTU 20.04 LTS. ADVANCED USERS.

    6.1 Apache and MySQL Installation

    6.2 Installing Nextcloud 22

    6.3 Apache configuration

    6.4 Starting Nextcloud



    1. INTRODUCTION.



    Nextcloud is an open source service that provides a private cloud hosted on our server, in the style of icloud or google drive, but with the documents under our absolute control on our server. It has countless plugins that expand its functionality. On its official page we find documentation for the user, see here, and for the administrator, see here.


    This guide explains the procedures in a way that a user new to Linux can understand. If you are an advanced user, you can skip many parts.


    The COMPLETE PROCESS is described starting from a conventional OPENMEDIAVAULT (OMV) installation to get Nextcloud in an Ubuntu VIRTUAL MACHINE (VM) within OMV through the KVM plug-in. The KVM plugin is integrated into the OMV GUI (thanks, ryecoaaron), it allows to virtualize an operating system in a simple way and there is support in this forum for its use. Ubuntu is one of the recommended operating systems to host Nextcloud in its official documentation, see here.


    The virtualization process in OMV is described using the KVM plug-in. It solves a possible keyboard mapping problem in languages other than English with some linux operating systems, this method can be improved, but it works.


    It describes how to install and configure Ubuntu with or without a graphical environment (Desktop or Server), and how to convert Desktop to Server and vice versa. You can also leave the graphical environment installed but disabled without consuming resources, recommended for non-advanced Linux users.


    Two methods of installing Nextcloud are described. By snap or by installing LAMP and Nextcloud on the system. There are several ways to do it, see here. Installation via snap is recommended for non-advanced linux users.


    It describes how to do the initial configuration of Nextcloud.


    It describes how to install a Lets Encrypt Certificate or a self-signed certificate if you do not have a domain (it is recommended to have one, it is cheap and easy to configure, but it is not essential).


    Depending on your installation choices, you will skip parts of the guide.



    1.1 Hardware requirements:



    CPU with virtualization capacity (check the characteristics on the manufacturer's website)

    CPU with at least two cores to install Ubuntu on the VM.

    RAM. At least 2GB to dedicate to the Ubuntu VM (plus what we need for the OMV system, it is advisable to have 4GB or more in the system)

    HDD. We recommend an SSD disk formatted in EXT4 and of the capacity that we want to have in Nextcloud. Disk formats that use "copy on write" are not virtual machine friendly, although you can always disable copy on write in that folder. If we need more space later, there are ways to expand it by adding another disk or replacing this one and moving the VM to the new disk (see point 4 of this guide).



    1.2 Difficulties with keyboard mapping in the VM:



    There are historical complications with keyboard mapping and graphical viewers in virtual machines (especially VNC viewers), and some apparently still persist. KVM configures the default keyboard mapping in English, if you use English keyboard you will not have these problems. In my case, with a Spanish keyboard, I have been able to configure it correctly in Ubuntu Server after several attempts. In other languages there are also complications.


    An easy way to overcome this difficulty is to install Ubuntu Desktop, and use Virt Viewer (Spice) to view the VM from a Windows PC. Ubuntu Desktop correctly configures everything automatically and it works. Then install Ubuntu Server on Ubuntu Desktop (very simple, a command on the command line). You can then choose to disable or uninstall the graphical interface to save resources and gain server security, or keep it active if you want.



    1.3 Network configuration in the VM:



    There are two network configuration options on the VM.


    The "default" network, the default configuration, explained in a simple way, is the equivalent of having an intermediate "virtual router" between our VM and the physical router (or the team that assigns IPs). This virtual router will assign IP addresses to the VM in a subnet within the main network of our intranet. That is, a subnet is created within our intranet.


    The network "bridge" is a Macvtap bridge, it is the equivalent of a "virtual switch". It is like having a switch that directs the host machine (OMV) and the guest machine (our VM) alike to the physical router of our intranet. Our router will assign an IP to OMV and another IP to the VM as if they were separate machines within the network.


    My recommendation if you have problems with this is to define the VM with the network "default" and then change it to "bridge". It is the method that has worked best for Ubuntu to recognize it correctly. Each one to follow their best path.



    (continue in the next post)

    • Offizieller Beitrag

    2. CREATION OF THE VM UBUNTU 20.04 LTS IN OPENMEDIAVAULT KVM.



    2.1 Previous steps



    Meet the hardware requirements, see point 1.1 of this guide.


    Install OMV, see here.


    Install "OMV-extras", see here.


    Activate the "KVM" plugin, see here.


    Download the installation ISO of your choice for Ubuntu Desktop or Ubuntu Server 20.04 LTS here.


    The disk that we are going to use for the VM must be mounted from the OMV GUI, see here.


    We create on our disk the folders to install the VM. If you are not familiar with linux you will prefer to do it with WinSCP (a graphical browser for windows, see here), from the command line we can do it with Putty (see here) or any other tool.


    We look for the folder where OMV has mounted our disk, this folder will be located inside /srv and we can find its name in the OMV GUI in "Storage - File system" opening the column "identified as" (to see this column open the drop-down of the title of any existing column and look for the option).


    Once inside this disk mount folder, we create the "kvm" folder. Inside "kvm" we create two other folders. The first folder will be "ISOS" and the second will be "pool". (The ISOS folder is the location where we will store the installation isos, and the pool folder will store the VMs generated by the KVM plugin).


    We give the corresponding permissions to the folders, in this case reading and writing to the root user. From WinSCP in properties we write "root" in the "owner" box and click on "r" and "w" for root, or on the command line from the folder where the disk is mounted by typing:

    sudo chown -R root /kvm/

    sudo chown 600 /kvm/

    Once the folders are created, we copy the Ubuntu ISO installation image previously downloaded into /kvm/ISOS/.


    We must tell the KVM plugin where we have created these folders. To do this, we go to the OMV GUI and click on "Services - KVM - Pools - +Add".


    In the dialog box we look for the path of the "ISOS" folder that we have created and select it, in my case it is:


    /srv/dev-disk-by-uuid-744d..../kvm/ISOS


    In the corresponding box we write the name "ISOS" and accept. We select the line that has appeared, and when it is highlighted in yellow, we activate the folder by clicking on the "Status - Start" menu.


    We repeat the process with the pool folder, we call it "pool", we accept and activate it in the same way.


    We click on the "ISOs" Menu and we verify that the Ubuntu installation ISO that we had previously copied in the previous point has appeared. If it does not appear there, it is because we have not copied the file to the folder or we have not activated it correctly.



    2.2 Creating the VM in the OMV GUI



    Once the folders of the previous point have been created and defined, now we create a network device so that the VM can use it, we go to the "Networks" menu, and in this case we use the existing "default" network, we select it (press the line and turn it yellow) and activate it by clicking on the "Status - Start" menu.


    Note: See the explanation of network "default" and network "bridge" in the introduction of this guide.


    Now we are going to define the characteristics of the virtual machine that we want to create. We go to the VMs tab and click on "+ Add". A dialog box will open for creating the VM. In the case at hand, we configure it by filling in the fields as follows:


    - Machine name: Whatever you want, I call it "nextcloud". This is NOT the name of the host that we are going to create, it is the name of the VM in the OMV GUI, the name of the host we will define within the VM during its installation. Attention: Do not use spaces in this name (if your version of the plugin is up to date it will not allow it).

    - OS: Linux

    - UEFI: According to your needs. I do not activate it.

    - CPU: Minimum 2 for Ubuntu to work. For Ubuntu Server the minimum is 1. I assign 4 (all I have), this can be modified later.

    - Memory: Minimum 2GB for Ubuntu to work. For Ubuntu Server the minimum is 1GB. I allocate 2GB, this can be modified later.

    - Volume: We select "Create new disk"

    - Pool: We select "pool"

    - Name: We leave it blank

    - Size: If we want to use the full disk, we mark its capacity. The VM file will grow as we use it.

    - Format: qcow2 (as is)

    - Bus: Virtio (as is)

    - CD: We select the Ubuntu installation ISO file in the drop-down list.

    - Model: virtio (as is)

    - Network: We select "Default". This can be changed later.


    Note: See network definition in the introduction of this guide.


    Note: If for some reason we need to have sound in the VM, it can be done by clicking the "advanced options" tab at the top left and then the audio tab within "Options". Other options will also appear in case someone has other advanced needs.


    Click on save and we have the virtual machine configured and ready to start.



    2.3 Viewers and VM startup



    Before starting the VM read this entire point.


    To turn on our VM we go to the OMV GUI, and in "Services - KVM - VMs" we select the VM "nextcloud-server" to turn it yellow, then we turn it on by clicking on "Status - Start". We go to the viewer that we have chosen and we can see Ubuntu starting on the screen.


    To view the VM there are several options, if your keyboard is English (you have root privileges ;) ) your possibilities are expanded.


    Option 1. Spice Visor.


    When we have started the VM, a port number will appear in the Spice port column. We need a viewer installed on our PC. The Virt Viewer (Spice) viewer for windows can be downloaded here. It has worked perfectly for me and it maps the keyboard without problems. If your PC is linux I don't know the options but there will be others. We start it and write the address:


    spice://[your OMV IP]:[port in the KVM GUI for Spice]


    Example: My access IP to OMV is 192: 168: 1: 87 and the port that I got in the KVM GUI for Spice is 5901, so in my case it would be:


    spice://192.168.1.87:5091


    Option 2. VNC Viewer


    When we have started the VM, a port number will appear in the column for VNC viewers. Real VNC or any other VNC viewer can be used. In the address we will write:


    [your OMV IP]:[port in OMV GUI for VNC]


    Note: This method doesn't work for me because VNC viewers have the most trouble with keyboard mapping. Some viewers map better than others but none are perfect, at least the ones I have tried. This nonsense renders the VM useless in many cases. If your keyboard is English you are in luck.


    Option 3. Console integrated in browser.


    You can open a tab directly in the browser, for this we click on "Console - Create consoles", we will see a Link under the column "noVNC URL" and another under the column "spice-html5 URL". If we click on either of the two, a tab will open in the display browser.


    Note: In my case I have the same problem with noVNC, incorrect keyboard mapping in many cases (if your keyboard is English you are in luck again). The second link (spice) gives me display problems depending on which PC I open it with, so I don't use it either, maybe it works better for you.


    In short, many options, each one using its best solution. Check which one works for you with your keyboard.


    (continue in the next post)

    • Offizieller Beitrag

    3. INSTALLATION AND INITIAL CONFIGURATION OF UBUNTU 20.04 LTS



    Choose Ubuntu Desktop or Ubuntu Server installation. See introduction and keyboard mapping problems. You can always turn a desktop into a server and vice versa later, here is how to do it. You can also choose Desktop if you are not an advanced Linux user and you prefer it. If you are going to install Ubuntu Server, go to point 3.2.



    3.1 Ubuntu Desktop 20.04 LTS



    In the viewer of our VM and with the Ubuntu welcome in front we select our language and click on install, we select our local keyboard, and in the "applications and other software" section we change the option to "Minimum installation", we accept the different options, We accept our location if it is correct or adjust it if necessary, enter a username and password and accept. By selecting the minimum installation we avoid the installation of many packages that we do not need.


    When the process is finished we restart. We log in again and update ubuntu from "software", clicking on "update", or we can open a terminal and type "sudo update" and then "sudo upgrade" (without quotes).


    Note: Ubuntu should have already recognized our network (we can check it in network settings, we should have an assigned IP) and we should already have the keyboard perfectly configured in our local language (we can check it by creating a blank file and typing special characters), yes everything is correct we can continue. In the case of the Spanish language everything works correctly, if in another language it is not correctly configured you will have to solve it before continuing, I cannot help you here.


    Go to 3.3



    3.2 Ubuntu Server 20.04 LTS



    We start the installation process. When the additional packages installation window appears, we DO NOT install nextcloud, we will install it later. If you can install OpenSSH during the process and you will already have a step forward, do not install any more options.


    We end the process and restart. We log in again and update ubuntu.

    sudo apt update

    sudo apt upgrade


    3.3 Network configuration. Fixed IP.



    Note: For operation without access from outside our network, the VM could live behind a NAT without further complications, it has access to the internet without problems. But in our case it will work as a server accessible from the outside and we need to send it information from the internet, the packets must be routed to the VM host in some way. The problem is that our router does not know where our server is, only the virtual KVM router (double NAT) does. We have two options, the first is to configure our physical router to redirect those packets to the KVM "virtual router", and it will forward them to the IP of the host nextcloud-server. To do this you have to configure a fixed route on the physical router. The second option is to create a "Bridge" (virtual switch), in this way the physical router will assign an IP directly to Nextcloud and it will be one more device on our main intranet, without intermediaries, the packets will arrive directly. This method seems simpler for day-to-day operation and is what we will do. We are going to change the "default" network from KVM (Virtual Router) to a "bridge" (Virtual Switch). I have tried to create the VM directly with a bridge and it has not worked for me, the adapter was not configured correctly and it gave me many problems that I do not know how to solve, that's why I do it like this. In your case maybe it works directly.


    We turn off the VM, we type "sudo shutdown" or we turn off Ubuntu in graphical mode if we have it.


    We go to the OMV GUI and check in "Services - KVM - VMs" that our "nextcloud" VM appears in the "shutoff" state in the corresponding column.


    In "Services - KVM - Networks" click on "+Add Macvtap bridge".


    A line called "bridge" will appear. We select it and activate it by clicking on "Status - Start".


    Click on "VMs", select the VM "nextcloud-server" and click on "Devices - Add network"


    In the dialog box and within the "Network" option we select "Bridge" and accept.


    Click on "Devices - Remove network", select the network "Default" and accept.


    We start the VM again by clicking on "Status - Start" and we go to our preferred viewer.


    Note: We should already have our server behind a (virtual) switch and our physical router should already see it and assign it an IP directly within our usual network as if it were just another computer. We can check it in the network settings.


    Now we can assign a fixed IP to the VM. We can do this from the physical router itself if it has this option through the MAC address of the Nextcloud host or from Ubuntu itself. We do it from Ubuntu below.


    If your Ubuntu is Desktop and you have a graphical interface, you can go directly to configuration and do it graphically, easier. In "configuration - network", press the wheel on "wiring", press "IPv4", press "manual", write the IP that interests us in "Address", in "Network mask" write "255.255.255.0" (without quotes), in "gateway" write the IP of our router, in DNS those of our internet provider or other generic ones, such as those of cloudflare 1.1.1.1,1.0.0.1 or whatever we want. Reboot and go to the next point (you can continue reading and experiment if you are not familiar with the command line, open a terminal and test).


    If your Ubuntu is Server you can do it from the command line by editing the configuration file. To check the initial value of the 00-installer-config.yaml file we type:


    cat /etc/netplan/00-installer-config.yaml


    The default NetPlan configuration will look like this:


    Code
    network:  
      ethernets:    
        enp0s3:      
          dhcp4: true  
      version: 2


    What it establishes is that the network adapter we are defining is enp0s3 and that it uses DHCP.


    Attention: be careful with indents, do not use TAB, yaml files will not work if they are not configured correctly. It is recommended to make a copy of the original before editing it.


    To edit the corresponding configuration file we type:


    sudo nano /etc/netplan/00-installer-config.yaml


    Inside the nano working window, the first thing to do is change the value "dhcp4: true" to "dhcp4: false" or "dhcp4: no". Then, we will write the network configuration values, which will be similar to these:


    Code
    network:
      ethernets: 
        enp0s3: 
          dhcp4: no 
          addresses: [192.168.1.200/24] 
          gateway4: 192.168.1.1 
          nameservers: 
             addresses: [1.1.1.1,1.0.0.1] 
      version: 2


    the lines that appear under "dhcp4: no" set the static values we need:


    addresses: [192.168.1.200/24]: It establishes that the IP address of the device will always be 192.168.1.200 in my case, you must choose the IP that interests you within your network. It also indicates that the netmask uses 24 bits (which is equivalent to 255.255.255.0). This value can also change depending on the characteristics of your network.

    gateway4: 192.168.1.1: Determines the gateway address for TCP/IPv4. In my case, the IP of my router, the most usual, if your case is different, adapt it to your needs.

    nameservers: Configure the Internet address (or addresses) where the DNS server that we will use to convert domain names into IP addresses is located. In this case we will use the cloudflare 1.1.1.1,1.0.0.1 server, put the ones you like the most, if there are several they can be separated with commas, as in this case.


    Once the changes in the file are completed, we will exit the editor saving changes. We press Ctrl + X, save changes and exit.


    We apply the changes of the configuration file by typing:


    sudo netplan apply


    We check the changes by consulting the current network configuration:


    ip addr


    and we can see that our IP is the one we have defined.



    3.4 Complete installation of Ubuntu Desktop to Ubuntu Server



    If you have installed Ubuntu Server directly, go to point 3.5.


    If you have installed Ubuntu Desktop you must complete your installation with the remaining Ubuntu Server packages. We install the Ubuntu Server package within our version of Ubuntu Desktop, opening a terminal using the keyboard shortcut Ctrl + Alt + T or clicking on the terminal icon and typing:

    sudo apt update

    sudo apt upgrade

    sudo apt install ubuntu-server

    sudo reboot

    The process will take a while depending on your hardware. Now you have Ubuntu Server with Desktop GUI.



    (continues in the next post)

    • Offizieller Beitrag

    3.5 Initial Ubuntu Server configuration. User, OpenSSH and Firewall.



    With our installation of Ubuntu Server (or Ubuntu Server on Desktop), we must perform an initial configuration of several points.



    3.5.1 User



    First we make sure that our user has administrative privileges. We open a terminal and log in as root by typing:


    sudo -i


    and we grant privileges to our user by typing:


    usermod -aG sudo [username]


    where [username] is the name of our user. And we return to our user by typing:


    your [username]



    3.5.2 OpenSSH



    If you already installed OpenSSH during the original Ubuntu Server installation skip to 3.5.3


    We install OpenSSH to be able to access the server remotely from the terminal with our PC using Putty or similar. To install OpenSSH we open a terminal using the keyboard shortcut Ctrl + Alt + T or by clicking on the terminal icon and type:

    sudo apt update

    sudo apt upgrade

    sudo apt install openssh-server

    The SSH service will install and start automatically. We verify it by writing:


    sudo systemctl status ssh


    We see an output message similar to the following:


    Active: active (running) ...


    We can now access our VM through Putty.



    3.5.3 Firewall



    Now we configure a basic firewall. Before we check that OpenSSH is available by typing:


    sudo ufw app list


    and it will give us the list of available applications:


    Available applications:

        OpenSSH


    We need to make sure the firewall allows SSH connections so that we can log back in next time. We can allow these connections by typing:


    sudo ufw allow OpenSSH


    We enable the firewall by typing:


    sudo ufw enable


    We can see that SSH connections are still allowed by typing:


    sudo ufw status


    We will get something like this:


    Code
    Status: active
    
    To              Action  From
    --              ------  ----
    OpenSSH         ALLOW   Anywhere
    OpenSSH (v6)    ALLOW   Anywhere (v6)


    and we check that the OpenSSH service appears as ALLOW. From now on we must give permission in the Firewall to the services that we install.


    Nextcloud will need us to open ports 80 and 443 for HTTP and HTTPS connections respectively, so we leave it already configured. When we have finished installing Nextcloud, we will open the ports we need on the router. We type:

    sudo ufw allow http

    sudo ufw allow https

    Note: One of the advantages of having the system virtualized is that we can access it from a viewer. This allows us to prevent access to the server by SSH once the entire system has been configured if we want to gain security. One way to do this is through the firewall.



    3.5.4 Set the host domain



    If you don't have a domain, go to the next point. If we have a domain and we want to establish it, we can do so by editing the hosts file, typing:


    sudo nano /etc/hosts


    and we add the line:


    [DOMAIN-IP] [YOUR-DOMAIN] [HOST-NAME]



    3.6 Disabling or uninstalling the graphical interface.



    If you did not install Ubuntu Desktop skip to point 4.


    At this moment we have an Ubuntu Server installation with the Ubuntu Desktop graphical environment. Since the use will be as a server, it is advisable to save resources and increase security by avoiding the use of the graphical interface. We have two options, the first is to disable it so that it does not start, it will be as if it were not there, but we will have it available if we need it at any time. The second option is to uninstall it and leave the system as Ubuntu Server only.


    If you prefer, you can keep the graphical interface until the end of the process and do this when Nextcloud is fully configured, it may be helpful to have the graphical interface at some point since we already have it installed.



    3.6.1 Disable graphical interface in Ubuntu 20.04 LTS



    To disable the graphical interface we do it through the following command, which will establish the operation of the system in text mode, we type in a terminal:

    sudo systemctl set-default multi-user.target

    sudo reboot

    If we want to run the graphical interface in a timely manner:


    sudo systemctl start graphical.target


    If we want to recover the graphical interface indefinitely:

    sudo systemctl set-default graphical.target

    sudo reboot


    3.6.2 Uninstall graphical interface in Ubuntu 20.04 LTS



    To permanently uninstall the graphical interface and leave the system in its Ubuntu Server version we use the following command. We type from a terminal:

    sudo apt-get update

    sudo apt-get upgrade

    sudo apt-get remove ubuntu-desktop

    sudo apt-get autoremove

    sudo reboot

    We can always reinstall Ubuntu Desktop later if we wanted by using the following command, we type:

    sudo apt-get update

    sudo apt-get upgrade

    sudo apt-get install ubuntu-desktop

    sudo reboot

    If we want a lighter desktop we can substitute ubuntu-desktop for the one we like, for example:


    sudo apt-get install xubuntu-desktop


    or any other that we like, there are many.


    (continues in the next post)

    • Offizieller Beitrag

    4. BACKUP COPY, RESTORATION AND DUPLICATION OF VM.



    At this point our server is ready to install Nextcloud Server (or any other service we want). It can be useful to be able to return to this situation at any time with a few steps, or create a duplicate to lay out another VM. One way to do this is to create a backup of this VM. For this we need two files, the one that hosts the VM and the one that contains the VM's configuration. With those two files we could later restore or duplicate the VM if we wanted.


    If we want to change the disk VM we could also do it by editing the configuration file, changing the path of the VM to the new disk. Previously, we must define the "pool" folder on the new disk as explained in point 2.1.



    4.1 VM backup



    We stop the VM, from ubuntu desktop on the "shutdown" button, from the terminal write "shutdown" or from the OMV GUI by clicking on "Services-KVM-VMs-Status-Stop".


    The file that contains the VM is in the folder that we have defined in the OMV GUI, in my case "pool". Its name is the same as the VM and its extension is ".qcow2" (or whatever we have chosen when creating it). We can access this folder from windows with WinSCP or any other available means. We log in with our user and look for the file. We go to the /srv folder and then we look for the folder where OMV has mounted our disk, and inside there will be the VM folders. In my case it is /srv/dev-disk-by-uuid-744de.../kvm/pool/nextcloud.qcow2. We copy the file using WinSCV at the click of a mouse on our PC and that's it.


    The configuration file of the VM is usually in /etc/libvirt/qemu/nextcloud.xml, it has the same name as the VM and it has a ".XML" extension. If it is not there, we can use the WinSCP search engine through the parameter "nextcloud *. *" For example and we will find it quickly. We make a copy and save it together with the previous file that contains the VM.


    Note: This XML file is in plain text, it is editable with any text editor. It contains the configuration parameters of the VM and can be modified at will with sufficient knowledge. You can find a lot of information on the internet about this.


    These two files are our backup of the VM so we can reuse it at any time and boot from a clean Ubuntu system easily without going through the entire installation process.



    4.2 Restore VM backup



    We turn off the VM


    We replace the file "[VM-name] .qcow2" that contains the VM in its original location (see the previous point "4.1 VM Backup").


    We set permissions to 0600 (read and write for root) with winSCP by clicking on file properties or from the command line.


    We replace the existing configuration file "[VM-name] .XML" in its original location (see the previous point "4.1 VM Backup"), normally it is /etc/libvirt/qemu/, by our copy of security.


    We set permissions to 0600 (read and write for root) with winSCP by clicking on file properties or from the command line.


    We start the VM and we will have it in the state in which the copy was made.



    4.3 VM duplication



    The first thing we need is a backup, see point "4.1 VM Backup".


    We edit the file "[VM-name] .XML" with any text editor and change the name of the VM in all the lines that appears to "[duplicate-VM-name]" or whatever we want. Attention: This name cannot be the same as any VM we already have and cannot contain spaces.


    Rename the file "[VM-name].qcow2" as "[duplicate-VM-name].qcow2".


    Rename the file "[VM-name].XML" as "[duplicate-VM-name].XML".


    We create a VM according to the process detailed in point "2.2 Creation of the VM in the OMV GUI" and with the name that we have given to our duplicate [duplicate-VM-name].


    When we finish we will have two newly created files in their corresponding locations with the name [duplicate-VM-name]. We replace them with the ones corresponding to our backup following the same procedure as in point "4.2 VM Restore".


    To avoid IP conflicts, it is convenient to turn off the original VM first, then we start the duplicate VM, assign it the IP that interests us following the procedure described in "3.3 Network configuration. Fixed IP", and we can start the original VM again.


    (continues in the next post)

    • Offizieller Beitrag

    5. INSTALLATION AND CONFIGURATION OF NEXTCLOUD SERVER IN UBUNTU 20.04 LTS THROUGH SNAP



    You can choose this installation or the manual installation on the system, described in point 6. The snap installation is simpler and recommended for less advanced Linux users. If you prefer the traditional installation with LAMP you can go to point 6.


    Snap-in installation is available in Ubuntu by default, it is a self-installing software container system, along with all its associated dependencies and settings, on a self-contained drive with automatic updates. One of the advantages of this installation is the command system that it integrates to facilitate even more the initial configuration.



    5.1 Installing the Nextcloud Server snap on Ubuntu 20.04 LTS



    If you have a graphical interface you can go to Ubuntu Software, in the search engine we find "Nextcloud Server" and we give it to install, that easy, you already have it installed and you only need to configure it. If you've already done so, skip to 5.2 (or keep reading if you're curious).


    From Ubuntu Server we first install snap by typing the following in terminal:

    sudo apt update

    sudo apt upgrade

    sudo apt install snapd

    and now we can install the Nextcloud snap by typing:


    sudo snap install nextcloud


    We can check the correct installation by typing:


    snap changes nextcloud


    It will give us an output similar to this:

    Code
    ID      Status  Spawn                   Ready                   Summary
    2       Done    today at 16:12 UTC      today at 16:12 UTC      Install "nextcloud" snap

    The status and summary indicate that the installation completed without problems.



    5.2 Initial configuration of the Nextcloud Server snap in Ubuntu 20.04 LTS



    The snap system offers us the advantage of having the snap configuration commands. This makes setup very quick. We can see a list of them by typing in terminal:


    snap info nextcloud


    To start the Nextcloud configuration we have to enter our administrator user and Nextcloud password by typing:


    sudo nextcloud.manual-install [username] [password]


    It will take a while to set up, when finished the cursor will appear again.


    The next step is to adjust the Nextcloud trusted domains. The domain (or fixed public IP in your case) that we write in the browser bar to access Nextcloud, must be included in the registry of domains authorized to access. Otherwise, the system will prevent us from accessing it. By default localhost is activated, this means that we can enter through the IP address whenever we are connected from the same network.


    To see the list of authorized domains we can type the following command at any time:


    sudo nextcloud.occ config:system:get trusted_domains


    A list appears on the screen where only localhost is authorized. If we have a domain (or we have a fixed IP on our router even though we do not have a domain) we proceed to add that address as follows:


    sudo nextcloud.occ config:system:set trusted_domains 1 --value=[my-domain.com]:[my-port]


    where


    [my-domain.com] is the domain that we want to authorize or our fixed public IP address for access to our network.

    [my-port] is the port that we can optionally configure in our router to access from outside and that will redirect the traffic to this host


    We can execute the previous command again and we see that we now have localhost and the domain that we have defined:


    sudo nextcloud.occ config:system:get trusted_domains


    Nextcloud has assigned a value of 0 to localhost and a value of 1 to the domain we have just defined. If we want to add another we will have to change the value 1 to 2 and it would be the third domain defined. We can modify the one we just created by defining the value 1 again and it will overwrite the domain we have on that line. We can create as many entries as we want by increasing that value each time.


    If we want to define custom ports to access Nextcloud we can do it using the following command:


    sudo snap set nextcloud ports.http=[my-http-port] ports.https=[my-https-port]


    Note: Remember that if you do, you will always have to write that port after the IP to access Nextcloud in the browser.


    If we have defined custom ports we must restart the apache server so that it recognizes these changes, typing:


    sudo systemctl restart snap.nextcloud.apache.service


    You can now access Nextcloud if you want by typing the IP of your server in a browser but be sure to read the next point of the guide.


    Note: Maybe your network system prevents you from accessing from localhost, you can solve this by adding your access IP to trusted domains.


    sudo nextcloud.occ config:system:set trusted_domains 1 --value=[your-IP]


    where [your-IP] is the IP address with which you access your Nextcloud server.



    5.3 Installation of Certificate for HTTPS secure browsing in Nextcloud snap.



    The next step is to install a Certificate to access Nextcloud through a secure connection (https). There are two types of certificates, signed by an authorized certification authority or self-signed. With both you can access safely and encrypted interchangeably.


    If you install a self-signed certificate, browsers do not recognize the self-signed certificate but it is only an inconvenience if someone other than you accesses it. The first time you access the web, the browser will give a certificate error, click on "advanced" and "access the web page". The certificate is yours so you can trust it. The next time you log in, it will no longer give that error, although a warning will continue to appear in the navigation bar.


    If you install a Certificate signed by an authorized certifying entity, the connection will be recognized by any browser without complications. The browser recognizes it and the connection is established without warning.


    If you do not have a domain (it is advisable to buy one, they are cheap and easy to configure), you will have to install a self-signed Certificate.


    If you have a domain you can install a Certificate signed by a certifying entity. Such a Certificate can be purchased or it can be a free one from Let's Encrypt. Let's Encrypt certificates expire after 90 days and must be renewed. There are ways to install them so that they auto-renew themselves, through the "certbot" package, depending on your network configuration, or through your domain service if it offers it. You generally need to have ports 80 and 443 open to configure this. Here I am going to explain a simple way to install and renew it manually. There are many other ways to do it.



    Let's Encrypt certificate installation from snap:


    If you have a domain and you have not changed the ports and you have the possibility of opening ports 80 and 443 on your router, you can configure the Let's Encrypt Certificate directly with the following command:


    sudo nextcloud.enable-https lets-encrypt


    and you will have your certificate installed.



    Installation of self-signed certificate and/or manual Let's encrypt:


    If you have changed the access ports to Nextcloud or cannot open ports 80 and 443 on your router, the easiest process is to install a self-signed certificate and then manually replace it with a Let's Encrypt Certificate. In this way we will avoid those port problems. Next I explain how to do it.


    To install a self-signed Certificate we type the following:

    sudo nextcloud.enable-https self-signed

    At this moment in Nextcloud we are already using a self-signed Certificate. If you do not have a domain, you have already finished your Nextcloud configuration. You can go to your favorite browser, write your access address and write username and password. Remember to open ports on your router and enjoy Nextcloud.


    If you want to replace the self-signed Certificate with a Let's Encrypt Certificate manually, keep reading.



    5.4 Manual replacement of self-signed certificate by Let's Encrypt certificate in Nextcloud snap.



    Once the self-signed certificate is installed (see point 5.3), the next thing you need to do is generate the certificates on the web, there are many ways to do it, for example at http://www.zerossl.com, and download them. If you do it on this website, the files you download correspond to those used by Nextcloud as follows:


    Certificate Type zerossl certificates Certificates used by Nextcloud


    Domain certificate.crt cert.pem -rw-r - r--

    Intermediate entity ca_bundle.crt chain.pem -rw-r - r--

    private key private.key privkey.pem -rw-r - r--


    So we change the names of our files to match those in Nextcloud, and we copy them to our Ubuntu home in a folder that we call "certificates", using the command line or in the graphical interface.


    The certificates that we are going to replace are in the /var/snap/nextcloud/current/certs/live/ folder. To access we must log in as root, in a terminal we write:


    sudo su


    we go to the folder where the self-signed certificates are and we check that they are indeed there:

    cd /var/snap/nextcloud/current/certs/live/

    ls -l

    We delete them and check that they are no longer there:

    rm * .pem

    ls -l

    and we copy our certificates from the home folder, checking it later:

    cp /home/[my-usuario]/certificates/*.pem.

    ls -l

    It only remains to install and configure them on the server


    sudo nextcloud.enable-https custom -s cert.pem privkey.pem chain.pem


    And we already have our certificates configured. These certificates expire after 90 days, so this process will have to be repeated at that time. Now you can go to your browser, enter the address of your domain and enjoy Nextcloud. Remember to open ports on your router.


    (continues in the next post)

    • Offizieller Beitrag

    6. INSTALLATION AND MANUAL CONFIGURATION OF NEXTCLOUD SERVER 22 IN UBUNTU 20.04 LTS. ADVANCED USERS.



    If you are a user unfamiliar with Linux, it is recommended that you do a snap installation following point 5. of this guide. If you are an advanced user, continue if you want.


    The manual installation consists of the manual installation and pre-configuration of the database and the apache server in Ubuntu. Later Nextcloud is installed and integrated directly into the operating system.


    To do this we follow the procedure described in the Nextcloud documentation, see here.



    6.1 Apache and MySQL Installation



    The first thing we must do is install the mariadb and apache packages by typing:

    sudo apt update

    sudo apt-get install apache2 mysql-server -y

    and we start them by typing:

    sudo systemctl start apache2

    sudo systemctl enable apache2

    sudo systemctl start mysql

    sudo systemctl enable mysql

    We install dependencies by typing:


    sudo apt-get install php zip libapache2-mod-php php-gd php-json php-mysql php-curl php-mbstring php-intl php-imagick php-xml php-zip php-mysql php-bcmath php-gmp zip -y


    Before using MySQL, it is important to secure it. We type:


    sudo mysql_secure_installation


    We answer the questions affirmatively and set a password. Next we connect to the database and configure it by typing:


    sudo mysql -u root -p


    We introduce the password that we established in the previous step, we create the database called "nextcloud", the user "nextcloud" and its password, and we give it privileges on the newly created database, using the following commands:

    CREATE DATABASE nextcloud;

    CREATE USER 'nextcloud'@'localhost' IDENTIFIED BY '[my-password]';

    GRANT ALL PRIVILEGES ON nextcloud. * TO 'nextcloud'@'localhost';

    FLUSH PRIVILEGES;

    quit

    where [my-password] is the strong password that we give to the user nextcloud.



    6.2 Installing Nextcloud 22



    At this moment you can start the installation of Nextcloud, the current version is 22. The download link is copied from the official Nexcloud download page here, click Right click on the download link and copy it. We download and unzip the application to the directory where we want to install it:

    wget https://download.nextcloud.com/server/releases/nextcloud-22.0.0.zip

    unzip nextcloud-22.0.0.zip

    sudo mv nextcloud /var/www/html/

    We change the owner of the newly created nextcloud directory and give it to the user www-data:


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



    6.3 Apache configuration



    Configuring Apache on Ubuntu requires the creation of a single configuration file for Nextcloud which will be /etc/apache2/sites-available/nextcloud.conf. We create it with the command:


    sudo nano /etc/apache2/sites-available/nextcloud.conf


    In that file, we copy the following:


    Code
    Alias /nextcloud "/var/www/html/nextcloud/"
    <Directory /var/www/html/nextcloud/>
        Options +FollowSymlinks 
        AllowOverride All 
          <IfModule mod_dav.c> 
            Dav off 
          </IfModule> 
         SetEnv HOME /var/www/html/nextcloud 
        SetEnv HTTP_HOME /var/www/html/nextcloud
    </Directory>


    We exit by ctrl+x saving the changes.


    We enable the new site by typing:

    sudo systemctl reload apache2

    sudo a2ensite nextcloud

    We enable the necessary Apache modules:


    sudo a2enmod rewrite headers env dir mime


    We change the PHP memory limit:


    sudo sed -i '/^memory_limit =/s/=.*/= 512M/' /etc/php/7.4/apache2/php.ini


    Note: If your PHP version is different from 7.4, you will need to modify the above command accordingly.


    We restart Apache:


    sudo systemctl restart apache2



    6.4 Starting Nextcloud



    Now we can start Nextcloud, we open a browser and go to http: // [your-IP] / nextcloud (where [your-IP] is the IP address or domain). In the dialog box we enter an administrator username for Nextcloud with its corresponding password, and complete the rest of the information as follows:


    Database user: nextcloud

    Database password: the password we created for the nextcloud database user

    Database name: nextcloud


    Click on "Finish installation" and we are already inside Nextcloud with the administrator user that we just created.


    You only need to add the Certificate you use to access your Nextcloud. Remember to open ports and enjoy your Nextcloud.

    • Offizieller Beitrag



    COMO INSTALAR NEXTCLOUD EN UNA VM UBUNTU 20.04 VIRTUALIZADO CON KVM EN OMV




    0. INDICE


    1. INTRODUCCION.

    1.1 Requisitos de hardware

    1.2 Configuración de teclado en la VM

    1.3 Configuración de la red


    2. CREACIÓN DE LA MAQUINA VIRTUAL EN KVM DE OPENMEDIAVAULT

    2.1 Pasos previos

    2.2 Creación de la VM en la GUI de OMV

    2.3 Visores y puesta en marcha de la VM


    3. INSTALACION Y CONFIGURACION INICIAL DE UBUNTU 20.04 LTS

    3.1 Ubuntu Desktop 20.04 LTS

    3.2 Ubuntu Server 20.04 LTS

    3.3 Configuración de red. IP fija.

    3.4 Completar instalación de Ubuntu Desktop a Ubuntu Server

    3.5 Configuración inicial Ubuntu Server. Usuario, OpenSSH y Firewall

    3.5.1 Usuario

    3.5.2 OpenSSH

    3.5.3 Firewall

    3.5.4 Establecer el dominio del host

    3.6 Deshabilitación o desintalación de interfaz gráfica.

    3.6.1 Desahibilitar interfaz gráfica en Ubuntu 20.04 LTS

    3.6.2 Desinstalar interfaz gráfica en Ubuntu 20.04 LTS


    4. COPIA DE SEGURIDAD, RESTAURACION Y DUPLICADO DE VM.

    4.1 Copia de seguridad de VM

    4.2 Restaurar copia de seguridad de VM

    4.3 Duplicado de VM


    5. INSTALACION DE NEXTCLOUD SERVER EN UBUNTU 20.04 LTS MEDIANTE SNAP

    5.1 Instalación del snap Nextcloud Server en Ubuntu 20.04 LTS

    5.2 Configuración inicial del snap Nextcloud Server en Ubuntu 20.04 LTS

    5.3 Instalación de Certificado para navegación segura HTTPS en snap de Nextcloud.

    5.4 Sustitución manual de certificado autofirmado por certificado Let's Encrypt en snap de Nextcloud.


    6. INSTALACION Y CONFIGURACION MANUAL DE NEXTCLOUD SERVER EN UBUNTU 20.04 LTS. USUARIOS AVANZADOS.

    6.1 Instalación de Apache y MySQL

    6.2 Instalación de Nextcloud 22

    6.3 Configuración de Apache

    6.4 Inicio de Nextcloud



    1. INTRODUCCIÓN.



    Nextcloud es un servicio de código abierto que proporciona una nube privada alojada en nuestro servidor, al estilo de icloud o google drive, pero con los documentos bajo nuestro absoluto control en nuestro servidor. Dispone de infinidad de plugins que amplían su funcionalidad. En su página oficial encontramos documentación para usuario, ver aquí, y para administrador, ver aquí.


    En esta guía se explican los procedimientos de manera que lo pueda entender un usuario recién llegado a linux, si eres un usuario avanzado podrás saltar muchas partes.


    Se describe el PROCESO COMPLETO partiendo de una instalación de OPENMEDIAVAULT (OMV) convencional para llegar a disponer de Nextcloud en una MAQUINA VIRTUAL (VM) de Ubuntu dentro de OMV mediante el complemento KVM. El complemento KVM está integrado en la GUI de OMV (gracias, ryecoaaron), permite virtualizar un sistema operativo de manera sencilla y existe apoyo en este foro para su uso. Ubuntu es uno de los sistemas operativos recomendados para alojar Nextcloud en su documentación oficial, ver aquí.


    Se describe el proceso de virtualización en OMV mediante el complemento KVM. Se soluciona algún posible problema de mapeo de teclado en idiomas distintos al inglés con algunos sistemas operativos linux, este método es mejorable, pero funciona.


    Se describe cómo instalar y configurar Ubuntu con entorno gráfico o sin él (Desktop o Server), y cómo convertir Desktop en Server y viceversa. Tambié se puede dejar el entorno gráfico instalado pero desactivado sin consumir recursos, recomendable para usuarios no avanzados de linux.


    Se describen dos métodos de instalación de Nextcloud. Mediante snap o mediante instalación de LAMP y Nextcloud en el sistema. Hay varias formas de hacerlo, ver aquí. Se recomienda la instalación mediante snap para usuarios no avanzados de linux.


    Se describe como hacer la configuración inicial inicial de Nextcloud.


    Se describe como instalar un Certificado Lets Encrypt o un certificado autofirmado si no dispones de un dominio (es recomendable disponer de uno, es barato y fácil de configurar, pero no es imprescindible).


    Según tus elecciones de instalación irás saltando partes de la guía.



    1.1 Requisitos de hardware:



    CPU con capacidad virtualización (consultar las características en la web del fabricante)

    CPU con al menos dos núcleos para instalar Ubuntu en la VM.

    Memoria RAM. Al menos 2GB para dedicar a la VM de Ubuntu (más la que necesitemos para el sistema OMV, aconsejable disponer de 4GB o más en el sistema)

    Disco duro. Recomendable un disco SSD formateado en EXT4 y de la capacidad que queramos disponer en Nextcloud. Los formatos de disco que utilizan "copy on write" no son amigos de las máquinas virtuales, aunque siempre se puede desactivar el "copy on write" en esa carpeta. Si más tarde necesitamos más espacio hay formas de ampliarlo añadiendo otro disco o sustituyendo éste y trasladando la VM al disco nuevo (ver punto 4 de esta guía).



    1.2 Dificultades con el mapeo de teclados en la VM:



    Hay complicaciones históricas con el mapeo de teclado y los visores gráficos en máquinas virtuales (sobre todo los visores VNC), y aparentemente algunos aún persisten. KVM configura por defecto el mapeo de teclado en inglés, si utilizas teclado inglés no tendrás estos problemas. En mi caso, con teclado español, he podido configurarlo correctamente en Ubuntu Server después de varios intentos. En otros idiomas también hay complicaciones.


    Un camino fácil para superar esta dificultad consiste en instalar Ubuntu Desktop, y utilizar Virt Viewer (Spice) para visualizar la VM desde un PC con windows. Ubuntu Desktop configura correctamente todo de manera automática y funciona. Después instalar Ubuntu Server sobre Ubuntu Desktop (muy sencillo, una orden en la línea de comando). Después puedes elegir desactivar o desinstalar la interfaz gráfica para ahorrar recursos y ganar en seguridad del servidor, o mantenerla activa si quieres.



    1.3 Configuración de la red en la VM:



    Hay dos opciones de configuración de red en la VM.


    La red "default", configuración por defecto, explicado de manera sencilla es el equivalente a tener un "router virtual" intermedio entre nuestra VM y el router físico (o el equipo que asigne IPs). Este router virtual asignará direcciones IP a la VM en una subred dentro de la red principal de nuestra intranet. Es decir, se crea una subred dentro de nuestra intranet.


    La red "bridge" es un puente Macvtap, es el equivalente a un "switch virtual". Es como tener un switch que direcciona a la máquina anfitrión (OMV) y a la máquina invitada (nuestra VM) por igual hasta el router físico de nuestra intranet. Nuestro router asignará una IP a OMV y otra IP a la VM como si fueran máquinas separadas dentro de la red.


    Mi recomendación si tienes problemas con esto es definir la VM con la red "default" y luego cambiarla a "bridge". Es el método que mejor me ha funcionado para que Ubuntu lo reconozca correctamente. Cada uno que siga su mejor camino.


    (continúa en el siguiente post)


    • Offizieller Beitrag

    2. CREACIÓN DE LA VM UBUNTU 20.04 LTS EN KVM DE OPENMEDIAVAULT.



    2.1 Pasos previos



    Cumplir los requisitos de hardware, ver punto 1.1 de esta guía.


    Instalar OMV. Ver aquí


    Instalar "OMV-extras", ver aquí.


    Activar el plugin "KVM", ver aquí.


    Descargar la ISO de instalación a elección de Ubuntu Desktop o Ubuntu Server 20.04 LTS aquí.


    El disco que vamos a utilizar para la VM debe estar montado desde la GUI de OMV, ver aquí.


    Creamos en nuestro disco las carpetas para instalar la VM. Si no estás familiarizado con linux preferirás hacerlo con WinSCP (un explorador gráfico para windows, ver aquí), desde línea de comandos lo podemos hacer con Putty (ver aquí) o cualquier otra herramienta.


    Buscamos la carpeta donde OMV ha montado nuestro disco, esta carpeta estará ubicada dentro de /srv y podemos encontrar su nombre en la GUI de OMV en "Almacenamiento - Sistema de archivos" abriendo la columna "identificado como" (para ver esta columna abrir el desplegable del título de cualquier columna existente y buscar la opción).


    Una vez dentro de esta carpeta de montaje del disco, creamos la carpeta "kvm". Dentro de "kvm" creamos otras dos carpetas. La primera carpeta será "ISOS" y la segunda será "pool". (La carpeta ISOS es la ubicación donde almacenaremos las isos de instalación, y la carpeta pool almacenará las VMs generadas por el complemento KVM).


    Damos los correspondientes permisos a las carpetas, en este caso lectura y escritura al usuario root. Desde WinSCP en propiedades escribimos "root" en el cuadro "propietario" y pinchamos en "r" y "w" de root, o en linea de comandos desde la carpeta donde está montado el disco tecleando:

    sudo chown -R root /kvm/

    sudo chown 600 /kvm/

    Una vez creadas las carpetas copiamos la imagen de instalación ISO de Ubuntu descargada previamente dentro de /kvm/ISOS/.


    Debemos decirle al complemento KVM dónde hemos creado estas carpetas. Para ello nos vamos a la GUI de OMV y pulsamos en "Servicios - KVM - Pools - +Añadir".


    En el cuadro de diálogo buscamos la ruta de la carpeta "ISOS" que hemos creado y la seleccionamos, en mi caso es:

    /srv/dev-disk-by-uuid-744d..../kvm/ISOS

    En el cuadro correspondiente escribimos el nombre "ISOS" y aceptamos. Seleccionamos la línea que ha aparecido, y cuando esté resaltada en amarillo, activamos la carpeta pulsando en el menú "Estado - Comienzo".


    Repetimos el proceso con la carpeta pool, la llamamos "pool", aceptamos y la activamos de la misma manera.


    Pulsamos en el Menú "ISOs" y comprobamos que ha aparecido el ISO de instalación de Ubuntu que habíamos copiado previamente en el punto anterior. Si no aparece ahí es porque no hemos copiado el archivo a la carpeta o no la hemos activado correctamente.



    2.2 Creación de la VM en la GUI de OMV



    Una vez creadas y definidas las carpetas del punto anterior, ahora creamos un dispositivo de red para que lo pueda utilizar la VM, nos vamos al menú "Redes", y en este caso usamos la red "default" existente, la seleccionamos (pulsar la línea y volverla amarillo) y la activamos pulsando en el menú "Estado - Comienzo".


    Nota: Ver la explicación de red "default" y red "bridge" en la introducción de esta guía.


    Ahora vamos a definir las características de la máquina virtual que queremos crear. Nos vamos a la pestaña VMs y pulsamos en "+Añadir". Se nos abrirá un cuadro de diálogo para la creación de la VM. En el caso que nos ocupa la configuramos rellenando los campos de la siguiente manera:


    - Nombre de la máquina: Lo que quieras, yo la llamo "nextcloud". Este NO es el nombre del host que vamos a crear, es el nombre de la VM en la GUI de OMV, el nombre del host lo definiremos dentro de la VM durante su instalación. Atención: No utilizar espacios en este nombre (si tu versión del complemento está actualizada no te lo permitirá).

    - OS: Linux

    - UEFI: Según tus necesidades. Yo no lo activo.

    - CPU: Mínimo 2 para que funcione Ubuntu. Para Ubuntu Server el mínimo es 1. Yo asigno 4 (todas las que tengo), esto se puede modificar después.

    - Memoria: Mínimo 2GB para que funcione Ubuntu. Para Ubuntu Server el mínimo es 1GB. Yo asigno 2GB, esto se puede modificar después.

    - Volumen: Seleccionamos "Create new disk"

    - Pool: Seleccionamos "pool"

    - Nombre: Lo dejamos en blanco

    - Tamaño: Si queremos utilizar el disco completo marcamos su capacidad. El archivo VM irá creciendo a medida que lo utilicemos.

    - Formatear: qcow2 (como está)

    - Bus: Virtio (como está)

    - CD: Seleccionamos el archivo ISO de instalación de Ubuntu en la lista desplegable.

    - Modelo: virtio (como está)

    - Red: Seleccionamos "Default". Esto se puede cambiar después.


    Nota: Ver definición de red en la introducción de esta guía.


    Nota: Si por algún motivo necesitáramos tener sonido en la VM, se puede hacer pulsando la pestaña "opciones avanzadas" arriba a la izquierda y luego la pestaña audio dentro de "Opciones". Aparecerán también otras opciones por si alguien tiene otras necesidades avanzadas.


    Pulsamos en salvar y ya tenemos la máquina virtual configurada y lista para arrancar.



    2.3 Visores y puesta en marcha de la VM



    Antes de poner en marcha la VM lee este punto completo.


    Para encender nuestra VM nos vamos a la GUI de OMV, y en "Servicios - KVM - VMs" seleccionamos la VM "nextcloud-server" para ponerla en amarillo, luego la encendemos pulsando en "Estado - Comienzo". Nos vamos al visor que hayamos elegido y ya podemos ver Ubuntu iniciándose en la pantalla.


    Para visualizar la VM hay varias opciones, si tu teclado es inglés (tienes privilegios de root ;) ) se amplían tus posibilidades.


    Opción 1. Visor Spice.


    Cuando hayamos puesto la VM en marcha, nos aparecerá un número de puerto en la columna Spice port. Necesitamos un visor instalado en nuestro PC. El visor Virt Viewer (Spice) para windows se puede descargar aquí. A mí me ha funcionado perfecto y me mapea el teclado sin problemas. Si tu PC es linux desconozco las opciones pero habrá otras. Lo arrancamos y escribimos la dirección:


    spice://[tu IP de OMV]:[puerto en la GUI de KVM para Spice]


    Ejemplo: Mi IP de acceso a OMV es 192:168:1:87 y el puerto que me ha salido en la GUI de KVM para Spice es 5901, así que en mi caso sería:


    spice://192.168.1.87:5091


    Opción 2. Visor VNC


    Cuando hayamos puesto la VM en marcha, nos aparecerá un número de puerto en la columna para visores VNC. Se puede utilizar Real VNC o cualquier otro visor VNC. En la dirección escribiremos:


    [tu IP de OMV]:[puerto en la GUI de OMV para VNC]


    Nota: Este método para mí no funciona porque los visores VNC son los que más problemas dan con el mapeo de teclados. Unos visores mapean mejor que otros pero ninguno es perfecto, al menos los que he probado. Esta tontería inutiliza la VM en muchos casos. Si tu teclado es inglés estás de suerte.


    Opción 3. Consola integrada en navegador.


    Se puede abrir una pestaña directamente en el navegador, para ello pulsamos en "Consola - Create consoles", nos parecerá un Link bajo la columna "noVNC URL" y otro bajo la columna "spice-html5 URL". Si pinchamos en cualquiera de los dos se nos abrirá una pestaña en el navegador de visualización.


    Nota: En mi caso tengo el mismo problema con noVNC, mapeo de teclado incorrecto en muchos casos (si tu teclado es imglés estás de suerte otra vez). El segundo link (spice) me da problemas de visualización según con qué PC lo abra, así que tampoco lo uso, tal vez a ti te funcione mejor.


    En definitiva, muchas opciones, cada uno que use su mejor solución. Comprueba cuál te funciona a tí con tu teclado.


    (continúa en el siguiente post)

    • Offizieller Beitrag

    3. INSTALACION Y CONFIGURACION INICIAL DE UBUNTU 20.04 LTS



    Elegir la instalación de Ubuntu Desktop o Ubuntu Server. Ver introducción y problemas de mapeo de teclados. Siempre podrás convertir después un desktop en server y viceversa, aquí se explica cómo hacerlo. También puedes elegir Desktop si no eres usuario avanzado de linux y lo prefieres. Si vas a instalar Ubuntu Server pasa al punto 3.2.



    3.1 Ubuntu Desktop 20.04 LTS



    En el visor de nuestra VM y con la bienvenida de Ubuntu delante seleccionamos nuestro idioma y pulsamos en instalar, seleccionamos nuestro teclado local, y en la sección "aplicaciones y otro software" cambiamos la opción a "Instalación mínima", aceptamos las distintas opciones, aceptamos la nuestra ubicación si es correcta o la ajustamos en caso necesario, introducimos un nombre de usuario y contraseña y aceptamos. Seleccionando la instalación mínima evitamos la instalación de muchos paquetes que no necesitamos.


    Cuando finalice el proceso reiniciamos. Nos logueamos de nuevo y actualizamos ubuntu desde "software", pulsando en "actualizar", o podemos abrir una terminal y teclear "sudo update" y después "sudo upgrade" (sin comillas).


    Nota: Ubuntu ya debería haber reconocido nuestra red (podemos comprobarlo en configuración de red, deberíamos tener una IP asignada) y ya deberíamos tener el teclado perfectamente configurado en nuestro idioma local (podemos comprobarlo creando un archivo en blanco y tecleando caracteres especiales), si todo es correcto podemos continuar. En el caso del idioma español funciona todo correctamente, si en otro idioma no está bien configurado tendrás que resolverlo antes de seguir, no puedo ayudarte aquí.


    Pasa al punto 3.3



    3.2 Ubuntu Server 20.04 LTS



    Iniciamos el proceso de instalación. Cuando salga la ventana de instalación de paquetes adicionales NO instalamos nextcloud, lo instalaremos después. Si que puedes instalar OpenSSH durante el proceso y ya tendrás un paso adelantado, no instales ninguna opción más.


    Finalizamos el proceso y reiniciamos. Nos logueamos de nuevo y actualizamos ubuntu.

    sudo apt update

    sudo apt upgrade


    3.3 Configuración de red. IP fija.



    Nota: Para un funcionamiento sin acceso desde el exterior de nuestra red, la VM podría vivir detrás de una NAT sin más complicaciones, tiene acceso a internet sin problemas. Pero en nuestro caso va a funcionar como servidor accesible desde el exterior y necesitamos enviarle información desde internet, los paquetes deben ser enrutados hasta el host de la VM de alguna manera. El problema es que nuestro router no sabe donde está nuestro servidor, solo lo sabe el router virtual de KVM (doble NAT). Tenemos dos opciones, la primera es configurar nuestro router físico para que redireccione esos paquetes al "router virtual" de KVM, y éste los reenviará a la IP del host nextcloud-server. Para hacer esto hay que configurar una ruta fija en el router físico. La segunda opción es crear un "Bridge" (switch virtual), de esta forma el router físico asignará una IP directamente a Nextcloud y será un dispositivo más en nuestra intranet principal, sin intermediarios, los paquetes le llegarán directamente. Este método parece más sencillo para el funcionamiento del dia a dia y es lo que haremos. Vamos a cambiar la red "default" de KVM (Router virtual) por un "bridge" (Switch virtual). He probado a crear la VM directamente con un bridge y no me ha funcionado, no se configuraba bien el adaptador y me daba muchos problemas que no sé resolver, por eso lo hago así. En tu caso tal vez funcione directamente.


    Apagamos la VM, tecleamos "sudo shutdown" o apagamos ubuntu en modo gráfico si lo tenemos.


    Nos vamos a la GUI de OMV y comprobamos en "Servicios - KVM - VMs" que nuestra VM "nextcloud" aparece en estado "shutoff" en la columna correspondiente.


    En "Servicios - KVM - Redes" pulsamos en "+Añadir puente Macvtap".


    Aparecerá una línea llamada "bridge". La seleccionamos y la activamos pulsando en "Estado - Comienzo".


    Pulsamos en "VMs", seleccionamos la VM "nextcloud-server" y pulsamos en "Dispositivos - Añadir red"


    En el cuadro de diálogo y dentro de la opción "Red" seleccionamos "Bridge" y aceptamos.


    Pulsamos en "Dispositivos - Quitar red", seleccionamos la red "Default" y aceptamos.


    Volvemos a iniciar la VM pulsando en "Estado - Comienzo" y nos vamos a nuestro visor preferido.


    Nota: Ya deberíamos tener nuestro servidor tras un switch (virtual) y nuestro router físico ya debería verlo y asignarle una IP directamente dentro de nuestra red habitual como si fuera un equipo más. Podemos comprobarlo en la configuración de red.


    Ahora ya podemos asignar una IP fija a la VM. Esto lo podemos hacer desde el propio router físico si dispone de esta opción mediante la dirección MAC del host de Nextcloud o desde el propio Ubuntu. Lo hacemos desde Ubuntu a continuación.


    Si tu Ubuntu es Desktop y tienes interfaz gráfica puedes entrar directamente a configuración y hacerlo gráficamente, más fácil. En "configuración - red", pulsar la rueda en "cableado", pulsar "IPv4", pulsar en "manual", escribir la IP que nos interese en "Dirección", en "Mascara de red" escribir "255.255.255.0" (sin comillas), en "puerta de enlace" escribir la IP de nuestro router, en DNS las de nuestro proveedor de internet u otras genéricas, como las de cloudflare 1.1.1.1,1.0.0.1 o las que queramos. Reinicia y pasa al punto siguiente (puedes seguir leyendo y experimentar si no estás familiarizado con la línea de comandos, abre una terminal y prueba).


    Si tu Ubuntu es Server puedes hacerlo desde la línea de comandos editando el fichero de configuración. Para comprobar el valor inicial que tiene el archivo 00-installer-config.yaml tecleamos:


    cat /etc/netplan/00-installer-config.yaml


    La configuración predeterminada de NetPlan será similar a esta:


    Code
    network:
      ethernets:
        enp0s3:
          dhcp4: true
      version: 2


    Lo que establece es que el adaptador de red que estamos definiendo es enp0s3 y que utiliza DHCP.


    Atención: cuidado con las sangrías, no utilizar TAB, los archivos yaml no funcionarán si no están bien configurados. Recomendable hacer antes una copia del original antes de editarlo.


    Para editar el archivo de configuración correspondiente tecleamos:


    sudo nano /etc/netplan/00-installer-config.yaml


    Dentro de la ventana de trabajo de nano, lo primero será cambiar el valor "dhcp4: true" por "dhcp4: false" o "dhcp4: no". Después, escribiremos los valores de configuración de la red, que serán parecidos a estos:


    Code
    network:
      ethernets:
        enp0s3:
          dhcp4: no
          addresses: [192.168.1.200/24]
          gateway4: 192.168.1.1
          nameservers:
             addresses: [1.1.1.1,1.0.0.1]
      version: 2


    las líneas que aparecen bajo "dhcp4: no" establecen los valores estáticos que necesitamos:


    addresses: [192.168.1.200/24]: Establece que la dirección IP de equipo será siempre 192.168.1.200 en mi caso, debes elegir la IP que te interese dentro de tu red. También indica que la máscara de red utiliza 24 bits (lo que equivale a 255.255.255.0). Este valor también puede cambiar según las características de tu red.

    gateway4: 192.168.1.1: Determina la dirección de la puerta de enlace para TCP/IPv4. En mi caso la IP de mi router, lo más habitual, si tu caso es distinto adaptalo a tus necesidades.

    nameservers: Configura la dirección (o direcciones) de Internet donde se encuentra el servidor DNS que usaremos para convertir los nombres de dominio en direcciones IP. En este caso utilizaremos el servidor de cloudflare 1.1.1.1,1.0.0.1, pon las que más te gusten, si son varias pueden ir separadas con comas, como en este caso.


    Una vez completados los cambios en el archivo saldremos del editor guardando cambios. Pulsamos Ctrl+X guardamos cambios y salimos.


    Aplicamos los cambios del archivo de configuración tecleando:


    sudo netplan apply


    Comprobamos los cambios consultando la configuración actual de la red:


    ip addr


    y podremos ver que nuestra IP es la que hemos definido.



    3.4 Completar instalación de Ubuntu Desktop a Ubuntu Server



    Si has instalado directamente Ubuntu Server pasa al punto 3.5.


    Si has instalado Ubuntu Desktop debes completar tu instalación con los paquetes de Ubuntu Server restantes. Instalamos el paquete Ubuntu Server dentro de nuestra versión de Ubuntu Desktop, abriendo una terminal usando el atajo de teclado Ctrl+Alt+T o haciendo clic en el icono de la terminal y escribimos:

    sudo apt update

    sudo apt upgrade

    sudo apt install ubuntu-server

    sudo reboot

    El proceso llevará un tiempo dependiendo de tu hardware. Ahora tienes Ubuntu Server con interfaz gráfica de Desktop.


    (continúa en el siguiente post)

    • Offizieller Beitrag

    3.5 Configuración inicial Ubuntu Server. Usuario, OpenSSH y Firewall.



    Con nuestra instalación de Ubuntu Server (o Ubuntu Server sobre Desktop), debemos realizar una configuración inicial de varios puntos.



    3.5.1 Usuario



    Primero nos aseguramos que nuestro usuario tiene privilegios administrativos. Abrimos una terminal e iniciamos sesión como root tecleando:


    sudo -i


    y le otorgamos privilegios a nuestro usuario tecleando:


    usermod -aG sudo [nombre_usuario]


    donde [nombre_usuario] es el nombre de nuestro usuario. Y volvemos a nuestro usuario tecleando:


    su [nombre_usuario]



    3.5.2 OpenSSH



    Si ya instalaste OpenSSH durante la instalación original de Ubuntu Server pasa al punto 3.5.3


    Instalamos OpenSSH para poder acceder en remoto al servidor desde terminal con nuestro PC mediante Putty o similar. Para instalar OpenSSH abrimos una terminal usando el atajo de teclado Ctrl+Alt+T o haciendo clic en el icono del terminal y escribimos:

    sudo apt update

    sudo apt upgrade

    sudo apt install openssh-server

    El servicio SSH se instalará y se iniciará automáticamente. Lo verificamos escribiendo:


    sudo systemctl status ssh


    Vemos un mensaje de salida similar al siguiente:


    Active: active (running)...


    Ya podemos acceder a nuestra VM mediante Putty.



    3.5.3 Firewall



    Ahora configuramos un firewall básico. Antes comprobamos que OpenSSH está disponible tecleando:


    sudo ufw app list


    y nos dará la lista de aplicaciones disponibles:

    Available applications:

    OpenSSH

    Necesitamos asegurarnos de que el firewall permita conexiones SSH para que podamos volver a iniciar sesión la próxima vez. Podemos permitir estas conexiones escribiendo:


    sudo ufw allow OpenSSH


    Habilitamos el firewall escribiendo:


    sudo ufw enable


    Podemos ver que las conexiones SSH todavía están permitidas escribiendo:


    sudo ufw status


    Nos saldrá algo como esto:

    Code
    Status: active
    
    
    To                         Action      From
    --                         ------      ----
    OpenSSH                    ALLOW       Anywhere
    OpenSSH (v6)               ALLOW       Anywhere (v6)

    y comprobamos que el servicio OpenSSH aparece como ALLOW. A partir de ahora debemos dar permiso en el Firewall a los servicios que instalemos.


    Nextcloud necesitará que abramos los puertos 80 y 443 para conexiones HTTP y HTTPS respectivamente, así que lo dejamos ya configurado. Cuando hayamos terminado la instalación de Nextcloud abriremos en el router los puertos que necesitemos. Tecleamos:

    sudo ufw allow http

    sudo ufw allow https

    Nota: Una de las ventajas de tener virtualizado el sistema es que podemos acceder a él desde un visor. Esto nos permite impedir el acceso al servidor por SSH una vez configurado todo el sistema si queremos para ganar en seguridad. Una forma de hacerlo es mediante el firewall.



    3.5.4 Establecer el dominio del host



    Si no tienes un dominio pasa al punto siguiente. Si disponemos de un dominio y queremos establecerlo, lo podemos hacer editando el archivo hosts, tecleando:


    sudo nano /etc/hosts


    y añadimos la línea:


    [IP-DEL-DOMINIO] [TU-DOMINIO] [NOMBRE DEL HOST]



    3.6 Deshabilitación o desintalación de interfaz gráfica.



    Si no instalaste Ubuntu Desktop pasa al punto 4.


    En este momento disponemos de una instalación de Ubuntu Server con el entorno gráfico de Ubuntu Desktop. Dado que el uso va a ser como servidor es recomendable ahorrar recursos y aumentar la seguridad evitando el uso de la interfaz gráfica. Tenemos dos opciones, la primera es deshabilitarla para que no se inicie, será como si no estuviera, pero la tendremos disponible si la necesitamos en cualquier momento. La segunda opción es desinstalarla y dejar el sistema como Ubuntu Server únicamente.


    Si lo prefieres puedes mantener la interfaz gráfica hasta el final del proceso y hacer esto cuando Nextcloud esté completamente configurado, puede ser de ayuda disponer de la interfaz gráfica en algún momento puesto que ya la tenemos instalada.



    3.6.1 Desahibilitar interfaz gráfica en Ubuntu 20.04 LTS



    Para deshabilitar la interfaz gráfica lo hacemos mediante el siguiente comando, que establecerá el funcionamiento del sistema en modo texto, tecleamos en una terminal:

    sudo systemctl set-default multi-user.target

    sudo reboot

    Si queremos ejecutar la interfaz gráfica de manera puntual:


    sudo systemctl start graphical.target


    Si queremos recuperar la interfaz gráfica de forma indefinida:

    sudo systemctl set-default graphical.target

    sudo reboot


    3.6.2 Desinstalar interfaz gráfica en Ubuntu 20.04 LTS



    Para desinstalar la interfaz gráfica de forma permanente y dejar el sistema en su versión Ubuntu Server utilizamos el siguiente comando. Tecleamos desde una terminal:

    sudo apt-get update

    sudo apt-get upgrade

    sudo apt-get remove ubuntu-desktop

    sudo apt-get autoremove

    sudo reboot

    Siempre podremos volver a instalar Ubuntu Desktop más adelante si quisiéramos mediante el siguiente comando, tecleamos:

    sudo apt-get update

    sudo apt-get upgrade

    sudo apt-get install ubuntu-desktop

    sudo reboot

    Si quisiéramos un escritorio más liviano podemos sustituir ubuntu-desktop por el que nos guste, por ejemplo:


    sudo apt-get install xubuntu-desktop


    o cualquier otro que nos guste, hay muchos.


    (continúa en el siguiente post)

    • Offizieller Beitrag

    4. COPIA DE SEGURIDAD, RESTAURACION Y DUPLICADO DE VM.



    En este punto nuestro servidor está listo para instalar Nextcloud Server (o cualquier otro servicio que queramos). Puede ser de utilidad poder volver en cualquier momento a esta situación con unos pocos pasos, o crear un duplicado para disponer otra VM. Una forma de hacerlo es crear una copia de seguridad de esta VM. Para ello necesitamos dos archivos, el que aloja la VM y el que contiene la configuración de la VM. Con esos dos archivos podríamos restaurar más adelante o duplicar la VM si quisiéramos.


    Si queremos cambiar la VM de disco también podríamos hacerlo editando el archivo de configuración, cambiando la ruta de la VM al nuevo disco. Previamente debemos definir la carpeta "pool" en el disco nuevo tal como es explica en el punto 2.1.



    4.1 Copia de seguridad de VM



    Paramos la VM, desde ubuntu desktop en el botón "apagar", desde terminal escribir "shutdown" o desde la GUI de OMV pulsando en "Servicios-KVM-VMs-Estado-Parar".


    El archivo que contiene la VM está en la carpeta que hamos definido en la GUI de OMV, en mi caso "pool". Su nombre es el mismo que el de la VM y su extensión es ".qcow2" (o el que hayamos elegido al crearla). Podemos acceder a esta carpeta desde windows con WinSCP o cualquier otro medio disponible. Nos logueamos con nuestro usuario y buscamos el archivo. Vamos a la carpeta /srv y luego buscamos la carpeta donde OMV ha montado nuestro disco, y dentro estarán las carpetas de la VM. En mi caso es /srv/dev-disk-by-uuid-744de.../kvm/pool/nextcloud.qcow2. Copiamos el archivo mediante WinSCV a golpe de ratón en nuestro PC y listo.


    El archivo de configuración de la VM normalmente está en /etc/libvirt/qemu/nextcloud.xml, ha recibido el mismo nombre que la VM y tiene extensión ".XML". Si no estuviera allí podemos utilizar el buscador de WinSCP mediante el parámetro "nextcloud*.*" por ejemplo y lo localizaremos rápidamente. Hacemos una copia y la guardamos junto al archivo anterior que contiene la VM.


    Nota: Este archivo XML está en texto plano, es editable con cualquier editor de texto. Contiene los parámetros de configuración de la VM y se puede modificar a voluntad con el conocimiento suficiente. Se puede encontrar mucha información en internet sobre esto.


    Estos dos archivos son nuestra copia de seguridad de la VM para poder reutilizarla en cualquier momento y arrancar desde un sistema limpio de Ubuntu fácilmente sin pasar por todo el proceso de instalación.



    4.2 Restaurar copia de seguridad de VM



    Apagamos la VM


    Sustituimos el archivo "[nombre-VM].qcow2" que contiene la VM en su ubicación original (ver el punto anterior "4.1 Copia de seguridad de VM").


    Establecemos permisos en 0600 (lectura y escritura para root) con winSCP pulsando en propiedades del archivo o desde línea de comandos.


    Sustituimos el archivo de configuración "[nombre-VM].XML" existente en su ubicación original (ver el punto anterior "4.1 Copia de seguridad de VM"), normalmente es /etc/libvirt/qemu/, por el de nuestra copia de seguridad.


    Establecemos permisos en 0600 (lectura y escritura para root) con winSCP pulsando en propiedades del archivo o desde línea de comandos.


    Iniciamos la VM y la tendremos en el estado en que se hizo la copia.



    4.3 Duplicado de VM



    Lo primero que necesitamos es una copia de seguridad, ver el punto "4.1 Copia de seguridad de VM".


    Editamos el archivo "[nombre-VM].XML" con cualquier editor de texto y cambiamos el nombre de la VM en todas las líneas que aparece por "[nombre-VM-duplicado]" o por el que queramos. Atención: Este nombre no puede ser igual que ninguna VM que ya tengamos y no puede contener espacios.


    Renombramos el archivo "[nombre-VM].qcow2" como "[nombre-VM-duplicado].qcow2".


    Renombramos el archivo "[nombre-VM].XML" como "[nombre-VM-duplicado].XML".


    Creamos una VM según el proceso detallado en el punto "2.2 Creación de la VM en la GUI de OMV" y con el nombre que le hemos dado a nuestro duplicado [nombre-VM-duplicado].


    Cuando finalicemos tendremos dos archivos recién creados en sus ubicaciones correspondientes con el nombre [nombre-VM-duplicado]. Los sustituimos por los correspondientes a nuestra copia de seguridad siguiendo el mismo procedimiento que en el punto "4.2 Restauración de VM".


    Para evitar conflictos de IP es conveniente apagar antes la VM original, después iniciamos la VM duplicada le asignamos la IP que nos interese siguiendo el procedimiento descrito en "3.3 Configuración de red. IP fija", y ya podemos volver a iniciar la VM original.


    (continúa en el siguiente post)

    • Offizieller Beitrag

    5. INSTALACION Y CONFIGURACION DE NEXTCLOUD SERVER EN UBUNTU 20.04 LTS MEDIANTE SNAP



    Puedes elegir esta instalación o la instalación manual en el sistema, descrita en el punto 6. La instalación de snap es más sencilla y recomendable para usuarios menos avanzados en linux. Si prefieres la instalación tradicional con LAMP puedes ir al punto 6.


    La instalación mediante snap está disponible en Ubuntu de forma predeterminada, es un sistema de contenedor de software autoinstalable, junto con todas sus dependencias y configuraciones asociadas, en una unidad autocontenida con actualizaciones automáticas. Una de las ventajas de esta instalación es el sistema de comandos que integra para facilitar aún más la configuración inicial.



    5.1 Instalación del snap Nextcloud Server en Ubuntu 20.04 LTS



    Si dispones de interfaz gráfica puedes ir a Ubuntu Software, en el buscador localizamos "Nextcloud Server" y le damos a instalar, así de fácil, ya lo tienes instalado y solo te falta configurarlo. Si ya lo has hecho pasa al punto 5.2 (o sigue leyendo si tienes curiosidad).


    Desde Ubuntu Server primero instalamos snap tecleando en terminal lo siguiente:

    sudo apt update

    sudo apt upgrade

    sudo apt install snapd

    y ahora ya podemos instalar el snap de Nextcloud tecleando:


    sudo snap install nextcloud


    Podemos comprobar la correcta instalación tecleando:


    snap changes nextcloud


    Nos dará una salida similar a esta:


    Code
    ID   Status  Spawn               Ready               Summary
    2    Done    today at 16:12 UTC  today at 16:12 UTC  Install "nextcloud" snap


    El estado y el resumen indican que la instalación se completó sin problemas.



    5.2 Configuración inicial del snap Nextcloud Server en Ubuntu 20.04 LTS



    El sistema de snap nos ofrece la ventaja de disponer de los comandos de configuración de snap. Esto agiliza mucho la configuración. Podemos ver una lista de ellos tecleando en terminal:


    snap info nextcloud


    Para iniciar la configuración de Nextcloud hemos de introducir nuestro usuario administrador y contraseña de Nextcloud tecleando:


    sudo nextcloud.manual-install [nombre-usuario] [contraseña]


    Tardará un poco en configurarse, cuando termine aparecerá de nuevo el cursor.


    El siguiente paso es ajustar los dominios de confianza de Nextcloud. El dominio (o IP pública fija en su caso) que escribamos en la barra del navegador para acceder a Nextcloud, debe estar incluido en el registro de dominios autorizados para acceder. En caso contrario el sistema nos impedirá el acceso. Por defecto localhost está activado, esto significa que podremos entrar mediante la dirección IP siempre que estemos conectados desde la misma red.


    Para ver la lista de dominios autorizados podemos teclear en cualquier momento la siguiente orden:


    sudo nextcloud.occ config:system:get trusted_domains


    Nos aparece en pantalla una lista donde únicamente está autorizado localhost. Si disponemos de un dominio (o tenemos una IP fija en nuestro router aunque no tengamos dominio) procedemos a agregar dicha dirección de la siguiente manera:


    sudo nextcloud.occ config:system:set trusted_domains 1 --value=[mi-dominio.com]:[mi-puerto]


    donde


    [mi-dominio.com] es el dominio que queramos autorizar o nuestra dirección IP pública fija del acceso a nuestra red.

    [mi-puerto] es el puerto que podemos configurar opcionalmente en nuestro router para acceder desde el exterior y que redirigirá el tráfico a este host


    Podemos ejecutar de nuevo el comando anterior y vemos que ahora tenemos localhost y el dominio que hemos definido:


    sudo nextcloud.occ config:system:get trusted_domains


    Nextcloud ha asignado a localhost el valor 0 y al dominio que acabamos de definir el valor 1. Si queremos agregar otro tendremos que cambiar el valor 1 por un 2 y sería el tercer dominio definido. Podemos modificar el que acabamos de crear definiendo de nuevo el valor 1 y sobreescribirá el dominio que tenemos en esa línea. Podemos crear todas entradas que queramos incrementando ese valor cada vez.


    Si queremos definir puertos personalizados para acceder a Nextcloud lo podemos hacer mediante el siguiente comando:


    sudo snap set nextcloud ports.http=[mi-puerto-http] ports.https=[mi-puerto-https]


    Nota: Recuerda que si lo haces tendrás que escribir siempre ese puerto a continuación de la IP para acceder a Nextcloud en el navegador.


    Si hemos definido puertos personalizados debemos reiniciar el servidor apache para que reconozca estos cambios, tecleando:


    sudo systemctl restart snap.nextcloud.apache.service


    Ya puedes acceder a Nextcloud si quieres escribiendo la IP de tu servidor en un navegador pero no dejes de leer el siguiente punto de la guía.


    Nota: Tal vez tu sistema de red te impida acceder desde localhost, puedes resolver esto añadiendo tu IP de acceso a los dominios de confianza.


    sudo nextcloud.occ config:system:set trusted_domains 1 --value=[tu-IP]


    siendo [tu-IP] la dirección IP con la que accedes a tuservidor de Nextcloud.



    5.3 Instalación de Certificado para navegación segura HTTPS en snap de Nextcloud.



    El siguiente paso es instalar un Certificado para acceder a Nextcloud mediante una conexión segura (https). Existen dos tipos de certificados, firmados por una entidad certificadora autorizada o autofirmados. Con los dos se puede acceder de manera segura y cifrada indistintamente.


    Si instalas un Certificado autofirmado, los navegadores no reconocen el certificado autofirmado pero solo es un incoveniente si accede alguien que no eres tú. La primera vez que accedas a la web el navegador dará un error de certificado, pulsa en "avanzado" y "acceder a la página web". El certificado es tuyo así que puedes confiar en él. La siguiente vez que accedas ya no dará ese error, aunque seguirá saliendo una advertencia en la barra de navegación.


    Si instalas un Certificado firmado por una entidad certificadora autorizada la conexión será reconocida por cualquier navegador sin complicaciones. El navegador lo reconoce y se establece la conexión sin adevertencias.


    Si no dispones de un dominio (es aconsejable comprar uno, son baratos y fáciles de configurar), tendrás que instalar un Certificado autofirmado.


    Si dispones de un dominio puedes instalar un Certificado firmado por una entidad certificadora. Un Certificado de este tipo se puede comprar o puede ser uno gratuito de Let's Encrypt. Los certificados de Let's Encrypt caducan a los 90 dias y hay que renovarlos. Hay formas de instalarlos de manera que se autorrenueven automáticamente, mediante el paquete "certbot", dependiendo de tu configuración de red, o mediante tu servicio de dominio si lo ofrece. Generalmente necesitas tener abiertos los puertos 80 y 443 para configurar esto. Aquí voy a explicar una manera sencilla de instalarlo y renovarlo manualmente. Hay otras muchas formas de hacerlo.



    Instalación de certificado Let's Encrypt desde snap:


    Si dispones de un dominio y no has variado los puertos y tienes la posibilidad de abrir los puertos 80 y 443 en tu router puedes configurar el Certificado Let's Encrypt directamente con el siguiente comando:


    sudo nextcloud.enable-https lets-encrypt


    y ya tendrás tu certificado instalado.



    Instalación de certificado autofirmado y/o Let's encrypt manual:


    Si has variado los puertos de acceso a Nextcloud o no puedes abrir los puertos 80 y 443 en tu router, el proceso más sencillo es instalar un certificado autofirmado y luego sustituirlo manualmente por un Certificado Let's Encrypt. De esta forma evitaremos esos problemas de puertos. A continuación explico como hacerlo.


    Para instalar un Certificado autofirmado tecleamos lo siguiente:


    sudo nextcloud.enable-https self-signed


    En este momento en Nextcloud ya estamos utilizando un Certificado autofirmado. Si no dispones de un dominio ya has terminado tu configuración de Nextcloud. Puedes dirigirte a tu navegador favorito, escribir tu dirección de acceso y escribir usuario y contraseña. Recuerda abrir puertos en tu router y disfruta de Nextcloud.


    Si quieres sustituir el Certificado autofirmado por un Certificado Let's Encrypt manualmente sigue leyendo.


    (continúa en el siguiente post)

    • Offizieller Beitrag

    5.4 Sustitución manual de certificado autofirmado por certificado Let's Encrypt en snap de Nextcloud.



    Una vez instalado el certificado autofirmado (ver punto 5.3) lo siguiente que necesitas es generar los certificados en web, hay muchas maneras de hacerlo, por ejemplo en http://www.zerossl.com, y descargarlos. Si lo haces en esta web, los archivos que descargues se corresponden con los que usa Nextcloud de la siguiente manera:


    Tipo de Certificado Certificados de zerossl Certificados que utiliza Nextcloud


    Dominio certificate.crt cert.pem -rw-r--r--

    Entidad intermedia ca_bundle.crt chain.pem -rw-r--r--

    clave privada private.key privkey.pem -rw-r--r--


    De modo que cambiamos los nombres a nuestros archivos para que coincidan con los que hay en Nextcloud, y los copiamos en nuestra home de ubuntu en una carpeta que llamamos "certificados", mediante línea de comandos o en la interfaz gráfica.


    Los certificados que vamos a sustituir están en la carpeta /var/snap/nextcloud/current/certs/live/. Para acceder debemos loguearnos como root, en una terminal escribimos:


    sudo su


    nos vamos a la carpeta donde están los certificados autofirmados y comprobamos que efectivamente están ahí:

    cd /var/snap/nextcloud/current/certs/live/

    ls -l

    los eliminamos y comprobamos que ya no están:

    rm *.pem

    ls -l

    y copiamos nuestros certificados de la carpeta home, comprobándolo después:

    cp /home/[mi-usuario]/certificados/*.pem .

    ls -l

    ya solo queda instalarlos y configurarlos en el servidor


    sudo nextcloud.enable-https custom -s cert.pem privkey.pem chain.pem


    Y ya tenemos nuestros certificados configurados. Estos certificados caducan a los 90 dias, así que habrá que repetir este proceso en ese momento. Ya puedes dirigirte a tu navegador, ingresar la dirección de tu dominio y disfrutar de Nextcloud. Recuerda abrir puertos en tu router.


    (continúa en el siguiente post)

    • Offizieller Beitrag

    6. INSTALACION Y CONFIGURACION MANUAL DE NEXTCLOUD SERVER 22 EN UBUNTU 20.04 LTS. USUARIOS AVANZADOS.



    Si eres un usuario poco familiarizado con linux es recomendable que hagas una instalación mediante snap siguiendo el punto 5. de esta guía. Si eres un usuario avanzado continúa si quieres.


    La instalación manual consiste en la instalación y configuración previa manualmente de la base de datos y el servidor apache en Ubuntu. Posteriormente se instala Nextcloud y se integra directamente en el sistema operativo.


    Para hacerlo seguimos el procedimiento descrito en la documentación de Nextcloud, ver aquí



    6.1 Instalación de Apache y MySQL



    Lo primero que debemos hacer es instalar los paquetes de mariadb y apache tecleando:

    sudo apt update

    sudo apt-get install apache2 mysql-server -y

    y los iniciamos tecleando:

    sudo systemctl start apache2

    sudo systemctl enable apache2

    sudo systemctl start mysql

    sudo systemctl enable mysql

    Instalamos dependencias tecleando:


    sudo apt-get install php zip libapache2-mod-php php-gd php-json php-mysql php-curl php-mbstring php-intl php-imagick php-xml php-zip php-mysql php-bcmath php-gmp zip -y


    Antes de utilizar MySQL, es importante securizarlo. Tecleamos:


    sudo mysql_secure_installation


    Contestamos a las preguntas afirmativamente y establecemos una contraseña. A continuación nos conectamos a la base de datos y la configuramos tecleando:


    sudo mysql -u root -p


    Introducimos la contraseña que establecimos en el paso anterior, creamos la base de datos llamada “nextcloud“, el usuario “nextcloud” y su contraseña, y le damos privilegios sobre la base de datos recién creada, mediante los siguientes comandos:

    CREATE DATABASE nextcloud;

    CREATE USER 'nextcloud'@'localhost' IDENTIFIED BY '[mi-contraseña]';

    GRANT ALL PRIVILEGES ON nextcloud.* TO 'nextcloud'@'localhost';

    FLUSH PRIVILEGES;

    quit

    donde [mi-contraseña] es la contraseña fuerte que le otorgamos al usuario nextcloud.



    6.2 Instalación de Nextcloud 22



    En este momento ya se puede iniciar la instalación de Nextcloud, la versión actual es la 22. El link de descarga lo copiamos de la página oficial de descargas de Nexcloud aquí https://nextcloud.com/install/#instructions-server, pinchamos con el botón derecho en el link de descarga y lo copiamos. Descargamos y descomprimimos la aplicación al directorio donde lo queremos instalar:

    wget https://download.nextcloud.com/server/releases/nextcloud-22.0.0.zip

    unzip nextcloud-22.0.0.zip

    sudo mv nextcloud /var/www/html/

    Cambiamos el propietario del directorio nextcloud recién creado y se lo damos al usuario www-data:


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



    6.3 Configuración de Apache



    La configuración de Apache en Ubuntu requiere la creación de un único archivo de configuración para Nextcloud que será /etc/apache2/sites-available/nextcloud.conf. Lo creamos con el comando:


    sudo nano /etc/apache2/sites-available/nextcloud.conf


    En ese archivo, copiamos lo siguiente:


    Code
    Alias /nextcloud "/var/www/html/nextcloud/"
    <Directory /var/www/html/nextcloud/>
        Options +FollowSymlinks
        AllowOverride All
          <IfModule mod_dav.c>
            Dav off
          </IfModule>
         SetEnv HOME /var/www/html/nextcloud
        SetEnv HTTP_HOME /var/www/html/nextcloud
    </Directory>


    Salimos mediante ctrl+x guardando los cambios.


    Habilitamos el nuevo sitio tecleando:

    sudo systemctl reload apache2

    sudo a2ensite nextcloud

    Habilitamos los módulos de Apache necesarios:


    sudo a2enmod rewrite headers env dir mime


    Cambiamos el límite de memoria de PHP:


    sudo sed -i '/^memory_limit =/s/=.*/= 512M/' /etc/php/7.4/apache2/php.ini


    Nota: Si tu versión de PHP es diferente a la 7.4, deberás modificar el comando anterior en consecuencia.


    Reiniciamos Apache:


    sudo systemctl restart apache2



    6.4 Inicio de Nextcloud



    Ya podemos iniciar Nextcloud, abrimos un navegador vamos a http://[tu-IP]/nextcloud (donde [tu-IP] es la dirección IP o el dominio). En el cuadro de diálogo introducimos un nombre de usuario administrador para Nextcloud con su correspondiente contraseña, y completamos el resto de información tal como sigue:


    Usuario de la base de datos: nextcloud

    Contraseña de la base de datos: la contraseña que creamos para el usuario de la base de datos de nextcloud

    Nombre de la base de datos: nextcloud


    Pulsamos en "Finalizar instalación" y ya estamos dentro de Nextcloud con el usuario administrador que acabmos de crear.


    Solo te falta añadir el Certificado que utilices para acceder a tu Nextcloud. Recuerda abrir puertos y disfruta de tu Nextcloud.

  • chente

    Hat den Titel des Themas von „[HOW TO] INSTALL NEXTCLOUD ON A VM UBUNTU 20.04 VIRTUALIZED WITH KVM IN OMV“ zu „[How to] Install Nextcloud on a VM Ubuntu 20.04 virtualized with KVM in OMV“ geändert.

Jetzt mitmachen!

Sie haben noch kein Benutzerkonto auf unserer Seite? Registrieren Sie sich kostenlos und nehmen Sie an unserer Community teil!