One place for hosting & domains

      Webserver

      So installieren Sie den Apache Webserver unter CentOS 8


      Einführung

      Der Apache-HTTP-Server ist der am häufigsten verwendete Webserver der Welt. Er bietet viele leistungsstarke Funktionen, darunter dynamisch ladbare Module, robuste Medienunterstützung und eine umfassende Integration mit anderer gängiger Software.

      In diesem Leitfaden installieren Sie einen Apache-Webserver mit virtuellen Hosts auf Ihrem CentOS 8-Server.

      Voraussetzungen

      Zur Absolvierung dieses Leitfadens benötigen Sie Folgendes:

      Schritt 1 — Installieren von Apache

      Apache ist in den Standard-Software-Repositorys von CentOS verfügbar und kann mit dem dnf-Paketmanager installiert werden.

      Installieren Sie das Apache-Paket als der non-root sudo user, der in den Voraussetzungen konfiguriert wurde:

      Nach der Bestätigung der Installation installiert dnf Apache und alle erforderlichen Abhängigkeiten.

      Wenn Sie dem im Abschnitt Voraussetzungen erwähnten Schritt 4 des Leitfadens Ersteinrichtung des Servers unter CentOS 8 gefolgt sind, haben Sie bereits firewalld auf Ihrem Server installiert, um Anforderungen über HTTP zu bedienen.

      Wenn Sie Apache so konfigurieren möchten, dass er auch Inhalte über HTTPS bedient, sollten Sie zudem Port 443 öffnen, indem Sie den https-Dienst aktivieren:

      • sudo firewall-cmd --permanent --add-service=https

      Laden Sie als Nächstes die Firewall neu, um diese neuen Regeln anzuwenden:

      • sudo firewall-cmd --reload

      Nach dem Neuladen der Firewall können Sie den Dienst starten und den Webserver überprüfen.

      Schritt 2 — Prüfen Ihres Webservers

      Apache startet beim Abschluss der Installation nicht automatisch auf CentOS, sodass Sie den Apache-Prozess manuell starten müssen:

      • sudo systemctl start httpd

      Überprüfen Sie mit dem folgenden Befehl, ob der Dienst ausgeführt wird:

      • sudo systemctl status httpd

      Wenn der Dienst ausgeführt wird, erhalten Sie einen active-Status:

      Output

      ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disa> Active: active (running) since Thu 2020-04-23 22:25:33 UTC; 11s ago Docs: man:httpd.service(8) Main PID: 14219 (httpd) Status: "Running, listening on: port 80" Tasks: 213 (limit: 5059) Memory: 24.9M CGroup: /system.slice/httpd.service ├─14219 /usr/sbin/httpd -DFOREGROUND ├─14220 /usr/sbin/httpd -DFOREGROUND ├─14221 /usr/sbin/httpd -DFOREGROUND ├─14222 /usr/sbin/httpd -DFOREGROUND └─14223 /usr/sbin/httpd -DFOREGROUND ...

      Die Ausgabe zeigt an, dass der Dienst erfolgreich gestartet wurde. Der beste Weg, dies zu testen, besteht jedoch darin, eine Seite von Apache anzufordern.

      Sie können auf die Standardstartseite von Apache zugreifen, um zu bestätigen, dass die Software ordnungsgemäß über Ihre IP-Adresse ausgeführt wird. Wenn Sie die IP-Adresse Ihres Servers nicht kennen, können Sie sie von der Befehlszeile auf verschiedene Arten abrufen.

      Geben Sie q ein, um zur Eingabeaufforderung zurückzukehren, und geben Sie dann Folgendes ein:

      Dieser Befehl zeigt alle Netzwerkadressen des Hosts an, wodurch Sie einige IP-Adressen erhalten, die durch Leerzeichen getrennt sind. Sie können jede in Ihrem Webbrowser ausprobieren, um zu sehen, ob sie funktionieren.

      Alternativ können Sie curl verwenden, um Ihre IP von icanhazip.com anzufordern. Dadurch erhalten Sie Ihre öffentliche IPv4-Adresse, wie sie von einem anderen Ort im Internet gelesen wird:

      Wenn Sie über die IP-Adresse Ihres Servers verfügen, geben Sie sie in die Adressleiste Ihres Browsers ein:

      http://your_server_ip
      

      Sie sehen dann die Standardwebsite von CentOS 8 Apache:

      Standardseite Apache für CentOS 8

      Diese Seite zeigt an, dass Apache richtig funktioniert. Sie enthält auch einige grundlegende Informationen zu wichtigen Apache-Dateien und Verzeichnispositionen.

      Schritt 3 — Verwalten des Apache-Prozesses

      Nachdem der Dienst nun installiert ist und ausgeführt wird, können Sie jetzt verschiedene systemctl-Befehle verwenden, um den Dienst zu verwalten.

      Um Ihren Webserver anzuhalten, geben Sie Folgendes ein:

      • sudo systemctl stop httpd

      Um den Webserver zu starten, wenn er angehalten wurde, geben Sie Folgendes ein:

      • sudo systemctl start httpd

      Um den Dienst anzuhalten und erneut zu starten, geben Sie Folgendes ein:

      • sudo systemctl restart httpd

      Wenn Sie nur Konfigurationsänderungen vornehmen, kann Apache oft neu geladen werden, ohne Verbindungen zu trennen. Dazu verwenden Sie diesen Befehl:

      • sudo systemctl reload httpd

      Standardmäßig ist Apache so konfiguriert, dass er beim Booten des Servers automatisch startet. Wenn Sie dieses Verhalten nicht wünschen, können Sie es durch folgende Eingabe deaktivieren:

      • sudo systemctl disable httpd

      Geben Sie Folgendes ein, um den Dienst beim Booten wieder zu aktivieren:

      • sudo systemctl enable httpd

      Apache wird jetzt automatisch gestartet, wenn der Server erneut gebootet wird.

      Die Standardkonfiguration für Apache ermöglicht Ihrem Server, eine einzelne Website zu hosten. Wenn Sie mehrere Domänen auf Ihrem Server hosten möchten, müssen Sie virtuelle Hosts auf Ihrem Apache-Webserver konfigurieren.

      Schritt 4 — Einrichten eines virtuellen Hosts (Empfohlen)

      Bei Verwendung des Apache-Webservers können Sie virtuelle Hosts verwenden (diese sind ähnlich wie Serverblocks in Nginx), um Konfigurationsdetails einzuschließen und mehr als eine Domäne auf einem einzelnen Server zu hosten. In diesem Schritt richten wir eine Domäne namens example.com ein, aber Sie sollten diesen Namen durch Ihren eigenen Domänennamen ersetzen. Wenn Sie mit DigitalOcean einen Domänennamen einrichten, lesen Sie bitte unsere Netzwerkdokumentation.

      Apache unter CentOS 8 hat einen virtuellen Host, der standardmäßig aktiviert und so konfiguriert ist, dass er Dokumente aus dem /var/www/html-Verzeichnis bereitstellt. Das eignet sich gut für eine Site, kann aber umständlich werden, wenn Sie mehrere Sites hosten. Statt /var/www/html zu ändern, erstellen Sie eine Verzeichnisstruktur innerhalb von /var/www für die Site example.com und lassen dabei /var/www/html als Standardverzeichnis stehen, das bereitgestellt wird, wenn eine Client-Anforderung keine übereinstimmenden Sites hat.

      Erstellen Sie das html-Verzeichnis für example.com wie folgt und verwenden Sie das -p-Flag, um alle notwendigen übergeordneten Verzeichnisse zu erstellen:

      • sudo mkdir -p /var/www/example.com/html

      Erstellen Sie ein zusätzliches Verzeichnis, um Protokolldateien für die Site zu speichern:

      • sudo mkdir -p /var/www/example.com/log

      Weisen Sie als Nächstes das Eigentum am html-Verzeichnis mit der Umgebungsvariablen $USER zu:

      • sudo chown -R $USER:$USER /var/www/example.com/html

      Stellen Sie sicher, dass Ihre Webroot über die Standardberechtigungen verfügt:

      • sudo chmod -R 755 /var/www

      Erstellen Sie als Nächstes eine index.html-Seite durch die Verwendung von vi oder Ihrem bevorzugten Texteditor:

      • sudo vi /var/www/example.com/html/index.html

      Drücken Sie i, um zum INSERT-Modus zu wechseln, und fügen Sie der Datei folgende Beispiel-HTML hinzu:

      /var/www/example.com/html/index.html

      <html>
        <head>
          <title>Welcome to Example.com!</title>
        </head>
        <body>
          <h1>Success! The example.com virtual host is working!</h1>
        </body>
      </html>
      

      Speichern und schließen Sie die Datei, indem Sie ESC drücken, :wq eingeben und ENTER drücken.

      Mit dem fertig erstellten Siteverzeichnis und der Beispiel-Indexdatei sind Sie nun fast bereit, die virtuellen Host-Dateien zu erstellen. Virtuelle Host-Dateien legen die Konfiguration Ihrer einzelnen Sites fest und weisen den Apache-Webserver an, wie er auf verschiedene Domänenanforderungen reagieren soll.

      Vor der Erstellung Ihrer virtuellen Hosts müssen Sie ein sites-available-Verzeichnis erstellen, in der diese gespeichert werden. Sie erstellen auch ein sites-enabled-Verzeichnis, welches Apache anweist, dass ein virtueller Host verfügbar ist, um Besucher zu bedienen. Das sites-enabled-Verzeichnis enthält symbolische Links zu virtuellen Hosts, die wir veröffentlichen möchten. Erstellen Sie beide Verzeichnisse mit dem folgenden Befehl:

      • sudo mkdir /etc/httpd/sites-available /etc/httpd/sites-enabled

      Als Nächstes weisen Sie Apache an, im sites-enabled-Verzeichnis nach virtuellen Hosts zu suchen. Bearbeiten Sie dazu die Hauptkonfigurationsdatei von Apache mit vi oder Ihrem bevorzugten Texteditor und fügen Sie eine Zeile hinzu, die ein optionales Verzeichnis für zusätzliche Konfigurationsdateien deklariert:

      • sudo vi /etc/httpd/conf/httpd.conf

      Drücken Sie den Großbuchstaben G, um zum Ende der Datei zu navigieren. Drücken Sie dann i, um zum INSERT-Modus zu wechseln, und fügen Sie die folgende Zeile am Ende der Datei hinzu:

      /etc/httpd/conf/httpd.conf

      ...
      # Supplemental configuration
      #
      # Load config files in the "/etc/httpd/conf.d" directory, if any.
      IncludeOptional conf.d/*.conf
      IncludeOptional sites-enabled/*.conf
      

      Nach dem Hinzufügen der Zeile speichern und schließen Sie die Datei. Nachdem Sie nun die virtuellen Host-Verzeichnisse eingerichtet haben, erstellen Sie die virtuelle Host-Datei.

      Zuerst erstellen Sie eine neue Datei im sites-available-Verzeichnis:

      • sudo vi /etc/httpd/sites-available/example.com.conf

      Fügen Sie folgenden Konfigurationsblock hinzu und ändern Sie example.com auf Ihren Domänennamen:

      /etc/httpd/sites-available/example.com.conf

      <VirtualHost *:80>
          ServerName www.example.com
          ServerAlias example.com
          DocumentRoot /var/www/example.com/html
          ErrorLog /var/www/example.com/log/error.log
          CustomLog /var/www/example.com/log/requests.log combined
      </VirtualHost>
      

      Hierdurch wird Apache mitgeteilt, wo das Rootverzeichnis mit den öffentlich zugänglichen Webdokumenten zu finden ist. Außerdem wird Apache angewiesen, wo die Fehler- und Anforderungsprotokolle für die jeweilige Site zu speichern sind.

      Wenn Sie fertig sind, speichern und schließen Sie die Datei.

      Die virtuellen Host-Dateien sind nun erstellt und können aktiviert werden, damit Apache sie für Besucher bereitstellen kann. Erstellen Sie hierzu einen symbolischen Link für jeden virtuellen Host im sites-enabled-Verzeichnis:

      • sudo ln -s /etc/httpd/sites-available/example.com.conf /etc/httpd/sites-enabled/example.com.conf

      Ihr virtueller Host ist nun konfiguriert und bereit, Inhalte bereitzustellen. Vor dem Neustart des Apache-Dienstes prüfen wir, ob SELinux über die richtigen Richtlinien für Ihre virtuellen Hosts verfügt.

      Schritt 5 — Anpassen von SELinux-Berechtigungen für virtuelle Hosts (empfohlen)

      SELinux ist ein Sicherheitsmodul des Linux-Kernels, das eine höhere Sicherheit für Linux-Systeme bietet. CentOS 8 ist mit SELinux ausgestattet und konfiguriert, um mit der Apache-Konfiguration zu arbeiten. Da Sie durch Einrichten eines benutzerdefinierten Protokollverzeichnisses in der Konfigurationsdatei der virtuellen Hosts die Standardkonfiguration geändert haben, erhalten Sie beim Versuch, den Apache-Dienst zu starten, eine Fehlermeldung. Zur Lösung des Problems müssen Sie die Richtlinien von SELinux aktualisieren, damit Apache in die erforderlichen Dateien schreiben kann.

      Es gibt verschiedene Möglichkeiten, Richtlinien entsprechend den Anforderungen Ihrer Umgebung festzulegen, da SELinux Ihnen die Möglichkeit bietet, Ihre Sicherheitsstufe anzupassen. Dieser Schritt behandelt zwei Methoden zur Anpassung der Richtlinien von Apache: universell und in einem bestimmten Verzeichnis. Da es sicherer ist, Richtlinien von Verzeichnissen anzupassen, wird dieser Ansatz empfohlen.

      Universelles Anpassen der Apache-Richtlinien

      Wenn die Apache-Richtlinien universell festgelegt werden, wird SELinux angewiesen, alle Apache-Prozesse mit dem booleschen Argument httpd_unified identisch zu behandeln. Dieser Ansatz ist zwar bequemer, gibt Ihnen aber nicht das gleiche Maß an Kontrolle wie ein Ansatz, der sich auf eine Datei- oder Verzeichnisrichtlinie konzentriert.

      Führen Sie den folgenden Befehl aus, um universelle Apache-Richtlinien festzulegen:

      • sudo setsebool -P httpd_unified 1

      Der Befehl setsebool ändert boolesche SELinux-Werte. Das -P-Flag aktualisiert den Bootzeitwert, sodass diese Änderung auch bei Neustarts erhalten bleibt. httpd_unified ist das boolesche Argument, das SELinux anweist, alle Apache-Prozesse als den gleichen Typ zu behandeln. Sie haben es mit dem Wert von 1 aktiviert.

      Anpassen von Apache-Richtlinien in einem Verzeichnis

      Das individuelle Einrichten von SELinux-Berechtigungen für das Verzeichnis /var/www/example.com/log gibt Ihnen mehr Kontrolle über die Apache-Richtlinien, kann aber wartungsintensiver sein. Da es sich bei dieser Option nicht um eine universelle Festlegung von Richtlinien handelt, müssen Sie den Kontexttyp für alle neuen Protokollverzeichnisse, die in Ihren virtuellen Host-Konfigurationen angegeben sind, manuell festlegen.

      Überprüfen Sie zunächst den Kontexttyp, den SELinux dem Verzeichnis /var/www/example.com/log gegeben hat:

      • sudo ls -dlZ /var/www/example.com/log/

      Dieser Befehl listet den SELinux-Kontext des Verzeichnisses auf und gibt ihn aus. Sie werden eine Ausgabe sehen, die etwa folgendermaßen aussieht:

      Output

      drwxr-xr-x. 2 root root unconfined_u:object_r:httpd_sys_content_t:s0 6 Apr 23 23:51 /var/www/example.com/log/

      Der aktuelle Kontext ist httpd_sys_content_t, der SELinux mitteilt, dass der Apache-Prozess nur Dateien lesen kann, die in diesem Verzeichnis erstellt wurden. In diesem Leitfaden ändern Sie den Kontexttyp des Verzeichnisses /var/www/example.com/log zu httpd_log_t. Dieser Typ ermöglicht Apache, Protokolldateien von Web-Anwendungen zu generieren und an diese anzuhängen:

      • sudo semanage fcontext -a -t httpd_log_t "/var/www/example.com/log(/.*)?"

      Verwenden Sie als Nächstes den Befehl restorecon, um diese Änderungen anzuwenden und sie bei Neustarts beizubehalten:

      • sudo restorecon -R -v /var/www/example.com/log

      Das Flag -R führt diesen Befehl rekursiv aus. Das bedeutet, dass alle vorhandenen Dateien aktualisiert werden, um den neuen Kontext zu verwenden. Das Flag -v gibt die Kontextänderungen aus, die der Befehl vorgenommen hat. Sie erhalten die folgende Ausgabe, die die Änderungen bestätigt:

      Output

      Relabeled /var/www/example.com/log from unconfined_u:object_r:httpd_sys_content_t:s0 to unconfined_u:object_r:httpd_log_t:s0

      Sie können die Kontexte erneut auflisten, um die Änderungen zu sehen:

      • sudo ls -dlZ /var/www/example.com/log/

      Die Ausgabe zeigt den aktualisierten Kontexttyp an:

      Output

      drwxr-xr-x. 2 root root unconfined_u:object_r:httpd_log_t:s0 6 Apr 23 23:51 /var/www/example.com/log/

      Das Verzeichnis /var/www/example.com/log verwendet nun den Typ httpd_log_t​​​​​​ und Sie können jetzt die Konfiguration des virtuellen Hosts testen.

      Schritt 6 — Testen des virtuellen Hosts (empfohlen)

      Sobald der SELinux-Kontext mit einer der beiden Methoden aktualisiert wurde, kann Apache in das Verzeichnis /var/www/example.com/log schreiben.  Sie können jetzt den Apache-Dienst erfolgreich neu starten:

      • sudo systemctl restart httpd

      Listen Sie den Inhalt des Verzeichnisses /var/www/example.com/log auf, um zu sehen, ob Apache die Protokolldateien erstellt hat:

      • ls -lZ /var/www/example.com/log

      Sie erhalten eine Bestätigung, dass Apache die in der Konfiguration des virtuellen Hosts angegebenen Dateien error.log und requests.log erstellen konnte:

      Output

      -rw-r--r--. 1 root root system_u:object_r:httpd_log_t:s0 0 Apr 24 00:06 error.log -rw-r--r--. 1 root root system_u:object_r:httpd_log_t:s0 0 Apr 24 00:06 requests.log

      Nachdem Sie nun Ihren virtuellen Host eingerichtet und die Berechtigungen von SELinux aktualisiert haben, stellt Apache Ihren Domänennamen bereit. Sie können dies testen, indem Sie zu http://example.com navigieren, wo Sie etwas Ähnliches sehen sollten wie:

      Erfolg!  Der virtuelle Host example.com funktioniert!

      Das bestätigt, dass Ihr virtueller Host erfolgreich konfiguriert ist und Inhalte bereitstellt. Wiederholen Sie die Schritte 4 und 5, um neue virtuelle Hosts mit SELinux-Berechtigungen für zusätzliche Domänen zu erstellen.

      Zusammenfassung

      In diesem Leitfaden haben Sie den Apache-Webserver installiert und verwaltet. Nachdem Sie Ihren Webserver nun installiert haben, haben Sie viele Möglichkeiten für die Art des Inhalts und die Technologien, die Sie verwenden möchten, um eine umfassendere Benutzererfahrung zu erzielen.

      Wenn Sie einen vollständigeren Anwendungsstapel erstellen möchten, lesen Sie den Artikel Konfigurieren eines LAMP-Stacks unter CentOS 8.



      Source link

      A Beginner's Guide to LXD: Setting Up an Apache Webserver In a Container


      Updated by Linode Contributed by Simos Xenitellis

      Access an Apache Web Server Inside a LXD Container

      What is LXD?

      LXD (pronounced “Lex-Dee”) is a system container manager build on top of LXC (Linux Containers) that is currently supported by Canonical. The goal of LXD is to provide an experience similar to a virtual machine but through containerization rather than hardware virtualization. Compared to Docker for delivering applications, LXD offers nearly full operating-system functionality with additional features such as snapshots, live migrations, and storage management.

      The main benefits of LXD are the support of high density containers and the performance it delivers compared to virtual machines. A computer with 2GB RAM can adequately support half a dozen containers. In addition, LXD officially supports the container images of major Linux distributions. We can choose the Linux distribution and version to run in the container.

      This guide covers how to install and setup LXD 3 on a Linode and how to setup an Apache Web server in a container.

      Note

      For simplicity, the term container is used throughout this guide to describe the LXD system containers.

      Before You Begin

      1. Complete the Getting Started guide. Select a Linode with at least 2GB of RAM memory, such as the Linode 2GB. Specify the Ubuntu 19.04 distribution. You may specify a different Linux distribution, as long as there is support for snap packages (snapd); see the More Information for more details.

      2. This guide will use sudo wherever necessary. Follow the Securing Your Server guide to create a limited (non-root) user account, harden SSH access, and remove unnecessary network services.

      3. Update your system:

        sudo apt update && sudo apt upgrade
        

      Configure the Snap Package Support

      LXD is available as a Debian package in the long-term support (LTS) versions of Ubuntu, such as Ubuntu 18.04 LTS. For other versions of Ubuntu and other distributions, LXD is available as a snap package. Snap packages are universal packages because there is a single package file that works on any supported Linux distributions. See the More Information section for more details on what a snap package is, what Linux distributions are supported, and how to set it up.

      1. Verify that snap support is installed correctly. The following command either shows that there are no snap packages installed, or that some are.

        snap list
        
          
        No snaps are installed yet. Try 'snap install hello-world'.
        
        
      2. View the details of the LXD snap package lxd. The output below shows that, currently, the latest version of LXD is 3.12 in the default stable channel. This channel is updated often with new features. There are also other channels such as the 3.0/stable channel which has the LTS LXD version (supported along with Ubuntu 18.04, until 2023) and the 2.0/stable channel (supported along with Ubuntu 16.04, until 2021). We will be using the latest version of LXD from the default stable channel.

        snap info lxd
        
          
        name:      lxd
        summary:   System container manager and API
        publisher: Canonical✓
        contact:   https://github.com/lxc/lxd/issues
        license:   Apache-2.0
        description: |
          **LXD is a system container manager**
        
          With LXD you can run hundreds of containers of a variety of Linux
          distributions, apply resource limits, pass in directories, USB devices
          or GPUs and setup any network and storage you want.
        
          LXD containers are lightweight, secure by default and a great
          alternative to running Linux virtual machines.
        
        
          **Run any Linux distribution you want**
        
          Pre-made images are available for Ubuntu, Alpine Linux, ArchLinux,
          CentOS, Debian, Fedora, Gentoo, OpenSUSE and more.
        
          A full list of available images can be [found
          here](https://images.linuxcontainers.org)
        
          Can't find the distribution you want? It's easy to make your own images
          too, either using our `distrobuilder` tool or by assembling your own image
          tarball by hand.
        
        
          **Containers at scale**
        
          LXD is network aware and all interactions go through a simple REST API,
          making it possible to remotely interact with containers on remote
          systems, copying and moving them as you wish.
        
          Want to go big? LXD also has built-in clustering support,
          letting you turn dozens of servers into one big LXD server.
        
        
          **Configuration options**
        
          Supported options for the LXD snap (`snap set lxd KEY=VALUE`):
           - criu.enable: Enable experimental live-migration support [default=false]
           - daemon.debug: Increases logging to debug level [default=false]
           - daemon.group: Group of users that can interact with LXD [default=lxd]
           - ceph.builtin: Use snap-specific ceph configuration [default=false]
           - openvswitch.builtin: Run a snap-specific OVS daemon [default=false]
        
          [Documentation](https://lxd.readthedocs.io)
        snap-id: J60k4JY0HppjwOjW8dZdYc8obXKxujRu
        channels:
          stable:        3.12        2019-04-16 (10601) 56MB -
          candidate:     3.12        2019-04-26 (10655) 56MB -
          beta:          ↑
          edge:          git-570aaa1 2019-04-27 (10674) 56MB -
          3.0/stable:    3.0.3       2018-11-26  (9663) 53MB -
          3.0/candidate: 3.0.3       2019-01-19  (9942) 53MB -
          3.0/beta:      ↑
          3.0/edge:      git-eaa62ce 2019-02-19 (10212) 53MB -
          2.0/stable:    2.0.11      2018-07-30  (8023) 28MB -
          2.0/candidate: 2.0.11      2018-07-27  (8023) 28MB -
          2.0/beta:      ↑
          2.0/edge:      git-c7c4cc8 2018-10-19  (9257) 26MB -
        
        
      3. Install the lxd snap package. Run the following command to install the snap package for LXD.

        sudo snap install lxd
        
          
        lxd 3.12 from Canonical✓ installed
        
        

      You can verify that the snap package has been installed by running snap list again. The core snap package is a prerequisite for any system with snap package support. When you install your first snap package, core is installed and shared among all other snap packages that will get installed in the future.

          snap list
      
      
        
      Name  Version  Rev    Tracking  Publisher   Notes
      core  16-2.38  6673   stable    canonical✓  core
      lxd   3.12     10601  stable    canonical✓  -
      
      

      Initialize LXD

      1. Add your non-root Unix user to the lxd group:

        sudo usermod -a -G lxd username
        

        Note

        By adding the non-root Unix user account to the lxd group, you are able to run any lxc commands without prepending sudo. Without this addition, you would have needed to prepend sudo to each lxc command.

      2. Start a new SSH session for the previous change to take effect. For example, log out and log in again.

      3. Verify the available free disk space:

        df -h /
        
          
        Filesystem      Size  Used Avail Use% Mounted on
        /dev/sda         49G  2.0G   45G   5% /
        
        

        In this case there is 45GB of free disk space. LXD requires at least 15GB of space for the storage needs of containers. We will allocate 15GB of space for LXD, leaving 30GB of free space for the needs of the server.

      4. Run lxd init to initialize LXD:

        sudo lxd init
        

        You will be prompted several times during the initialization process. Choose the defaults for all options.

          
        Would you like to use LXD clustering? (yes/no) [default=no]:
        Do you want to configure a new storage pool? (yes/no) [default=yes]:
        Name of the new storage pool [default=default]:
        Name of the storage backend to use (btrfs, ceph, dir, lvm, zfs) [default=zfs]:
        Create a new ZFS pool? (yes/no) [default=yes]:
        Would you like to use an existing block device? (yes/no) [default=no]:
        Size in GB of the new loop device (1GB minimum) [default=15GB]:
        Would you like to connect to a MAAS server? (yes/no) [default=no]:
        Would you like to create a new local network bridge? (yes/no) [default=yes]:
        What should the new bridge be called? [default=lxdbr0]:
        What IPv4 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]:
        What IPv6 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]:
        Would you like LXD to be available over the network? (yes/no) [default=no]:
        Would you like stale cached images to be updated automatically? (yes/no) [default=yes]
        Would you like a YAML "lxd init" preseed to be printed? (yes/no) [default=no]:
        
        

      Apache Web Server with LXD

      This section will create a container, install the Apache web server, and add the appropriate iptables rules in order to expose post 80.

      1. Launch a new container:

        lxc launch ubuntu:18.04 web
        
      2. Update the package list in the container.

        lxc exec web -- apt update
        
      3. Install the Apache in the LXD container.

        lxc exec web -- apt install apache2
        
      4. Get a shell in the LXD container.

        lxc exec web -- sudo --user ubuntu --login
        
      5. Edit the default web page for Apache to make a reference that it runs inside a LXD container.

        sudo nano /var/www/html/index.html
        

        Change the line It works! (line number 224) to It works inside a LXD container!. Then, save and exit.

      6. Exit back to the host. We have made all the necessary changes to the container.

        exit
        
      7. Add a LXD proxy device to redirect connections from the internet to port 80 (HTTP) on the server to port 80 at this container.

        sudo lxc config device add web myport80 proxy listen=tcp:0.0.0.0:80 connect=tcp:127.0.0.1:80
        

        Note

        In recent versions of LXD, you need to specify an IP address (such as 127.0.0.1) instead of a hostname (such as localhost). If your container already has a proxy device that uses hostnames, you can edit the container configuration to replace with IP addresses by running lxc config edit web.

      8. From your local computer, navigate to your Linode’s public IP address in a web browser. You should see the default Apache page:

        Web page of Apache server running in a container

      Common LXD Commands

      • List all containers:

        lxc list
        
          
        To start your first container, try: lxc launch ubuntu:18.04
        
        +------+-------+------+------+------+-----------+
        | NAME | STATE | IPV4 | IPV6 | TYPE | SNAPSHOTS |
        +------+-------+------+------+------+-----------+
        
        
      • List all available repositories of container images:

        lxc remote list
        
          
        +-----------------+------------------------------------------+---------------+-------------+--------+--------+
        |      NAME       |                   URL                    |   PROTOCOL    |  AUTH TYPE  | PUBLIC | STATIC |
        +-----------------+------------------------------------------+---------------+-------------+--------+--------+
        | images          | https://images.linuxcontainers.org       | simplestreams | none        | YES    | NO     |
        +-----------------+------------------------------------------+---------------+-------------+--------+--------+
        | local (default) | unix://                                  | lxd           | file access | NO     | YES    |
        +-----------------+------------------------------------------+---------------+-------------+--------+--------+
        | ubuntu          | https://cloud-images.ubuntu.com/releases | simplestreams | none        | YES    | YES    |
        +-----------------+------------------------------------------+---------------+-------------+--------+--------+
        | ubuntu-daily    | https://cloud-images.ubuntu.com/daily    | simplestreams | none        | YES    | YES    |
        +-----------------+------------------------------------------+---------------+-------------+--------+--------+
        
        

        The repository ubuntu has container images of Ubuntu versions. The images repository has container images of a large number of different Linux distributions. The ubuntu-daily has daily container images to be used for testing purposes. The local repository is the LXD server that we have just installed. It is not public and can be used to store your own container images.

      • List all available container images from a repository:

        lxc image list ubuntu:
        
          
        +------------------+--------------+--------+-----------------------------------------------+---------+----------+-------------------------------+
        |      ALIAS       | FINGERPRINT  | PUBLIC |                  DESCRIPTION                  |  ARCH   |   SIZE   |          UPLOAD DATE          |
        +------------------+--------------+--------+-----------------------------------------------+---------+----------+-------------------------------+
        | b (11 more)      | 5b72cf46f628 | yes    | ubuntu 18.04 LTS amd64 (release) (20190424)   | x86_64  | 180.37MB | Apr 24, 2019 at 12:00am (UTC) |
        +------------------+--------------+--------+-----------------------------------------------+---------+----------+-------------------------------+
        | c (5 more)       | 4716703f04fc | yes    | ubuntu 18.10 amd64 (release) (20190402)       | x86_64  | 313.29MB | Apr 2, 2019 at 12:00am (UTC)  |
        +------------------+--------------+--------+-----------------------------------------------+---------+----------+-------------------------------+
        | d (5 more)       | faef94acf5f9 | yes    | ubuntu 19.04 amd64 (release) (20190417)       | x86_64  | 322.56MB | Apr 17, 2019 at 12:00am (UTC) |
        +------------------+--------------+--------+-----------------------------------------------+---------+----------+-------------------------------+
        .....................................................................
        
        

        Note

        The first two columns for the alias and fingerprint provide an identifier that can be used to specify the container image when launching it.

        The output snippet shows the container images Ubuntu versions 18.04 LTS, 18.10, and 19.04. When creating a container we can just specify the short alias. For example, ubuntu:b means that the repository is ubuntu and the container image has the short alias b (for bionic, the codename of Ubuntu 18.04 LTS).

      • Get more information about a container image:

        lxc image info ubuntu:b
        
          
        Fingerprint: 5b72cf46f628b3d60f5d99af48633539b2916993c80fc5a2323d7d841f66afbe
        Size: 180.37MB
        Architecture: x86_64
        Public: yes
        Timestamps:
            Created: 2019/04/24 00:00 UTC
            Uploaded: 2019/04/24 00:00 UTC
            Expires: 2023/04/26 00:00 UTC
            Last used: never
        Properties:
            release: bionic
            version: 18.04
            architecture: amd64
            label: release
            serial: 20190424
            description: ubuntu 18.04 LTS amd64 (release) (20190424)
            os: ubuntu
        Aliases:
            - 18.04
            - 18.04/amd64
            - b
            - b/amd64
            - bionic
            - bionic/amd64
            - default
            - default/amd64
            - lts
            - lts/amd64
            - ubuntu
            - amd64
        Cached: no
        Auto update: disabled
        
        

        The output shows the details of the container image including all the available aliases. For Ubuntu 18.04 LTS, we can specify either b (for bionic, the codename of Ubuntu 18.04 LTS) or any other alias.

      • Launch a new container with the name mycontainer:

        lxc launch ubuntu:18.04 mycontainer
        
          
        Creating mycontainer
        Starting mycontainer
        
        
      • Check the list of containers to make sure the new container is running:

        lxc list
        
          
        +-------------+---------+-----------------------+---------------------------+------------+-----------+
        |    NAME     |  STATE  |         IPV4          |          IPV6             |    TYPE    | SNAPSHOTS |
        +-------------+---------+-----------------------+---------------------------+------------+-----------+
        | mycontainer | RUNNING | 10.142.148.244 (eth0) | fde5:5d27:...:1371 (eth0) | PERSISTENT | 0         |
        +-------------+---------+-----------------------+---------------------------+------------+-----------+
        
        
      • Execute basic commands in mycontainer:

        lxc exec mycontainer -- apt update
        lxc exec mycontainer -- apt upgrade
        

        Note

        The characters -- instruct the lxc command not to parse any more command-line parameters.

      • Open a shell session within mycontainer:

        lxc exec mycontainer -- sudo --login --user ubuntu
        
          
        To run a command as administrator (user "root"), use "sudo ".
        See "man sudo_root" for details.
        
        ubuntu@mycontainer:~$
        
        

        Note

        The Ubuntu container images have by default a non-root account with username ubuntu. This account can use sudo and does not require a password to perform administrative tasks.

        The sudo command provides a login to the existing account ubuntu.

      • View the container logs:

        lxc info mycontainer --show-log
        
      • Stop the container:

        lxc stop mycontainer
        
      • Remove the container:

        lxc delete mycontainer
        

        Note

        A container needs to be stopped before it can be deleted.

      Troubleshooting

      Error “unix.socket: connect: connection refused”

      When you run any lxc command, you get the following error:

          lxc list
      
      
        
      Error: Get http://unix.socket/1.0: dial unix /var/snap/lxd/common/lxd/unix.socket: connect: connection refused
      
      

      This happens when the LXD service is not currently running. By default, the LXD service is running as soon as it is configured successfully. See Initialize LXD to configure LXD.

      Error “unix.socket: connect: permission denied”

      When you run any lxc command, you get the following error:

          lxc list
      
      
        
      Error: Get http://unix.socket/1.0: dial unix /var/snap/lxd/common/lxd/unix.socket: connect: permission denied
      
      

      This happens when your limited user account is not a member of the lxd group, or you did not log out and log in again so that the new group membership to the lxd group gets updated.

      If your user account is ubuntu, the following command shows whether you are a member of the lxd group:

          groups ubuntu
      
      
        
      ubuntu : ubuntu sudo lxd
      
      

      In this example, we are members of the lxd group and we just need to log out and log in again. If you are not a member of the lxd group, see Initialize LXD on how to make your limited account a member of the lxd group.

      Next Steps

      If you plan to use a single website, then a single proxy device to the website container will suffice. If you plan to use multiple websites, you may install virtual hosts inside the website container. If instead you would like to setup multiple websites on their own container, then you will need to set up a reverse proxy in a container. In that case, the proxy device would direct to the reverse proxy container to direct the connections to the individual websites containers.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      Find answers, ask questions, and help others.

      This guide is published under a CC BY-ND 4.0 license.



      Source link