One place for hosting & domains

      Server

      Nginx Server- und Standortblockauswahlalgorithmen verstehen


      Einführung

      Nginx ist einer der beliebtesten Webserver der Welt. Er kann hohe Lasten mit vielen gleichzeitigen Clientverbindungen erfolgreich bewältigen und kann problemlos als Webserver, Mailserver oder Reverse-Proxy-Server fungieren.

      In diesem Leitfaden werden wir einige der Details hinter den Kulissen erörtern, die bestimmen, wie Nginx Client-Abfragen verarbeitet. Das Verständnis dieser Ideen kann das Rätselraten beim Entwerfen von Server- und Standortblöcken erleichtern und die Bearbeitung von Abfragen weniger unvorhersehbar erscheinen lassen.

      Nginx-Blockkonfigurationen

      Nginx unterteilt die Konfigurationen, die unterschiedliche Inhalte bereitstellen sollen, logisch in Blöcke, die in einer hierarchischen Struktur leben. Bei jedem Abfragen einer Client-Abfrage beginnt Nginx einen Prozess zur Feststellung, welche Konfigurationsblöcke zur Bearbeitung der Abfrage verwendet werden sollen. Dieser Entscheidungsprozess ist das, was wir in diesem Leitfaden diskutieren werden.

      Die Hauptblöcke, die wir diskutieren werden, sind der Server-Block und der Standort-Block.

      Ein Serverblock ist eine Teilmenge der Nginx-Konfiguration, die einen virtuellen Server definiert, der zur Verarbeitung von Abfragen eines definierten Typs verwendet wird. Administratoren konfigurieren häufig mehrere Serverblöcke und entscheiden anhand des angeforderten Domainnamens, Ports und der IP-Adresse, welcher Block welche Verbindung verarbeiten soll.

      Ein Standortblock befindet sich in einem Serverblock und wird verwendet, um zu definieren, wie Nginx Abfragen für verschiedene Ressourcen und URIs für den übergeordneten Server verarbeiten soll. Der URI-Bereich kann nach Belieben des Administrators mithilfe dieser Blöcke unterteilt werden. Es ist ein extrem flexibles Modell.

      Wie Nginx entscheidet, welcher Serverblock eine Abfrage verarbeiten wird

      Da der Administrator mit Nginx mehrere Serverblöcke definieren kann, die als separate virtuelle Webserverinstanzen fungieren, muss festgelegt werden, welcher dieser Serverblöcke zur Erfüllung einer Abfrage verwendet wird.

      Dies geschieht durch ein definiertes System von Überprüfungen, mit denen die bestmögliche Übereinstimmung gefunden wird. Die wichtigsten Serverblock-Direktiven, mit denen sich Nginx während dieses Prozesses befasst, sind die Direktive listen und server_name.

      Analysieren der „listen“-Direktive, um mögliche Übereinstimmungen zu finden

      Zunächst überprüft Nginx die IP-Adresse und den Port der Abfrage. Dies wird mit der listen-Direktive jedes Servers verglichen, um eine Liste der Serverblöcke zu erstellen, die möglicherweise die Abfrage auflösen können.

      Die listen-Direktive definiert typischerweise, auf welche IP-Adresse und welchen Port der Serverblock reagieren wird. Standardmäßig erhält jeder Serverblock, der keine listen-Direktive enthält, die listen-Parameter 0.0.0.0:80 (oder 0.0.0.0:8080, wenn Nginx von einem normalen non-root-Benutzer ausgeführt wird). Auf diese Weise können diese Blöcke auf Abfragen an einer beliebigen Schnittstelle an Port 80 antworten, aber dieser Standardwert hat im Serverauswahlprozess nicht viel Gewicht.

      Die listen-Direktive kann auf Folgendes eingestellt werden:

      • Eine Kombination aus IP-Adresse und Port.
      • Eine einzelne IP-Adresse, die dann den Standardport 80 überwacht.
      • Ein einzelner Port, der jede Schnittstelle an diesem Port überwacht.
      • Der Pfad zu einem Unix-Socket.

      Die letzte Option hat im Allgemeinen nur Auswirkungen beim Übergeben von Abfragen zwischen verschiedenen Servern.

      Wenn Sie versuchen, zu bestimmen, an welchen Serverblock eine Abfrage gesendet wird, wird Nginx zunächst versuchen, anhand der Spezifität der listen-Direktive mit den folgenden Regeln zu entscheiden:

      • Nginx übersetzt alle „unvollständigen“ listen-Direktiven, indem fehlende Werte mit den Standardwerten ersetzt werden, sodass jeder Block durch seine IP-Adresse und den Port bewertet werden kann. Einige Beispiele für diese Übersetzungen sind:
        • Ein Block ohne listen-Direktive verwendet den Wert 0.0.0.0:80.
        • Ein Block, der auf eine IP-Adresse 111.111.111.111 ohne Port festgelegt ist, wird zu 111.111.111.111:80
        • Ein Block, der auf Port 8888 ohne IP-Adresse festgelegt ist, wird zu 0.0.0.0:8888
      • Nginx versucht dann, eine Liste der Serverblöcke zu sammeln, die der Abfrage am spezifischsten entsprechen, basierend auf der IP-Adresse und dem Port. Dies bedeutet, dass ein Block, der funktional 0.0.0.0 als IP-Adresse verwendet (um mit einer beliebigen Schnittstelle übereinzustimmen), nicht ausgewählt wird, wenn übereinstimmende Blöcke vorhanden sind, in denen eine bestimmte IP-Adresse aufgeführt ist. In jedem Fall muss der Port genau übereinstimmen.
      • Wenn nur eine spezifischste Übereinstimmung vorhanden ist, wird dieser Serverblock verwendet, um die Abfrage zu bedienen. Wenn mehrere Serverblöcke mit derselben Spezifitätsübereinstimmung vorhanden sind, beginnt Nginx mit der Auswertung der Direktive server_name jedes Serverblocks.

      Es ist wichtig, zu verstehen, dass Nginx die Direktive server_name nur dann auswertet, wenn zwischen Serverblöcken unterschieden werden muss, die der gleichen Spezifitätsstufe in der listen-Direktive entsprechen. Wenn beispielsweise example.com auf Port 80 von 192.168.1.10 gehostet wird, wird eine Abfrage für example.com in diesem Beispiel trotz der Direktive server_name im zweiten Block immer vom ersten Block bedient.

      server {
          listen 192.168.1.10;
      
          . . .
      
      }
      
      server {
          listen 80;
          server_name example.com;
      
          . . .
      
      }
      

      Für den Fall, dass mehr als ein Serverblock mit gleicher Spezifität übereinstimmt, besteht der nächste Schritt darin, die Direktive server_name zu überprüfen.

      Analysieren der Direktive „server_name“, um eine Übereinstimmung auszuwählen

      Um Abfragen mit gleichermaßen spezifischen listen-Direktiven weiter auszuwerten, überprüft Nginx die „Host“-Überschrift der Abfrage. Dieser Wert enthält die Domain oder IP-Adresse, die der Client tatsächlich versucht hat, zu erreichen.

      Nginx versucht, die beste Übereinstimmung für den gefundenen Wert zu finden, indem es sich die Direktive server_name in jedem der Serverblöcke ansieht, die noch Auswahlkandidaten sind. Nginx bewertet diese durch die folgende Formel:

      • Nginx versucht zunächst, einen Serverblock mit einem server_name zu finden, der dem Wert in der „Host“-Überschrift der Abfrage genau entspricht. Wenn dieser gefunden wird, wird der zugeordnete Block verwendet, um die Abfrage zu bedienen. Wenn mehrere genaue Übereinstimmungen gefunden werden, wird die erste verwendet.
      • Wenn keine genaue Übereinstimmung gefunden wird, versucht Nginx, einen Serverblock mit einem server_name zu finden, der mit einem führenden Platzhalter übereinstimmt (angezeigt durch ein * am Anfang des Namens in der Konfiguration). Wenn eine gefunden wird, wird der zugeordnete Block verwendet, um die Abfrage zu bedienen. Wenn mehrere Übereinstimmungen gefunden werden, wird die längste Übereinstimmung verwendet, um die Abfrage zu bedienen.
      • Wenn mit einem führenden Platzhalter keine Übereinstimmung gefunden wird, sucht Nginx nach einem Serverblock mit einem server_name, der mit einem nachfolgenden Platzhalter übereinstimmt (angezeigt durch einen Servernamen, der in der Konfiguration mit einem * endet). Wenn eine gefunden wird, wird dieser Block verwendet, um die Abfrage zu bedienen. Wenn mehrere Übereinstimmungen gefunden werden, wird die längste Übereinstimmung verwendet, um die Abfrage zu bedienen.
      • Wenn mit einem nachgestellten Platzhalter keine Übereinstimmung gefunden wird, wertet Nginx Serverblöcke aus, die den server_name mithilfe regulärer Ausdrücke definieren (angezeigt durch ein ~ vor dem Namen). Der erste server_name mit einem regulären Ausdruck, der der „Host“-Überschrift entspricht, wird zur Bearbeitung der Abfrage verwendet.
      • Wenn keine Übereinstimmung mit regulären Ausdrücken gefunden wird, wählt Nginx den Standardserverblock für diese IP-Adresse und diesen Port aus.

      Jede Kombination aus IP-Adresse und Port verfügt über einen Standardserverblock, der verwendet wird, wenn mit den oben genannten Methoden keine Vorgehensweise festgelegt werden kann. Bei einer Kombination aus IP-Adresse und Port ist dies entweder der erste Block in der Konfiguration oder der Block, der die Option default_server als Teil der listen-Direktive enthält (die den zuerst gefundenen Algorithmus überschreiben würde). Pro IP-Adresse/Port-Kombination kann nur eine default_server-Deklaration vorhanden sein.

      Beispiele

      Wenn ein server_name definiert ist, der genau mit dem „Host“-Überschriftswert übereinstimmt, wird dieser Serverblock ausgewählt, um die Abfrage zu verarbeiten.

      Wenn in diesem Beispiel die „Host“-Überschrift der Abfrage auf „host1.example.com“ gesetzt wäre, würde der zweite Server ausgewählt:

      server {
          listen 80;
          server_name *.example.com;
      
          . . .
      
      }
      
      server {
          listen 80;
          server_name host1.example.com;
      
          . . .
      
      }
      

      Wenn keine genaue Übereinstimmung gefunden wird, prüft Nginx, ob ein server_name mit einem passenden Start-Platzhalter vorhanden ist. Die längste Übereinstimmung mit einem Platzhalter wird ausgewählt, um die Abfrage zu erfüllen.

      Wenn in diesem Beispiel die Abfrage einer „Host“-Überschrift „www.example.org“ hat, würde der zweite Serverblock ausgewählt:

      server {
          listen 80;
          server_name www.example.*;
      
          . . .
      
      }
      
      server {
          listen 80;
          server_name *.example.org;
      
          . . .
      
      }
      
      server {
          listen 80;
          server_name *.org;
      
          . . .
      
      }
      

      Wenn mit einem Start-Platzhalter keine Übereinstimmung gefunden wird, prüft Nginx anhand eines Platzhalters am Ende des Ausdrucks, ob eine Übereinstimmung vorliegt. An diesem Punkt wird die längste Übereinstimmung mit einem Platzhalter ausgewählt, um die Abfrage zu bedienen.

      Wenn beispielsweise die Abfrage eine „Host“-Überschrift auf „www.example.com“ festgelegt hat, wird der dritte Serverblock ausgewählt:

      server {
          listen 80;
          server_name host1.example.com;
      
          . . .
      
      }
      
      server {
          listen 80;
          server_name example.com;
      
          . . .
      
      }
      
      server {
          listen 80;
          server_name www.example.*;
      
          . . .
      
      }
      

      Wenn keine Platzhalterübereinstimmungen gefunden werden können, versucht Nginx, Übereinstimmungen mit den Direktiven server_name zuzuordnen, die reguläre Ausdrücke verwenden. Der erste übereinstimmende reguläre Ausdruck wird ausgewählt, um auf die Abfrage zu antworten.

      Wenn beispielsweise die „Host“-Überschrift der Abfrage auf „www.example.com“ gesetzt ist, wird der zweite Serverblock ausgewählt, um die Abfrage zu erfüllen:

      server {
          listen 80;
          server_name example.com;
      
          . . .
      
      }
      
      server {
          listen 80;
          server_name ~^(www|host1).*.example.com$;
      
          . . .
      
      }
      
      server {
          listen 80;
          server_name ~^(subdomain|set|www|host1).*.example.com$;
      
          . . .
      
      }
      

      Wenn keiner der oben genannten Schritte die Abfrage erfüllen kann, wird die Abfrage an den Standardserver für die übereinstimmende IP-Adresse und den passenden Port weitergeleitet.

      Übereinstimmung von Standortblöcken

      Ähnlich wie bei dem Prozess, mit dem Nginx den Serverblock auswählt, der eine Abfrage verarbeitet, verfügt Nginx auch über einen etablierten Algorithmus zur Entscheidung, welcher Standortblock innerhalb des Servers zur Verarbeitung von Abfragen verwendet werden soll.

      Standortblock-Syntax

      Bevor wir uns damit befassen, wie Nginx entscheidet, welcher Standortblock zur Verarbeitung von Abfragen verwendet werden soll, gehen wir einen Teil der Syntax durch, der möglicherweise in Standortblockdefinitionen angezeigt wird. Standortblöcke befinden sich in Serverblöcken (oder anderen Standortblöcken) und werden verwendet, um zu entscheiden, wie der Abfrage-URI (der Teil der Abfrage, der nach dem Domainnamen oder der IP-Adresse/dem IP-Port kommt) verarbeitet werden soll.

      Standortblöcke haben im Allgemeinen die folgende Form:

      location optional_modifier location_match {
      
          . . .
      
      }
      

      Das oben angezeigte location_match definiert, gegen was Nginx den Abfrage-URI prüfen soll. Das Vorhandensein oder Nichtvorhandensein des Modifikators im obigen Beispiel beeinflusst die Art und Weise, wie der Nginx versucht, mit dem Standortblock übereinzustimmen. Die folgenden Modifikatoren bewirken, dass der zugehörige Standortblock wie folgt interpretiert wird:

      • (none): Wenn keine Modifikatoren vorhanden sind, wird der Speicherort als Präfix-Übereinstimmung interpretiert. Dies bedeutet, dass der angegebene Speicherort mit dem Beginn des Abfrage-URIs abgeglichen wird, um eine Übereinstimmung zu ermitteln.
      • =: Wenn ein Gleichheitszeichen verwendet wird, wird dieser Block als Übereinstimmung betrachtet, wenn der Abfrage-URI genau mit dem angegebenen Standort übereinstimmt.
      • ~: Wenn ein Tilde-Modifikator vorhanden ist, wird dieser Speicherort als Übereinstimmung zwischen regulären Ausdrücken und Groß- und Kleinschreibung interpretiert.
      • ~*: Wenn ein Tilde- und ein Sternchen-Modifikator verwendet werden, wird der Positionsblock als Übereinstimmung zwischen regulären Ausdrücken ohne Berücksichtigung der Groß- und Kleinschreibung interpretiert.
      • ^~: Wenn ein Karat- und Tilde-Modifikator vorhanden ist und dieser Block als beste Übereinstimmung mit nicht regulären Ausdrücken ausgewählt ist, findet keine Übereinstimmung mit regulären Ausdrücken statt.

      Beispiele zur Demonstration der Standortblock-Syntax

      Als Beispiel für die Präfixübereinstimmung kann der folgende Standortblock ausgewählt werden, um auf Abfrage-URIs zu antworten, die wie /site, /site/page1/index.html oder /site/index.html aussehen:

      location /site {
      
          . . .
      
      }
      

      Zur Demonstration der genauen Übereinstimmung der Abfrage-URI wird dieser Block immer verwendet, um auf eine Abfrage-URI zu antworten, die wie /page1 aussieht. Es wird nicht verwendet, um auf eine /page1/index.html-Abfrage-URI zu antworten. Beachten Sie, dass bei Auswahl dieses Blocks und Erfüllung der Abfrage über eine Indexseite eine interne Umleitung an einen anderen Speicherort erfolgt, der der eigentliche Handhaber der Abfrage ist:

      location = /page1 {
      
          . . .
      
      }
      

      Als Beispiel für einen Speicherort, der als regulärer Ausdruck mit Groß- und Kleinschreibung interpretiert werden sollte, kann dieser Block verwendet werden, um Abfragen für /tortoise.jpg zu verarbeiten, nicht jedoch für /FLOWER.PNG:

      location ~ .(jpe?g|png|gif|ico)$ {
      
          . . .
      
      }
      

      Ein Block, der eine Übereinstimmung ohne Berücksichtigung der Groß- und Kleinschreibung ähnlich wie oben ermöglichen würde, ist unten dargestellt. Hier könnten sowohl /tortoise.jpg als auch /FLOWER.PNG von diesem Block verarbeitet werden:

      location ~* .(jpe?g|png|gif|ico)$ {
      
          . . .
      
      }
      

      Schließlich würde dieser Block verhindern, dass eine Übereinstimmung mit regulären Ausdrücken auftritt, wenn festgestellt wird, dass dies die beste Übereinstimmung mit nicht regulären Ausdrücken ist. Er könnte Abfragen für /costumes/ninja.html verarbeiten:

      location ^~ /costumes {
      
          . . .
      
      }
      

      Wie Sie sehen, geben die Modifikatoren an, wie der Standortblock interpretiert werden soll. Dies sagt uns jedoch nicht, welchen Algorithmus Nginx verwendet, um zu entscheiden, an welchen Standortblock die Abfrage gesendet werden soll. Wir werden das als nächstes durchgehen.

      Wie Nginx wählt, welcher Standort zur Bearbeitung von Abfragen verwendet werden soll

      Nginx wählt den Speicherort aus, an dem eine Abfrage bearbeitet wird, ähnlich wie bei der Auswahl eines Serverblocks. Es wird ein Prozess durchlaufen, der den besten Standortblock für eine bestimmte Abfrage ermittelt. Das Verständnis dieses Prozesses ist eine entscheidende Anforderung, um Nginx zuverlässig und korrekt konfigurieren zu können.

      Unter Berücksichtigung der oben beschriebenen Arten von Standortdeklarationen bewertet Nginx die möglichen Standortkontexte, indem der Abfrage-URI mit jedem der Standorte verglichen wird. Dies geschieht mit dem folgenden Algorithmus:

      • Nginx überprüft zunächst alle Präfix-basierten Standortübereinstimmungen (alle Standorttypen, die keinen regulären Ausdruck enthalten). Es vergleicht jeden Standort mit dem vollständigen Abfrage-URI.
      • Zunächst sucht Nginx nach einer genauen Übereinstimmung Wenn ein Standortblock mit dem Modifikator = gefunden wird, der genau mit dem Abfrage-URI übereinstimmt, wird dieser Standortblock sofort ausgewählt, um die Abfrage zu bedienen.
      • Wenn keine genauen (mit dem Modifikator =) Positionsblockübereinstimmungen gefunden werden, fährt Nginx mit der Auswertung nicht exakter Präfixe fort. Es ermittelt den am längsten übereinstimmenden Präfixspeicherort für den angegebenen Abfrage-URI, den es dann wie folgt auswertet:
        • Wenn der am längsten übereinstimmende Präfixstandort den Modifikator ^ ~ hat, beendet Nginx die Suche sofort und wählt diesen Standort aus, um die Abfrage zu bearbeiten.
        • Wenn die Position mit dem längsten übereinstimmenden Präfix nicht den Modifikator ^ ~ verwendet, wird die Übereinstimmung für den Moment von Nginx gespeichert, damit der Fokus der Suche verschoben werden kann.
      • Nachdem die Position mit der längsten Übereinstimmung ermittelt und gespeichert wurde, fährt Nginx mit der Auswertung der Positionen für reguläre Ausdrücke fort (sowohl Groß- und Kleinschreibung als auch Nicht-Groß-/Kleinschreibung beachten). Wenn sich Positionen mit regulären Ausdrücken innerhalb der am längsten übereinstimmenden Präfixposition befinden, verschiebt Nginx diese an den Anfang der Liste der zu überprüfenden Regex-Positionen. Nginx versucht dann, nacheinander mit den Positionen der regulären Ausdrücke abzugleichen. Der erste reguläre Ausdruck des Standortes wird sofort ausgewählt, um die Abfrage zu bedienen.
      • Wenn keine Standorte für reguläre Ausdrücke gefunden werden, die mit dem Abfrage-URI übereinstimmen, wird der zuvor gespeicherte Präfixstandort ausgewählt, um die Abfrage zu bedienen.

      Es ist wichtig, zu verstehen, dass Nginx standardmäßig Übereinstimmungen mit regulären Ausdrücken anstelle von Präfixübereinstimmungen bereitstellt. Es werden jedoch zuerst Präfixpositionen ausgewertet, sodass die Verwaltung diese Tendenz überschreiben kann, indPositionen mit den Modifikatoren = und ^ ~ angegeben werden.

      Es ist auch wichtig, zu beachten, dass, während Präfixpositionen im Allgemeinen basierend auf der längsten, spezifischsten Übereinstimmung ausgewählt werden, die Auswertung regulärer Ausdrücke gestoppt wird, wenn die erste übereinstimmende Position gefunden wird. Dies bedeutet, dass die Positionierung innerhalb der Konfiguration enorme Auswirkungen auf die Positionen regulärer Ausdrücke hat.

      Schließlich ist es wichtig, zu verstehen, dass Übereinstimmungen mit regulären Ausdrücken innerhalb der längsten Präfixübereinstimmung „die Zeile überspringen“, wenn Nginx Regex-Positionen auswertet. Diese werden der Reihe nach ausgewertet, bevor andere Übereinstimmungen mit regulären Ausdrücken berücksichtigt werden. Maxim Dounin, ein unglaublich hilfreicher Nginx-Entwickler, erklärt in diesem Beitrag diesen Teil des Auswahlalgorithmus.

      Wann springt die Standortblockbewertung zu anderen Standorten?

      Wenn ein Standortblock ausgewählt wird, um eine Abfrage zu bedienen, wird die Abfrage im Allgemeinen von diesem Punkt an vollständig in diesem Kontext behandelt. Nur der ausgewählte Standort und die geerbten Anweisungen bestimmen, wie die Abfrage verarbeitet wird, ohne dass Geschwisterstandortblöcke eingreifen.

      Obwohl dies eine allgemeine Regel ist, mit der Sie Ihre Standortblöcke auf vorhersehbare Weise entwerfen können, ist es wichtig zu wissen, dass es manchmal Zeiten gibt, in denen eine neue Standortsuche durch bestimmte Anweisungen innerhalb des ausgewählten Standortes ausgelöst wird. Die Ausnahmen von der Regel „Nur ein Standortblock“ können Auswirkungen auf die tatsächliche Zustellung der Abfrage haben und stimmen möglicherweise nicht mit den Erwartungen überein, die Sie beim Entwerfen Ihrer Standortblöcke hatten.

      Einige Direktiven, die zu dieser Art der internen Weiterleitung führen können, sind:

      • index
      • try_files
      • rewrite
      • error_page

      Gehen wir diese kurz durch.

      Die Direktive index führt immer zu einer internen Weiterleitung, wenn sie verwendet wird, um die Abfrage zu verarbeiten. Genaue Standortübereinstimmungen werden häufig verwendet, um den Auswahlprozess zu beschleunigen, indem die Ausführung des Algorithmus sofort beendet wird. Wenn Sie jedoch eine genaue Standortübereinstimmung mit einem Verzeichnis vornehmen, besteht eine gute Chance, dass die Abfrage zur tatsächlichen Verarbeitung an einen anderen Standort umgeleitet wird.

      In diesem Beispiel wird der erste Standort mit einem Abfrage-URI von /exact abgeglichen. Um die Abfrage zu verarbeiten, initiiert die vom Block geerbte Indexanweisung eine interne Umleitung zum zweiten Block:

      index index.html;
      
      location = /exact {
      
          . . .
      
      }
      
      location / {
      
          . . .
      
      }
      

      Wenn Sie im obigen Fall wirklich die Ausführung benötigen, um im ersten Block zu bleiben, müssen Sie eine andere Methode finden, um die Abfrage an das Verzeichnis zu erfüllen. Sie können beispielsweise einen ungültigen index für diesen Block festlegen und den autoindex aktivieren:

      location = /exact {
          index nothing_will_match;
          autoindex on;
      }
      
      location  / {
      
          . . .
      
      }
      

      Dies ist eine Möglichkeit, um zu verhindern, dass ein index den Kontext wechselt, ist jedoch für die meisten Konfigurationen wahrscheinlich nicht hilfreich. Meistens kann eine genaue Übereinstimmung mit Verzeichnissen hilfreich sein, um beispielsweise die Abfrage neu zu schreiben (was auch zu einer neuen Standortsuche führt).

      Eine andere Instanz, in der der Verarbeitungsort neu bewertet werden kann, ist die Direktive try_files. Diese Direktive weist Nginx an, das Vorhandensein einer benannten Gruppe von Dateien oder Verzeichnissen zu überprüfen. Der letzte Parameter kann ein URI sein, zu dem Nginx eine interne Umleitung vornimmt.

      Erwägen Sie folgende Konfiguration:

      root /var/www/main;
      location / {
          try_files $uri $uri.html $uri/ /fallback/index.html;
      }
      
      location /fallback {
          root /var/www/another;
      }
      

      Wenn im obigen Beispiel eine Anfrage für /blahblah gestellt wird, erhält der erste Standort zunächst die Abfrage. Er wird versuchen, eine Datei namens blahblah im Verzeichnis /var/www/main zu finden. Wenn gefunden werden kann, wird anschließend nach einer Datei mit dem Namen blahblah.html gesucht. Anschließend wird versucht, festzustellen, ob sich im Verzeichnis /var/www/main ein Verzeichnis mit dem Namen blahblah/ befindet. Wenn alle diese Versuche fehlschlagen, wird zu /fallback/index.html umgeleitet. Dies löst eine weitere Standortsuche aus, die vom zweiten Standortblock abgefangen wird. Dies wird die Datei /var/www/anderen/fallback/index.html bereitstellen.

      Eine weitere Direktive, die dazu führen kann, dass ein Standortblock übergeben wird, ist die Direktive rewrite. Wenn Sie den letzten Parameter mit der Direktive rewrite zum Umschreiben oder überhaupt keinen Parameter verwenden, sucht Nginx basierend auf den Ergebnissen des Umschreibens nach einem neuen übereinstimmenden Standort.

      Wenn wir beispielsweise das letzte Beispiel so ändern, dass es ein Umschreiben enthält, können wir feststellen, dass die Abfrage manchmal direkt an den zweiten Standort übergeben wird, ohne sich auf die Direktive try_files zu verlassen:

      root /var/www/main;
      location / {
          rewrite ^/rewriteme/(.*)$ /$1 last;
          try_files $uri $uri.html $uri/ /fallback/index.html;
      }
      
      location /fallback {
          root /var/www/another;
      }
      

      Im obigen Beispiel wird eine Abfrage für /rewriteme/hello zunächst vom ersten Standortblock verarbeitet. Sie wird in /hello umgeschrieben und ein Standort gesucht. In diesem Fall stimmt sie wieder mit dem ersten Standort überein und wird wie gewohnt von den try_files verarbeitet. Wenn nichts gefunden wird, kehren Sie möglicherweise zu /fallback/index.html zurück (mithilfe der oben beschriebenen internen Umleitung try_files).

      Wenn jedoch eine Abfrage für /rewriteme/fallback/hello gestellt wird, stimmt der erste Block erneut überein. Das Umschreiben wird erneut angewendet, diesmal mit /fallback/hello. Die Abfrage wird dann aus dem zweiten Standortblock heraus zugestellt.

      Eine verwandte Situation tritt bei der Direktive return auf, wenn die Statuscodes 301 oder 302 gesendet werden. Der Unterschied in diesem Fall ist, dass es eine völlig neue Abfrage in Form einer extern sichtbaren Umleitung bildet. Dieselbe Situation kann bei der Direktive rewrite auftreten, wenn die Flags redirect oder permanent verwendet werden. Diese Standortsuche sollte jedoch nicht unerwartet sein, da extern sichtbare Weiterleitungen immer zu einer neuen Abfrage führen.

      Die Direktive error_page kann zu einer internen Umleitung führen, die der von try_files erstellten ähnelt. Diese Direktive wird verwendet, um zu definieren, was passieren soll, wenn bestimmte Statuscodes aufgetreten sind. Dies wird wahrscheinlich nie ausgeführt, wenn try_files festgelegt ist, da diese Direktive den gesamten Lebenszyklus einer Abfrage behandelt.

      Erwägen Sie dieses Beispiel:

      root /var/www/main;
      
      location / {
          error_page 404 /another/whoops.html;
      }
      
      location /another {
          root /var/www;
      }
      

      Jede Abfrage (außer denjenigen, die mit /another beginnen) wird vom ersten Block bearbeitet, der Dateien aus /var/www/main bereitstellt. Wenn jedoch keine Datei gefunden wird (Status 404), erfolgt eine interne Umleitung zu /another/whoops.html, die zu einer neuen Standortsuche führt, die schließlich im zweiten Block landet. Diese Datei wird aus /var/www/another/whoops.html. bereitgestellt.

      Wie Sie sehen können, kann das Verständnis der Umstände, unter denen Nginx eine neue Standortsuche auslöst, dazu beitragen, das Verhalten vorherzusagen, das bei Abfragen auftreten wird.

      Zusammenfassung

      Wenn Sie wissen, wie Nginx Client-Abfragen verarbeitet, können Sie Ihre Arbeit als Administrator erheblich vereinfachen. Sie können anhand jeder Client-Abfrage wissen, welchen Serverblock Nginx auswählt. Sie können auch anhand der Abfrage-URI festlegen, wie der Standortblock ausgewählt wird. Wenn Sie wissen, wie Nginx verschiedene Blöcke auswählt, können Sie die Kontexte verfolgen, die Nginx anwenden wird, um jede Abfrage zu bearbeiten.



      Source link

      How to Make a Minecraft Server with DreamCompute (In 3 Steps)


      Minecraft is a rare game with the longevity to still be wildly popular over nine years after its initial release, boasting 126 million monthly players. However, if you’ve ever wanted your own block kingdom, the technical aspects of making a Minecraft server may make it seem like you’re dealing with a real-life Enderman.

      Fortunately, there are ways to make the process fast and easy. 

      DreamCompute is our cloud computing service that can help you set up your own Minecraft server. With just a few simple steps, you’ll be ready to launch your Minecraft world.

      In this article, we’ll discuss some of the reasons you might want to make your own Minecraft server and cover the technical aspects of the process. Then we’ll provide you with three easy steps to get it up and running with DreamHost. Let’s go! 

      The Benefits of Making Your Own Minecraft Server

      Minecraft servers let you play the game either online or in a local network. It’s like a subset within the larger game that is yours to customize as you see fit. You’re free to build inside of it on your terms. 

      There are lots of benefits to making your own server. For one, you have full control. You can use any mods you want to customize your gameplay. Creating a unique environment with these tools can be advantageous if you’re looking to start your own YouTube channel

      It doesn’t have to be just you, either. Having your own server enables you to build a community. You can invite people you want to join you in-game for a multiplayer adventure. If you’d rather keep to yourself, you can still share your custom designs with the world. 

      To top it all off, creating your own Minecraft server can be a pretty painless experience. You might be surprised by how accessible the process can be. With a little bit of guidance, you’ll have your own space up and running in no time. 

      Why You Should Use DreamCompute for Your Minecraft Server

      DreamCompute info on dreamhost.com

      You probably have a few options when it comes to server hosts. They might seem similar at first glance, especially if you’re just starting out. However, there are some important differences to be aware of before you make your choice.

      The first thing to look for in a host is whether it offers a cloud-based server. These are generally a better choice than more traditional local servers, as they don’t directly tax your computer’s resources. Typically, this translates to smoother, improved gameplay. 

      Tech support might also have an easier time navigating a cloud server than a local server if you run into any trouble. Plus, having a cloud server means you won’t have to worry about keeping your computer running at all times for other server members who want access to it. 

      Our DreamCompute service offers cloud servers for Minecraft with competitive features. It’s suitable for both simple and complex configurations, offering impressive speeds for all users. It also has a straightforward and predictable billing system to prevent any nasty surprises at the end of the month.

      Further, it’s flexible enough to grow with if you need to change any aspect of your account. Rest assured that any alterations you need to make will get the support they need. 

      If you already know you’re looking for premium performance and control, you might want to check out DreamHost’s dedicated server option. It offers impressive benefits, such as fully-managed, cross-platform cooperative play. However, if you’re just looking for a basic server setup, we’ve got you covered there too. 

      Get Minecraft Hosting That Scales

      DreamCompute is the ideal solution for Minecraft servers that require fast speeds and consistent uptime.

      What to Know Before You Get Started

      There are a couple of tools you’ll need to get started. First, make sure you have a downloaded copy of Minecraft ready. You’ll also need to set up a DreamCompute account.

      You also might find some knowledge of servers to be informative since it will help you understand exactly what’s going on in each step. However, if you’re a beginner, don’t fret! The process is very accessible, and our guide is here to help. 

      How to Make Your Own Minecraft Server with DreamCompute (In 3 Steps)

      Once you have all the resources you need, just follow these three simple steps to create your own Minecraft server.

      Step 1: Create a Security Group

      The first thing you’ll want to do is create a security group. This is a set of rules that define network access and will allow or prevent traffic into your Minecraft server according to your preferences. All you need to do is adjust some settings.

      To get this started, navigate to your DreamCompute dashboard and click to expand the Network option on the left-hand side.

      The DreamCompute Dashboard with the network options expanded.

      Next, you can click the Security Groups button and then select Create Security Group. This will bring up a window where you can add a name and description. We’ll be using “Minecraft” for both in this walkthrough, but feel free to get creative with yours.

      The DreamCompute security group creation screen. 

      Once you’ve finished filling in those fields, click on Create Security Group to move on to the next step. You’ll then be presented with the options to create rules for this new group.  

      Step 2: Manage Your Rules

      In the new group, click on the Manage Rules button on the far right. Next, select Add Rule to bring up the following screen.

      The “Add Rule” pop-up screen in DreamCompute. 

      There are a lot of options on this page, but you don’t have to worry about them too much. If you’re looking to quick-start your server, you can just fill it in the same way we did above.

      Specifically, we suggest selecting Custom TCP Rule in the first field, Ingress in the second, and Port in the third. Under Port, enter the number “25565”; this is the default port for Minecraft.

      Next, make sure the bottom two fields are set to CIDR and “0.0.0.0/0” respectively. Once you’re ready, click on the Add button.

      Step 3: Create a Virtual Machine (VM)

      For the last step, you’ll need a Virtual Machine (VM). Anything with Java will suffice. We’ll be using Ubuntu-14.04 for this walkthrough, and we recommend using it if you’re unsure which solution to choose.

      You can then navigate back to your DreamCompute dashboard, and under the Compute menu, click on Instances. Next, select the Launch Instance button on the far right. This will bring up a screen that looks something like the following:

      The “Launch Instance” pop-up with the “Details” section selected.

      Try not to get overwhelmed by all the options! There are only a few that you’ll need to deal with. Start by naming your server in the top field under Instance Name. We used “My New Minecraft Server,” but you can name it anything you like.

      Click Next to move on.

      The “Launch Instance” pop-up with the “Source” section selected.

      From the provided list, select Ubuntu-14.04. The search function can be helpful here if you’re having trouble finding it. Then you can click on the up arrow to move your selection into the Allocated section. To make sure that your instance does not immediately run out of disk / storage space, adjust the Volume Size (GB) to be 10 GB and then click on Next to browse to the Flavor section.

      The “Launch Instance” pop-up with the “Flavor” section selected.

      You can also use the search function here to find a specific ‘Flavor’ you’re looking for. If you’re not sure which is best for you, we recommend the Lightspeed option. It has 4GB of RAM, making it a solid choice for most users. 

      Next, select the up arrow next to your chosen Flavor to move it into the Allocated category. Click on Next until you get to the Security Groups section.

      The “Launch Instance” pop-up with the “Security Groups” section selected.

      This section is an easy one. Simply click on the arrow next to the Minecraft security group we created earlier, so it’s listed under the Allocated category as shown above. 

      Click on Next to get to the Key Pair section. If you’ve already imported a Key Pair into your DreamCompute project, use the arrow next to that key to assign it to your instance. Otherwise, use the “Create Key Pair” button to create a new Key Pair and then assign that Key Pair to your instance (this is used for emergency connections and for making additional adjustments to the MineCraft server). 

      That should be all you need to do before switching to the Configuration section.

      The “Launch Instance” pop-up with the “Configuration” section selected.

      At this point, you’ll be brought to a page with a blank field titled Customization Script. On it, you can copy and paste the below code:

      #!/bin/bash
      
      apt-get update && apt-get -y install wget screen openjdk-7-jre-headless
      
      su - ubuntu -c 'wget https://s3.amazonaws.com/Minecraft.Download/versions/1.8.9/minecraft_server.1.8.9.jar -O ~/mcserver.jar'
      
      su - ubuntu -c 'echo 'eula=true' > ~/eula.txt'
      
      su - ubuntu -c 'screen -S mcserver -d -m java -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -d64 -Xms512M -Xmx2G -jar mcserver.jar'

      You can also load the script from a file. However, you might find that the copy and paste method is quicker and easier.

      Keep in mind that the -Xms512M -Xmx2G part of this code is what tells Java the minimum and maximum allowed memory for the Lightspeed flavor we chose earlier. As such, it may not be suitable for other Flavors.

      After you’ve entered that code, click on Launch Instance. Sit back, relax, and give your server a few minutes for the setup process to complete. Once that’s done, your server will be online and ready to go!

      To add your new server to your client, you can open Minecraft and click on Multiplayer > Add Server. Name it whatever you’d like, and provide the IPv4 address of the VM you set up earlier. 

      If you want to modify the default server settings, you can log into your server via Secure Shell (SSH) as “ubuntu.” This will give you access to a server.properties file where you can change the message of the day, spawn different creatures, adjust the maximum number of players, and more.

      Be Awesome on the Internet

      Join our monthly newsletter for tips and tricks to build your dream website!

      Build Your Minecraft Realm

      Minecraft offers nearly endless opportunities for creative freedom. If you want to take full advantage of all it has to offer and elevate your game to the next level, making your own Minecraft server is the way to go.

      In this article, we covered three simple steps for setting one up using DreamCompute:

      1. Create a security group for your new server.
      2. Adjust the network access rules.
      3. Set up your VM to finish the process.

      Can’t wait to create a world of your own? DreamCompute can help you set up your own Minecraft server in a matter of minutes. Get ready to grab your pickaxe and get out there!  



      Source link

      How To Monitor Server Health with Checkmk on Ubuntu 20.04


      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      As a systems administrator, it’s best to know the current state of your infrastructure and services. Ideally, you want to notice failing disks or application downtimes before your users do. Monitoring tools like Checkmk can help administrators detect these issues and maintain healthy servers.

      Generally, monitoring software can track your servers’ hardware, uptime, and service statuses, and it can raise alerts when something goes wrong. In a real scenario, a monitoring system would alert you if any services go down. In a more robust one, the notifications would come shortly after any suspicious signs arose, such as increased memory usage or an abnormal amount of TCP connections.

      Many monitoring solutions offer varying degrees of complexity and feature sets, both free and commercial. In many cases, the installation, configuration, and management of these tools is difficult and time-consuming.

      Checkmk is a monitoring solution that is both robust and simpler to install. It is a self-contained software bundle that combines Nagios (a popular and open-source alerting service) with add-ons for gathering, monitoring, and graphing data. It also comes with Checkmk’s web interface — a comprehensive tool that addresses many of Nagios’s shortcomings. It offers a user-friendly dashboard, a full-featured notification system, and a repository of easy-to-install monitoring agents for many Linux distributions. If it weren’t for Checkmk’s web interface, we would have to use different views for various tasks. It wouldn’t be possible to configure all these features without resorting to extensive file modifications.

      In this guide, we will set up Checkmk on an Ubuntu 20.04 server and monitor two separate hosts. We will monitor the Ubuntu server itself and a separate CentOS 8 server, but we could use the same approach to add any number of additional hosts to our monitoring configuration.

      Prerequisites

      Step 1 — Installing Checkmk on Ubuntu

      In order to use our monitoring site, we first must install Checkmk on the Ubuntu server. This will give us all the tools we need. Checkmk provides official ready-to-use Ubuntu package files that we can use to install the software bundle.

      First, let’s update the packages list so that we have the most recent version of the repository listings:

      To browse the packages we can go to the package listing site. Ubuntu 20.04, among others, can be selected in the page menu.

      Now download the package:

      • wget https://download.checkmk.com/checkmk/1.6.0p20/check-mk-raw-1.6.0p20_0.focal_amd64.deb

      Then install the newly downloaded package:

      • sudo apt install -y ./check-mk-raw-1.6.0p20_0.focal_amd64.deb

      This command will install the Checkmk package along with all necessary dependencies, including the Apache web server that is used to provide web access to the monitoring interface.

      After the installation completes, we now can access the omd command. Try it out:

      This omd command will output the following:

      Output

      Usage (called as root): omd help Show general help . . . General Options: -V <version> set specific version, useful in combination with update/create omd COMMAND -h, --help show available options of COMMAND

      The omd command can manage all Checkmk instances on our server. It can start and stop all the monitoring services at once, and we will use it to create our Checkmk instance. First, however, we have to update our firewall settings to allow outside access to the default web ports.

      Step 2 — Adjusting the Firewall Settings

      Before we’ll be able to work with Checkmk, it’s necessary to allow outside access to the web server in the firewall configuration. Assuming that you followed the firewall configuration steps in the prerequisites, you’ll have a UFW firewall set up to restrict access to your server.

      During installation, Apache registers itself with UFW to provide an easy way to enable or disable access to Apache through the firewall.

      To allow access to Apache, use the following command:

      Now verify the changes:

      You’ll see that Apache is listed among the allowed services:

      Output

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

      This will allow us to access the Checkmk web interface.

      In the next step, we’ll create the first Checkmk monitoring instance.

      Step 3 — Creating a Checkmk Monitoring Instance

      Checkmk uses the concept of instances, or individual installations, to isolate multiple Checkmk copies on a server. In most cases, only one copy of Checkmk is enough and that’s how we will configure the software in this guide.

      First we must give our new instance a name, and we will use monitoring throughout this text. To create the instance, type:

      • sudo omd create monitoring

      The omd tool will set up everything for us automatically. The command output will look similar to the following:

      Output

      Adding /opt/omd/sites/monitoring/tmp to /etc/fstab. Creating temporary filesystem /omd/sites/monitoring/tmp...OK Restarting Apache...OK Created new site monitoring with version 1.6.0p20.cre. The site can be started with omd start monitoring. The default web UI is available at http://your_ubuntu_server/monitoring/ The admin user for the web applications is cmkadmin with password: your-default-password (It can be changed with 'htpasswd -m ~/etc/htpasswd cmkadmin' as site user.) Please do a su - monitoring for administration of this site.

      In this output the URL address, default username, and password for accessing our monitoring interface are highlighted. The instance is now created, but it still needs to be started. To start the instance, type:

      • sudo omd start monitoring

      Now all the necessary tools and services will be started at once. At the end we’ll see an output verifying that all our services have started successfully:

      Output

      Starting mkeventd...OK Starting rrdcached...OK Starting npcd...OK Starting nagios...OK Starting apache...OK Initializing Crontab...OK

      The instance is up and running.

      To access the Checkmk instance, open http://your_ubuntu_server_ip/monitoring/ in the web browser. You will be prompted for a password. Use the default credentials printed beforehand on the screen; we will change these defaults later on.

      The Checkmk screen opens with a dashboard, which shows all our services and server statuses in lists, and it uses practical graphs resembling the Earth. Straight after installation these are empty, but we will shortly make it display statuses for our services and systems.

      Blank Checkmk dashboard

      In the next step, we will change the default password to secure the site using this interface.

      Step 4 — Changing Your Administrative Password

      During installation, Checkmk generates a random password for the cmkadmin administrative user. This password is meant to be changed upon installation, and as such it is often short and not very secure. We can change this via the web interface.

      First, open the Users page from the WATO - Configuration menu on the left. The list will show all users that currently have access to the Checkmk site. On a fresh installation it will list only two users. The first one, automation, is intended for use with automated tools; the second is the cmkadmin user we used to log in to the site.

      List of Checkmk users

      Click on the pencil icon next to the cmkadmin user to change its details, including the password.

      Edit form for Checkmk admin user

      Update the password, add an admin email, and make any other desired changes.

      After saving the changes we will be asked to log in again using our new credentials. Do so and return to the dashboard, where there is one more thing we must do to fully apply our new configuration.

      Once again open the Users page from the WATO - Configuration menu on the left. The orange button in the top left corner labeled as 1 Change tells us that we have made some changes to the configuration of Checkmk, and that we need to save and activate them. This will happen every time we change the configuration of our monitoring system, not only after editing a user’s credentials. To save and activate pending changes we have to click on this button and agree to activate the listed changes using the Activate affected option on the following screen.

      List of Checkmk users after modifications
      Activate configuration changes confirmation screen
      Successfully activated configuration changes

      After activating the changes the new user’s data is written to the configuration files and it will be used by all the system’s components. Checkmk automatically takes care of notifying individual monitoring system components, reloading them when necessary, and managing all the needed configuration files.

      The Checkmk installation is now ready for use. In the next step, we will add the first host to our monitoring system.

      Step 5 — Monitoring the First Host

      We are now ready to monitor the first host. To accomplish this, we will first install check-mk-agent on the Ubuntu server. Then, we’ll restrict access to the monitoring data using xinetd.

      The components installed with Checkmk are responsible for receiving, storing, and presenting monitoring information. They do not provide the information itself.

      To gather the actual data, we will use Checkmk agent. Designed specifically for the job, Checkmk agent can monitor all vital system components at once and report that information back to the Checkmk instance.

      Installing the agent

      The first host we will monitor will be your_ubuntu_server—the server on which we have installed the Checkmk instance itself.

      To begin, we must install the Checkmk agent. Packages for all major distributions, including Ubuntu, are available directly from the web interface. Open the Monitoring Agents page from the WATO - Configuration menu on the left. You will see the available agent downloads with the most popular packages under the first section labeled Packaged agents.

      List of available packaged monitoring agents

      The package check-mk-agent_1.6.0p20-1_all.deb is the one suited for Debian based distributions, including Ubuntu. Copy the download link for that package from the web browser and use that address to download the package:

      • wget http://your_ubuntu_server_ip/monitoring/check_mk/agents/check-mk-agent_1.6.0p20-1_all.deb

      After downloading, install the package:

      • apt install -y ./check-mk-agent_1.6.0p20-1_all.deb

      Now verify the agent installation:

      The command will output a very long text that looks like gibberish but combines all vital information about the system in one place:

      Output

      <<<check_mk>>> Version: 1.6.0p20 AgentOS: linux . . . <<<job>>> <<<local>>>

      It is the output from this command that Checkmk uses to gather status data from monitored hosts. Now, we’ll restrict access to the monitoring data with xinetd.

      Restricting Access to Monitoring Data Using xinetd

      By default, the data from check_mk_agent is served using xinetd, a mechanism that outputs data on a certain network port upon accessing it. This means that we can access the check_mk_agent by using telnet to port 6556 (the default port for Checkmk) from any other computer on the internet unless our firewall configuration disallows it.

      It is not a good security policy to publish vital information about servers to anyone on the internet. We should allow only hosts that run Checkmk and are under our supervision to access this data, so that only our monitoring system can gather it.

      If you have followed the initial server setup tutorial including the steps about setting up a firewall, then access to Checkmk agent is by default blocked. It is, however, a good practice to enforce these access restrictions directly in the service configuration and not rely only on the firewall to guard it.

      To restrict access to the agent data, we have to edit the configuration file at /etc/xinetd.d/check_mk. Open the configuration file in your favorite editor. To use nano, type:

      • sudo nano /etc/xinetd.d/check_mk

      Locate this section:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      #only_from      = 127.0.0.1 10.0.20.1 10.0.20.2
      . . .
      

      The only_from setting is responsible for restricting access to certain IP addresses. Because we are now working on monitoring the same server that Checkmk is running on, it is ok to allow only localhost to connect. Uncomment and update the configuration setting to:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      only_from      = 127.0.0.1
      . . .
      

      Save and exit the file.

      The xinetd daemon has to be restarted for changes to take place. Do so now:

      • sudo systemctl restart xinetd

      Now our agent is up and running and restricted to accept only local connections. We can proceed to configure monitoring for that host using Checkmk.

      Configuring Host in Checkmk Web Interface

      First, to add a new host to monitor we have to go to the Hosts menu in the WATO - Configuration menu on the left. From here click Create new host. We will be asked for some information about the host.

      Creating a new host in Checkmk

      The Hostname is the familiar name that Checkmk will use for the monitoring. It may be a fully-qualified domain name, but it is not necessary. In this example, we will name the host monitoring, just like the name of the Checkmk instance itself. Because monitoring is not resolvable to our IP address, we also have to provide the IP address of our server. And since we are monitoring the local host, the IP will simply be 127.0.0.1. Check the IPv4 Address box to enable the manual IP input and enter the value in the text field.

      The default configuration of the Data Sources section relies on Checkmk agent to provide monitoring data, which is fine. The Networking Segment setting is used to denote hosts on remote networks, which are characterized by a higher expected latency that is not a sign of malfunction. Since this is a local host, the default setting is fine as well.

      To save the host and configure which services will be monitored, click the Save & go to services button.

      List of available services to monitor

      Checkmk will do an automatic inventory. That means it will gather the output from the agent and decipher it to know what kinds of services it can monitor. All available services for monitoring will be on the list, including CPU load, memory usage, and free space on disks.

      To enable monitoring of all discovered services, we have to click the Monitor button under the Undecided services (currently not monitored) section. This will refresh the page, but now all services will be listed under the Monitored services section, informing us that they are indeed being monitored.

      As was the case when changing our user password, these new changes must be saved and activated before they go live. Press the 2 changes button and accept the changes using the Activate affected button. After that, the host monitoring will be up and running.

      Now you are ready to work with your server data. Take a look at the main dashboard using the Overview/Main Overview menu item on the left.

      Working with Monitoring Data

      Now let’s take a look at the main dashboard using the Overview/Main Overview menu item on the left:

      Monitoring dashboard with all services healthy

      The Earth sphere is now fully green and the table says that one host is up with no problems. We can see the full host list, which now consists of a single host, in the Hosts/All hosts view (using the menu on the left).

      List of hosts with all services healthy

      There we will see how many services are in good health (shown in green), how many are failing, and how many are pending to be checked. After clicking on the hostname we will be able to see the list of all services with their full statuses and their Perf-O-Meters. Perf-O-Meter shows the performance of a single service relative to what Checkmk considers to be good health.

      Details of a host service status

      All services that return graphable data display a graph icon next to their name. We can use that icon to get access to graphs associated with the service. Since the host monitoring is fresh, there is almost nothing on the graphs—but after some time the graphs will provide valuable information on how our service performance changes over time.

      Graphs depicting CPU load on the server

      When any of these services fails or recovers, the information will be shown on the dashboard. For failing services a red error will be shown, and the problem will also be visible on the Earth graph.

      Dashboard with one host having problems

      After recovery, everything will be shown in green as working properly, but the event log on the right will contain information about past failures.

      Dashboard with one host recovered after problems

      Now that we have explored the dashboard a little, let’s add a second host to our monitoring instance.

      Step 6 — Monitoring a Second CentOS Host

      Monitoring gets really useful when you have multiple hosts. We will now add a second server to our Checkmk instance, this time running CentOS 8.

      As with our Ubuntu server, installing Checkmk agent is necessary to gather monitoring data on CentOS. This time, however, we will need an rpm package from the Monitoring Agents page in the web interface, called check-mk-agent-1.6.0p20-1.noarch.rpm.

      First, however, we must install xinetd, which by default is not available on the CentOS installation. Xinetd, we will remember, is a daemon that is responsible for making the monitoring data provided by check_mk_agent available over the network.

      On your CentOS server, first install xinetd:

      • sudo dnf install -y xinetd

      Now we can download and install the monitoring agent package needed for our CentOS server:

      • sudo dnf install -y http://your_ubuntu_server_ip/monitoring/check_mk/agents/check-mk-agent-1.6.0p20-1.noarch.rpm

      Just like before, we can verify that the agent is working properly by executing check_mk_agent:

      The output will be similar to that from the Ubuntu server. Now we will restrict access to the agent.

      Restricting Access

      This time we will not be monitoring a local host, so xinetd must allow connections coming from the Ubuntu server, where Checkmk is installed, to gather the data. To allow that, first open your configuration file:

      • sudo vi /etc/xinetd.d/check_mk

      Here you will see the configuration for your check_mk service, specifying how Checkmk agent can be accessed through the xinetd daemon. Find the following two commented lines:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      #only_from      = 127.0.0.1 10.0.20.1 10.0.20.2
      . . .
      

      Now uncomment the second line and replace the local IP addresses with your_ubuntu_server_ip:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      only_from      = your_ubuntu_server_ip
      . . .
      

      Save and exit the file by typing :x and then ENTER. Restart the xinetd service using:

      • sudo systemctl restart xinetd

      If you have configured local firewall following the initial server setup tutorial, it is also necessary to adjust the firewall settings. Without doing so, connections to Checkmk agent won’t be allowed. To do so, execute:

      • sudo firewall-cmd --add-port=6556/tcp --permanent

      This would allow incoming TCP traffic to port 6556 which is used by Checkmk. The configuration will update after you reload the firewall:

      • sudo firewall-cmd --reload

      Note: You can learn how to fine tune the firewall settings by following the How To Set Up a Firewall Using firewalld on CentOS 8 guide.

      We can now proceed to configure Checkmk to monitor our CentOS 8 host.

      Configuring the New Host in Checkmk

      To add additional hosts to Checkmk, we use the Hosts menu just like before. This time we will name the host centos, configure its IP address, and choose WAN (high-latency) under the Networking Segment select box, since the host is on another network. If we skipped this and left it as local, Checkmk would soon alert us that the host is down, since it would expect it to respond to agent queries much quicker than is possible over the internet.

      Creating second host configuration screen

      Click Save & go to services, which will show services available for monitoring on the CentOS server. The list will be very similar to the one from the first host. Again, this time we also must click Monitor and then activate the changes using the orange button on the top left corner.

      After activating the changes, we can verify that the host is monitored on the All hosts page. Go there. Two hosts, monitoring and centos, will now be visible.

      List of hosts with two hosts being monitored

      You are now monitoring an Ubuntu server and a CentOS server with Checkmk. It is possible to monitor even more hosts. In fact, there is no upper limit other than server performance, which should not be a problem until your hosts number in the hundreds. Moreover, the procedure is the same for any other host. Checkmk agents in deb and rpm packages work on Ubuntu, CentOS, and the majority of other Linux distributions.

      Conclusion

      In this guide we set up two servers with two different Linux distributions: Ubuntu and CentOS. We then installed and configured Checkmk to monitor both servers, and explored Checkmk’s powerful web interface.

      Checkmk allows for the easy setup of a complete and versatile monitoring system, which packs all the hard work of manual configuration into an easy-to-use web interface full of options and features. With these tools it is possible to monitor multiple hosts; set up email, SMS, or push notifications for problems; set up additional checks for more services; monitor accessibility and performance, and so on.

      To learn more about Checkmk, make sure to visit the official documentation.



      Source link