One place for hosting & domains

      Comment installer WordPress sur Ubuntu 20.04 avec un LAMP Stack


      Introduction

      WordPress est une technologie open-source extrêmement populaire pour la création de sites web et de blogs sur l’internet aujourd’hui. Utilisés par 63 % des sites web qui utilisent un système de gestion de contenu (CMS), les sites WordPress représentent 36 % de tous les sites web qui sont actuellement en ligne.

      Il existe de nombreuses approches différentes pour accéder à WordPress et certains processus de configuration sont plus complexes que d’autres. Ce tutoriel est destiné à ceux qui souhaitent installer et administrer une instance de WordPress sur un serveur en nuage non géré via la ligne de commande. Bien que cette approche nécessite plus d’étapes qu’une installation WordPress toute faite, elle offre aux administrateurs un plus grand contrôle sur leur environnement WordPress.

      Si vous cherchez à accéder à une installation WordPress prête à l’emploi, DigitalOcean Marketplace propose une app en un clic pour vous aider à démarrer avec WordPress, jusqu’à l’installation lors de la mise en route de votre serveur.

      En fonction de vos besoins et de vos objectifs, vous pouvez trouver d’autres options plus adaptées. En tant que logiciel open-source, WordPress peut être téléchargé et installé gratuitement, mais pour être disponible sur le web, vous devrez probablement acheter une infrastructure en nuage et un nom de domaine. Continuez à suivre ce guide si vous êtes intéressé par l’installation côté serveur et par la mise en place d’un site WordPress.

      Ce tutoriel utilisera un LAMP (Linux, Apache, MySQL et PHP) stack qui est une option pour une architecture de serveur qui supporte WordPress en fournissant le système d’exploitation Linux, le serveur web Apache, la base de données MySQL et le langage de programmation PHP. Nous installerons et configurerons WordPress via LAMP sur un serveur Linux Ubuntu 20.04.

      Conditions préalables

      Pour pouvoir suivre ce tutoriel, vous devez avoir accès à un serveur Ubuntu 20.04 et effectuer les étapes suivantes avant de commencer ce guide :

      • Configurez votre serveur en suivant notre guide de configuration initiale du serveur Ubuntu 20.04 et assurez-vous d’avoir un non-root sudo user. 
      • Installez un LAMP stack en suivant notre guide LAMP pour installer et configurer ce logiciel.
      • Sécurisez votre site : WordPress prend en compte les entrées de l’utilisateur et stocke ses données, il est donc important pour lui d’avoir une couche de sécurité. TLS/SSL est la technologie qui vous permet de crypter le trafic de votre site afin que votre connexion et celle de vos utilisateurs soient sécurisées. Voici deux options qui s’offrent à vous pour répondre à cette exigence :
        • Si vous avez un nom de domaine… vous pouvez sécuriser votre site avec Let’s Encrypt, qui fournit des certificats gratuits et fiables. Suivez notre guide Let’s Encrypt pour Apache afin de configurer cela.
        • Si vous n’avez pas de domaine… et que vous utilisez cette configuration à des fins de test ou pour un usage personnel, vous pouvez à la place utiliser un certificat auto-signé. Cela permet d’obtenir le même type de chiffrement, mais sans la validation du domaine. Suivez notre guide SSL auto-signé pour Apache afin de le mettre en place.

      Une fois les étapes de préparation terminées, connectez-vous à votre serveur en tant qu’utilisateur sudo et continuez ci-dessous.

      Étape 1 – Créer une base de données MySQL et un utilisateur pour WordPress

      La première étape que nous allons suivre est une étape préparatoire. WordPress utilise MySQL pour gérer et stocker les informations du site et des utilisateurs. Nous avons déjà installé MySQL, mais nous devons créer une base de données et un utilisateur pour WordPress.

      Pour commencer, connectez-vous au compte MySQL root (administratif) en exécutant cette commande (notez que ce n’est pas le root user de votre serveur) :

      Le mot de passe que vous avez défini pour le compte root MySQL lors de son installation vous sera demandé.

      Note : Si vous ne pouvez pas accéder à votre base de données MySQL via le root, en tant que sudo user, vous pouvez mettre à jour le mot de passe de votre root user en vous connectant à la base de données de cette manière : 

      Une fois que vous recevez l’invite MySQL, vous pouvez mettre à jour le mot de passe du root user. Ici, remplacez new_password par un mot de passe fort de votre choix.

      • ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new_password';

      Vous pouvez maintenant taper EXIT ; et vous pouvez vous reconnecter à la base de données via un mot de passe avec la commande suivante :

      Dans la base de données, nous pouvons créer une base de données exclusive que WordPress peut contrôler. Vous pouvez l’appeler comme vous le souhaitez, mais nous utiliserons le nom wordpress dans ce guide. Créez la base de données pour WordPress en tapant :

      • CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

      Remarque : chaque instruction MySQL doit se terminer par un point-virgule (;). Vérifiez qu’il est bien présent si vous rencontrez des problèmes.

      Ensuite, nous allons créer un compte utilisateur MySQL distinct que nous utiliserons exclusivement pour exploiter notre nouvelle base de données. La création de bases de données et de comptes spécifiques peut nous aider du point de vue de la gestion et de la sécurité. Nous utiliserons le nom wordpressuser dans ce guide, mais n’hésitez pas à utiliser le nom qui vous convient le mieux.

      Nous allons créer ce compte, définir un mot de passe et lui donner accès à la base de données que nous avons créée. Nous pouvons le faire en tapant la commande ci-dessous. N’oubliez pas de choisir un mot de passe fort ici pour l’utilisateur de votre base de données où nous avons password :

      • CREATE USER 'wordpressuser'@'%' IDENTIFIED WITH mysql_native_password BY 'password';

      Ensuite, faites savoir à la base de données que notre wordpressuser devrait avoir un accès complet à la base de données que nous avons mise en place : 

      • GRANT ALL ON wordpress.* TO 'wordpressuser'@'%';

      Vous disposez désormais d’une base de données et d’un compte d’utilisateur, chacun spécialement conçu pour WordPress. Nous devons supprimer les privilèges afin que l’instance actuelle de MySQL soit informée des récents changements que nous avons apportés :

      Sortez de MySQL en tapant :

      Dans la prochaine étape, nous poserons quelques bases pour les plugins WordPress en téléchargeant des extensions PHP pour notre serveur.

      Étape 2 – Installez des extensions PHP supplémentaires

      Lors de la mise en place de notre pile LAMP, nous n’avons eu besoin que d’un ensemble très limité d’extensions pour que PHP puisse communiquer avec MySQL. WordPress et beaucoup de ses plugins utilisent des extensions PHP supplémentaires.

      Nous pouvons télécharger et installer certaines des extensions PHP les plus populaires pour WordPress en tapant :

      • sudo apt update
      • sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip

      Cela permettra de préparer le terrain pour l’installation de plugins supplémentaires sur notre site WordPress.

      Remarque : chaque plugin WordPress a ses propres exigences. Certains peuvent nécessiter l’installation de packages PHP supplémentaires. Consultez la documentation de votre plugin pour connaître ses besoins en matière de PHP. S’ils sont disponibles, ils peuvent être installés avec apt comme illustré ci-dessus.

      Nous devrons redémarrer Apache pour charger ces nouvelles extensions, nous ferons d’autres configurations sur Apache dans la prochaine section, vous pouvez donc attendre jusque-là, ou redémarrer maintenant pour terminer le processus d’extension PHP.

      • sudo systemctl restart apache2

      Étape 3 – Ajuster la configuration d’Apache pour autoriser .htaccess à remplacer et réécrire

      Nous allons maintenant procéder à quelques ajustements mineurs de notre configuration Apache. Après avoir suivi les tutoriaux préalables, vous devez disposer d’un fichier de configuration pour votre site dans le répertoire /etc/apache2/sites-available/.

      Dans ce guide, nous utiliserons ici /etc/apache2/sites-available/wordpress.conf comme exemple, mais vous devez substituer le chemin d’accès à votre fichier de configuration le cas échéant. De plus, nous utiliserons /var/www/wordpress comme répertoire root de notre installation WordPress. Vous devez utiliser la racine Web spécifiée dans votre propre configuration. Si vous avez suivi notre tutoriel LAMP, il se peut que ce soit votre nom de domaine au lieu de wordpress dans ces deux cas.

      Remarque : il est possible que vous utilisiez la configuration par défaut 000-default.conf (avec /var/www/html comme racine Web). C’est une bonne solution si vous n’hébergez qu’un seul site web sur ce serveur. Sinon, il est préférable de diviser la configuration nécessaire en morceaux logiques, un fichier par site.

      Une fois nos chemins identifiés, nous pouvons passer à la collaboration avec htaccess afin qu’Apache puisse gérer les changements de configuration par répertoire. 

      Autoriser les remplacements .htaccess

      Actuellement, l’utilisation des fichiers .htaccess est désactivée. WordPress et de nombreux plugins WordPress utilisent ces fichiers de manière intensive pour des ajustements dans les répertoires du comportement du serveur web.

      Ouvrez le fichier de configuration Apache pour votre site web avec un éditeur de texte comme nano.

      • sudo nano /etc/apache2/sites-available/wordpress.conf

      Pour autoriser les fichiers .htaccess, nous devons paramétrer la directive AllowOverride dans un bloc Directory pointant vers la racine de notre document. Ajoutez le bloc de texte suivant dans le bloc VirtualHost de votre fichier de configuration, en veillant à utiliser le bon répertoire web root :

      /etc/apache2/sites-available/wordpress.conf

      <Directory /var/www/wordpress/>
          AllowOverride All
      </Directory>
      

      Lorsque vous avez terminé, enregistrez et fermez le fichier. Dans nano, vous pouvez le faire en appuyant sur CTRL et X ensemble, puis Y, puis ENTER.

      Activer le module de réécriture

      Ensuite, nous pouvons activer mod_rewrite afin de pouvoir utiliser la fonction de permalien de WordPress :

      Cela vous permet d’avoir des permaliens plus lisibles à l’oeil humain pour vos messages, comme les deux exemples suivants :

      http://example.com/2012/post-name/
      http://example.com/2012/12/30/post-name
      

      La commande a2enmod appelle un script qui active le module spécifié dans la configuration d’Apache.

      Activer les modifications

      Avant de mettre en œuvre les modifications que nous avons apportées, vérifiez que nous n’avons pas fait d’erreurs de syntaxe en effectuant le test suivant.

      • sudo apache2ctl configtest

      Vous pouvez recevoir des résultats comme ceux qui suivent :

      Output

      AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message Syntax OK

      Si vous souhaitez supprimer la première ligne, ajoutez simplement une directive ServerName à votre fichier de configuration principal (global) d’Apache à l’emplacement /etc/apache2/apache2.conf. Le ServerName peut être le domaine ou l’adresse IP de votre serveur. Il s’agit toutefois d’un simple message qui n’affecte pas la fonctionnalité de votre site. Tant que la sortie contient Syntax OK, vous êtes prêt à continuer.

      Redémarrez Apache pour mettre en œuvre les changements. Veillez à redémarrer maintenant même si vous avez redémarré plus tôt dans ce tutoriel.

      • sudo systemctl restart apache2

      Nous allons ensuite télécharger et mettre en place WordPress lui-même.

      Étape 4 – Téléchargement de WordPress

      Maintenant que le logiciel de notre serveur est configuré, nous pouvons télécharger et installer WordPress. Pour des raisons de sécurité notamment, il est toujours recommandé de se procurer la dernière version de WordPress sur leur site.

      Passez dans un répertoire inscriptible (nous recommandons un répertoire temporaire comme /tmp) et téléchargez la version compressée.

      • cd /tmp
      • curl -O https://wordpress.org/latest.tar.gz

      Extrayez le fichier compressé pour créer la structure de répertoire de WordPress :

      Nous allons déplacer ces fichiers à la racine de notre document dans un instant. Avant cela, nous pouvons ajouter un fichier .htaccess factice afin qu’il soit disponible pour une utilisation ultérieure par WordPress.

      Créez le fichier en tapant :

      • touch /tmp/wordpress/.htaccess

      Nous allons également copier l’exemple du fichier de configuration vers le nom de fichier que WordPress lit :

      • cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

      Nous pouvons également créer le répertoire des upgrade, afin que WordPress ne rencontre pas de problèmes de permissions lorsqu’il essaie de le faire seul après une mise à jour de son logiciel :

      • mkdir /tmp/wordpress/wp-content/upgrade

      Nous pouvons maintenant copier l’intégralité du contenu du répertoire à la racine de notre document. Nous ajoutons un point à la fin de notre répertoire source pour indiquer que tout ce qui se trouve dans le répertoire doit être copié, y compris les fichiers cachés (tels que le fichier .htaccess que nous avons créé) :

      • sudo cp -a /tmp/wordpress/. /var/www/wordpress

      Veillez à remplacer le /var/www/wordpress avec le répertoire que vous avez configuré sur votre serveur. 

      Étape 5 – Configurer le répertoire WordPress

      Avant de procéder à la configuration Web de WordPress, nous devons ajuster certains éléments de notre répertoire WordPress.

      Ajuster la propriété et les autorisations

      Une étape importante que nous devons accomplir consiste à établir des autorisations et des droits de propriété raisonnables sur les fichiers.

      Nous commencerons par donner la propriété de tous les fichiers à www-data user et group. C’est l’utilisateur sous lequel le serveur web Apache fonctionne, et Apache devra être capable de lire et d’écrire des fichiers WordPress afin de servir le site web et d’effectuer des mises à jour automatiques.

      Mettez à jour la propriété avec la commande chown qui vous permet de modifier la propriété du fichier. Veillez à pointer vers le répertoire pertinent de votre serveur.

      • sudo chown -R www-data:www-data /var/www/wordpress

      Ensuite, nous allons en faire deux find pour définir les autorisations correctes sur les répertoires et les fichiers WordPress :

      • sudo find /var/www/wordpress/ -type d -exec chmod 750 {} ;
      • sudo find /var/www/wordpress/ -type f -exec chmod 640 {} ;

      Ces autorisations devraient vous permettre de travailler efficacement avec WordPress, mais notez que certains plugins et procédures peuvent nécessiter des ajustements supplémentaires.

      Modifier le fichier de configuration WordPress

      Maintenant, nous devons apporter quelques modifications au fichier de configuration principal de WordPress.

      Lorsque nous ouvrirons le fichier, notre première tâche sera d’ajuster certaines clés secrètes afin d’assurer un niveau de sécurité pour notre installation. WordPress fournit un générateur sécurisé pour ces valeurs, afin que vous n’ayez pas à essayer de trouver de bonnes valeurs par vous-même. Elles ne sont utilisées qu’en interne, de sorte qu’il ne sera pas préjudiciable à la facilité d’utilisation d’avoir des valeurs complexes et sûres ici.

      Pour récupérer des valeurs sécurisées du générateur de clés secrètes de WordPress, tapez :

      • curl -s https://api.wordpress.org/secret-key/1.1/salt/

      Vous obtiendrez des valeurs uniques qui ressemblent à des sorties similaires à celles du bloc ci-dessous.

      Attention ! Il est important que vous demandiez des valeurs uniques à chaque fois. Ne copiez PAS les valeurs ci-dessous !

      Output

      define('AUTH_KEY', '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H'); define('SECURE_AUTH_KEY', 'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3'); define('LOGGED_IN_KEY', 'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88'); define('NONCE_KEY', 'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g'); define('AUTH_SALT', 'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES 07VC*Lj*lD&?3w!BT#-'); define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY'); define('LOGGED_IN_SALT', 'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|'); define('NONCE_SALT', 'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%');

      Il s’agit de lignes de configuration que nous pouvons coller directement dans notre fichier de configuration pour définir des clés sécurisées. Copiez la sortie que vous venez d’obtenir.

      Ensuite, ouvrez le fichier de configuration de WordPress :

      • sudo nano /var/www/wordpress/wp-config.php

      Trouvez la section qui contient les exemples de valeurs pour ces paramètres.

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'put your unique phrase here');
      define('SECURE_AUTH_KEY',  'put your unique phrase here');
      define('LOGGED_IN_KEY',    'put your unique phrase here');
      define('NONCE_KEY',        'put your unique phrase here');
      define('AUTH_SALT',        'put your unique phrase here');
      define('SECURE_AUTH_SALT', 'put your unique phrase here');
      define('LOGGED_IN_SALT',   'put your unique phrase here');
      define('NONCE_SALT',       'put your unique phrase here');
      
      . . .
      

      Supprimez ces lignes et collez les valeurs que vous avez copiées depuis la ligne de commande :

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_KEY',  'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_KEY',    'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_KEY',        'VALUES COPIED FROM THE COMMAND LINE');
      define('AUTH_SALT',        'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_SALT',   'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_SALT',       'VALUES COPIED FROM THE COMMAND LINE');
      
      . . .
      

      Ensuite, nous allons modifier certains des paramètres de connexion à la base de données au début du fichier. Vous devez ajuster le nom de la base de données, l’utilisateur de la base de données et le mot de passe associé que vous avez configuré dans MySQL.

      L’autre modification que nous devons apporter est de définir la méthode que WordPress doit utiliser pour écrire dans le système de fichiers. Comme nous avons donné au serveur web la permission d’écrire là où il faut, nous pouvons explicitement définir la méthode du système de fichiers sur « direct ». Si nous ne configurons pas la méthode avec nos paramètres actuels, WordPress demandera les informations d’identification FTP lorsque nous effectuerons certaines actions.

      Ce paramètre peut être ajouté sous les paramètres de connexion à la base de données ou n’importe où ailleurs dans le fichier :

      /var/www/wordpress/wp-config.php

      . . .
      
      // ** MySQL settings - You can get this info from your web host ** //
      /** The name of the database for WordPress */
      define( 'DB_NAME', 'wordpress' );
      
      /** MySQL database username */
      define( 'DB_USER', 'wordpressuser' );
      
      /** MySQL database password */
      define( 'DB_PASSWORD', 'password' );
      
      /** MySQL hostname */
      define( 'DB_HOST', 'localhost' );
      
      /** Database Charset to use in creating database tables. */
      define( 'DB_CHARSET', 'utf8' );
      
      /** The Database Collate type. Don't change this if in doubt. */
      define( 'DB_COLLATE', '' );
      
      
      . . .
      
      define('FS_METHOD', 'direct');
      

      Enregistrez et fermez le fichier lorsque vous avez terminé.

      Étape 6 — Finalisation de l’installation via l’interface Web

      Maintenant que la configuration du serveur est terminée, nous pouvons finaliser l’installation via l’interface Web.

      Dans votre navigateur web, naviguez vers le nom de domaine ou l’adresse IP publique de votre serveur :

      https://server_domain_or_IP
      

      Sélectionnez la langue que vous souhaitez utiliser :

      WordPress language selection

      Ensuite, vous arriverez à la page de configuration principale.

      Choisissez un nom pour votre site WordPress et choisissez un nom d’utilisateur. Il est recommandé de choisir quelque chose d’unique et d’éviter les noms d’utilisateur courants comme « admin » pour des raisons de sécurité. Un mot de passe fort est généré automatiquement. Enregistrez ce mot de passe ou choisissez un autre mot de passe fort.

      Entrez votre adresse e-mail et choisissez si vous voulez demander aux moteurs de recherche de ne pas indexer votre site :

      WordPress setup installation

      Lorsque vous cliquez, vous accédez à une page qui vous invite à vous connecter :

      WordPress login prompt

      Une fois connecté, vous serez redirigé vers le tableau de bord d’administration de WordPress :

      WordPress login prompt

      A ce stade, vous pouvez commencer à concevoir votre site WordPress ! Si c’est la première fois que vous utilisez WordPress, explorez un peu l’interface pour vous familiariser avec votre nouveau CMS.

      Conclusion

      Félicitations, WordPress est maintenant installé et prêt à être utilisé !

      À ce stade, vous voudrez peut-être commencer à faire ce qui suit :

      • Choisissez vos paramètres de permaliens pour les messages WordPress, qui se trouvent dans Settings > Permalinks.
      • Sélectionnez un nouveau thème dans Appearance > Themes. 
      • Installez de nouveaux plugins pour augmenter les fonctionnalités de votre site sous Plugins > Add New. 
      • Si vous comptez collaborer avec d’autres personnes, vous pouvez également ajouter des utilisateurs supplémentaires à ce moment sous Users > Add New. 

      Vous pouvez trouver des ressources supplémentaires pour d’autres façons d’installer WordPress, apprendre comment installer WordPress sur différentes distributions de serveurs, automatiser vos installations WordPress, et faire évoluer vos sites WordPress en consultant notre balise communautaire WordPress. 



      Source link

      How to Deploy the Elastic Stack on Kubernetes


      Updated by Linode Written by Tyler Langlois

      What is the Elastic Stack?

      The Elastic Stack is a collection of open source projects from Elastic that help collect and visualize a wide variety of data sources. Elasticsearch can store and aggregate data such as log files, container metrics, and more. The products in the stack include: Elasticsearch, Logstash, Kibana, and now Beats.

      This guide provides instructions to:

      You can further use the Elastic Stack deployed and configured for application logs or monitoring Kubernetes.

      Caution

      This guide’s example instructions creates the following billable resources on the Linode account: four (4) Linodes and three (3) Block Storage volumes. If you do not want to keep using the example cluster that you create, be sure to delete the cluster Linodes and volumes after you have finished the guide.

      If you remove the resources afterward, you are billed only for the hour(s) that the resources were present on the account. For more information, see Billing and Payments guide about how hourly billing works and for a table of plan pricing.

      Before You Begin

      Note

      This guide uses Kubernetes services which are private by default. Local listeners are opened which allow you to access the services on the local browser, however, web servers and NodeBalancers are out scope for this guide. Due to this, you should complete the steps of this guide from the local computer or from a computer that gives you access to the web browser. If you want to access these services from a public domain, please see the Getting Started with NodeBalancers guide.
      1. Install the Kubernetes CLI (kubectl) on the local computer.

      2. Follow the instructions in Deploying and Managing a Cluster with Linode Kubernetes Engine Tutorial to create and connect to an LKE cluster.

        Note

        Ensure that the LKE cluster that you create has three nodes and one master node with 4GB Linode instances. Also ensure that the KUBECONFIG context is persistent
      3. You should also make sure that Kubernetes CLI is using the right cluster context. Run the get-contexts subcommand to check:

        kubectl config get-contexts
        
      4. Set up Helm in the Kubernetes cluster by following the Install Helm section in the How to Install Apps on Kubernetes with Helm 3 guide.

      Configure Helm

      You should now have a Kubernetes cluster with Helm installed and configured.

      1. Add the elastic chart repository to the local installation of Helm:

        helm repo add elastic https://helm.elastic.co
        
      2. Fetch the updated list of charts from all configured chart repositories:

        helm repo update
        
      3. Search for the official elasticsearch chart to confirm Helm has been configured correctly. Note that this chart released by Elastic differs from the chart bundled with the default installation of Helm.

        helm search hub elasticsearch
        

        This command returns all the charts available for elasticsearch in the hub. Select the one listed below. The exact version numbers may be different; at the time of writing this guide the version is 7.8.0.

          
        NAME                                              CHART VERSION   APP VERSION   DESCRIPTION
        https://hub.helm.sh/charts/elastic/elasticsearch  7.8.0        	  7.8.0      	Official Elastic helm chart for Elasticsearch
        
        

        The Helm environment is now ready to install official Elasticsearch charts to the Kubernetes cluster.

      Install Charts

      Install Elasticsearch

      Before installing the chart, ensure that resources are set appropriately. By default, the elasticsearch chart allocates 1GB of memory to the JVM heap and sets Kubernetes resource requests and limits to 2GB. Using a Linode 4GB instance is compatible with these defaults, but if you are using a different instance type, you need to provide different values to the chart at install time in order to ensure that running Pods are within the resource constraints of the node sizes you have chosen.

      1. Install the elasticsearch chart:

        helm install elasticsearch elastic/elasticsearch
        

        An output similar to the following appears:

          
            LAST DEPLOYED: Tue Jul  7 14:46:52 2020
            NAMESPACE: default
            STATUS: deployed
            REVISION: 1
            NOTES:
            1. Watch all cluster members come up.
               $ kubectl get pods --namespace=default -l app=elasticsearch-master -w
            2. Test cluster health using Helm test.
              $ helm test elasticsearch --cleanup
            
        
      2. A three-node Elasticsearch cluster is now configured and available locally to the Kubernetes cluster. To confirm this, first port-forward a local port to the Elasticsearch service. Leave this command running in a terminal window or tab in the background for the remainder of this tutorial.

        kubectl port-forward svc/elasticsearch-master 9200:9200
        

        Note

        This command times out after 5 minutes, if you find that and want to have the port forward for longer, consider using the following command to keep it open: while true; do kubectl port-forward svc/elasticsearch-master 9200:9200; done

      3. In another terminal window, send a request to this port:

        curl http://localhost:9200/
        

        An output similar to the following appears:

          
        {
          "name" : "elasticsearch-master-1",
          "cluster_name" : "elasticsearch",
          "cluster_uuid" : "2eKh30v2Q1ybT9HTPqQw9w",
          "version" : {
            "number" : "7.8.0",
            "build_flavor" : "default",
            "build_type" : "docker",
            "build_hash" : "757314695644ea9a1dc2fecd26d1a43856725e65",
            "build_date" : "2020-06-14T19:35:50.234439Z",
            "build_snapshot" : false,
            "lucene_version" : "8.5.1",
            "minimum_wire_compatibility_version" : "6.8.0",
            "minimum_index_compatibility_version" : "6.0.0-beta1"
          },
          "tagline" : "You Know, for Search"
        }
        
        

        Note

        The specific version numbers and dates may be different in this JSON response. Elasticsearch is operational, but not receiving or serving any data.

      Install Filebeat

      In order to start processing data, deploy the filebeat chart to the Kubernetes cluster. This collects all Pod logs and stores them in Elasticsearch, after which they can be searched and used in visualizations within Kibana.

      1. Deploy the filebeat chart. No custom values.yaml file should be necessary:

        helm install filebeat elastic/filebeat
        

        An output similar to the following appears:

          
        NAME: filebeat
        LAST DEPLOYED: Tue Jul  7 15:33:52 2020
        NAMESPACE: default
        STATUS: deployed
        REVISION: 1
        TEST SUITE: None
        NOTES:
        1. Watch all containers come up.
           $ kubectl get pods --namespace=default -l app=filebeat-filebeat -w
        
        
      2. Confirm that Filebeat has started to index documents into Elasticsearch by sending a request to the locally-forwarded Elasticsearch service port in a different terminal:

        curl http://localhost:9200/_cat/indices
        

        At least one filebeat index should be present, and output should be similar to the following:

          
        green open filebeat-7.8.0-2020.07.07-000001 6CYTk-UWQSeG7Y5-XjbQww 1 1 16975 0 10mb 5.8mb
            
        

      Install Kibana

      Kibana provides a frontend to Elasticsearch and the data collected by Filebeat.

      1. Deploy the kibana chart:

        helm install kibana elastic/kibana
        

        An output similar to the following appears:

          
        NAME: kibana
        LAST DEPLOYED: Tue Jul  7 15:40:21 2020
        NAMESPACE: default
        STATUS: deployed
        REVISION: 1
        TEST SUITE: None
        
        
      2. Port-forward the kibana-kibana service in order to access Kibana locally. Leave this command running in the background as well for the remainder of this tutorial.

        kubectl port-forward svc/kibana-kibana 5601:5601
        

        Note

        This command times out after 5 minutes, if you find that and want to have the port forward for longer, consider using the following command to keep it open: while true; do kubectl port-forward svc/kibana-kibana 5601:5601; done

      Configure Kibana

      Before visualizing Pod logs, Kibana must be configured with an index pattern for Filebeat’s indices.

      1. With the previous port-forward command running in another terminal window, open a browser and navigate to http://localhost:5601

      2. A welcome page similar to the following appears in the browser. Click the Explore on my own button.

        Kibana Welcome Page

      3. Open the menu, then go to Stack Management > Kibana > Index Patterns to create a new index pattern. The Index patterns page appears.

      4. Click the Create index pattern button to begin.

        Kibana Index Patterns Page

      5. In the Define index pattern window, type filebeat-* in the Index pattern text box and click the Next step button.

        Kibana Create Index Pattern

      6. In the Configure settings window, select @timestamp from the Time Filter field name dropdown menu and click the Create index pattern button.

        Kibana Create Index Pattern

      7. A page with the index pattern details appears. Open the menu, then go to Kibana > Discover to view incoming logs.

        Kibana Select Discover

      8. The Discover page provides a realtime view of logs as they are ingested by Elasticsearch from the Kubernetes cluster. The histogram provides a view of log volume over time, which by default, spans the last 15 minutes. The sidebar on the left side of the user interface displays various fields parsed from JSON fields sent by Filebeat to Elasticsearch.

      9. Use the Filters box to search only for logs arriving from Kibana Pods by filtering for kubernetes.container.name : "kibana". Click the Update button to apply the search filter.

        Note

        When searching in the filters box, field names and values are auto-populated.

        Kibana Filter

      10. In order to expand a log event, click the arrow next to an event in the user interface.

        Kibana Open Log Event

      11. Scroll down to view the entire log document in Kibana. Observe the fields provided by Filebeat, including the message field, which contains standard out and standard error messages from the container, as well as the Kubernetes node and Pod name in fields prefixed with kubernetes.

        Kibana Log Document

      12. Look closely at the message field in the log representation and note that the text field is formatted as JSON. While the terms in this field can be searched with free text search terms in Kibana, parsing the field generally yields better results.

      Metricbeat

      In addition to collecting logs with Filebeat, Metricbeat can collect Pod and node metrics in order to visualize information such as resource utilization.

      Install Metricbeat

      1. Deploy the metricbeat chart.

        helm install metricbeat elastic/metricbeat
        

        An output similar to the following appears:

          
        NAME: metricbeat
        LAST DEPLOYED: Tue Jul  7 18:43:58 2020
        NAMESPACE: default
        STATUS: deployed
        REVISION: 1
        TEST SUITE: None
        NOTES:
        1. Watch all containers come up.
           $ kubectl get pods --namespace=default -l app=metricbeat-metricbeat -w
        
        
      2. Confirm that Metricbeat has started to index documents into Elasticsearch by sending a request to the locally-forwarded Elasticsearch service port:

        curl http://localhost:9200/_cat/indices
        

        At least one metricbeat index should be present, similar to the following:

          
        green open metricbeat-7.8.0-2020.07.07-000001 wAWu5op1SJqlbaXKOj_tSg 1 1  1214 0   3.5mb   1.7mb
        
        

      Load Dashboards

      Metricbeat can install default Dashboards into Kibana to provide out-of-the-box visualizations for data collected by Kubernetes.

      Before following these steps, ensure that the port-forward command to expose Kibana over port 5601 locally is still running.

      Run the following commands on the local machine. This communicates with Kibana over 127.0.0.1:5601 to import default Dashboards that is populated with data from Metricbeat.

      Note

      The commands should use the same version of Metricbeat deployed to the Kubernetes cluster. You can find this version by issuing the following command:

      helm get values --all metricbeat | grep imageTag
      

      For Linux

      1. Get the Metricbeat package.

        wget https://artifacts.elastic.co/downloads/beats/metricbeat/metricbeat-7.8.0-linux-x86_64.tar.gz
        
      2. Unzip the package.

        tar xvzf metricbeat-7.8.0-linux-x86_64.tar.gz
        
      3. Navigate to the directory.

        cd metricbeat-7.8.0-linux-x86_64
        
      4. Setup the dashboards.

        ./metricbeat setup --dashboards
        

      For MacOS

      1. Get the Metricbeat package.

        curl -L -O https://artifacts.elastic.co/downloads/beats/metricbeat/metricbeat-7.8.0-darwin-x86_64.tar.gz
        
      2. Unzip the package.

        tar xzvf metricbeat-7.8.0-darwin-x86_64.tar.gz
        
      3. Navigate to the directory.

        cd metricbeat-7.8.0-darwin-x86_64
        
      4. Setup the dashboards.

        ./metricbeat setup --dashboards
        

      Explore Dashboards

      1. Open a browser window to http://localhost:5601 and click the Dashboards in the left sidebar.

        Kibana Dashboards Link

      2. In the search box, enter “kubernetes” and press Enter. Select the [Metricbeat Kubernetes] Overview ECS dashboard.

        Kibana Kubernetes Dashboards

      3. The following dashboard displays several types of metrics about the Kubernetes cluster.

        Kibana Kubernetes Dashboards

      4. You can explore the various visualizations on this page in order to view metrics about Pods, nodes, and the overall health of the Kubernetes cluster.

      Next Steps

      From this point onward, any additional workloads started in Kubernetes is processed by Filebeat and Metricbeat in order to collect logs and metrics for later introspection within Kibana. As Kubernetes nodes are added or removed, the Filebeat and Metricbeat DaemonSets automatically scale out Pods to monitor nodes as they join the Kubernetes cluster.

      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.

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



      Source link

      How To Install an ERPNext Stack on Ubuntu 20.04


      Not using Ubuntu 20.04?


      Choose a different version or distribution.

      The author selected Software in the Public Interest to receive a donation as part of the Write for DOnations program.

      Introduction

      ERPNext is an Enterprise Resource Planning (ERP) suite that leverages the power and flexibility of open-source technologies. It excels at managing core business processes such as finance, sales, human resources, manufacturing, purchases, services, helpdesk needs, and more. Among the benefits of implementing a system like ERPNext are:

      • Better productivity by automating repetitive business processes
      • Improved IT efficiency by sharing a database for all departments within the company
      • Better decision-making thanks to an integral vision of how business units relate to each other

      ERPNext is based on Frappe, a full-stack web application framework written in Python that takes full advantage of the Node/JavaScript runtime environment and uses MariaDB as its database backend. One of the many advantages of Frappe-based applications, like ERPNext, is the bench command-line utility. The bench CLI saves administrators time by automating tasks such as installing, updating, configuring, and managing multiple Frappe/ERPNext sites.

      In this tutorial you will install and configure an ERPNext stack on one server running Ubuntu 20.04. This will allow you to configure your stack for various development or production environments depending on your needs, and it will prepare you to build a more complex, fault-tolerant architecture.

      Prerequisites

      Note: When choosing your server’s specifications, keep in mind that ERP systems are resource-intensive. This guide calls for one server with 4 GB of RAM, which is sufficient for basic use cases, but specific hardware requirements may vary depending on the number of users as well as your business size.

      Step 1 — Configuring the Firewall

      Although configuring a firewall for development is optional, for production it is a mandatory security practice.

      You will need to open the following ports on your ERPNext server:

      • 80/tcp and 443/tcp for HTTP and HTTPS respectively
      • 3306/tcp for MariaDB connection (recommended only if you need remote access to database)
      • 143/tcp and 25/tcp for IMAP and STMP respectively
      • 22/tcp for SSH (if you have not already enabled OpenSSH in your UFW settings)
      • 8000/tcp for testing your platform before deploying to production

      To open multiple ports at once you can use the following command:

      • sudo ufw allow 22,25,143,80,443,3306,8000/tcp

      Alternatively, you can allow connections from specific IP addresses on specific ports using this command:

      • sudo ufw allow from server_IP to any port port_number

      After opening all necessary ports enable the firewall:

      Now confirm the status of your firewall:

      UFW will output a list of your enabled rules. Make sure ERPNext’s necessary ports are open:

      Output

      Status: active To Action From -- ------ ---- 22,25,80,143,443,3306,8000/tcp ALLOW Anywhere 22,25,80,143,443,3306,8000/tcp (v6) ALLOW Anywhere (v6)

      For more information regarding UFW’s configuration, consult our guide on how to set up a firewall with UFW on Ubuntu 20.04.

      Setting up a proper firewall is the first of two preliminary steps. Now you will configure keyboard mapping and character encoding on your server.

      Step 2 — Configuring Locales

      It’s highly recommended that you configure keyboard mapping for the console as well as the language and the character encoding on your host. This is necessary to avoid possible issues during the ERPNext 12 installation process. Take note that this configuration has nothing to do with the UI language on your actual ERPNext platform, but with the system locale configuration.

      First, update your server:

      Now configure keymap, language, and character encoding:

      • sudo localectl set-keymap us && sudo localectl set-locale LANG=en_US.utf8

      The localectl utility is used by Ubuntu 20.04 and other Linux distributions to control and change system-wide locale and keyboard layout settings before the user logs in, which is exactly what ERPNext 12 requires.

      You will also need to add the following lines to your /etc/environment file. Use nano or your preferred text editor to open the file:

      • sudo nano /etc/environment

      Now add the following content:

      /etc/environment

      LC_ALL=en_US.UTF-8
      LC_CTYPE=en_US.UTF-8
      LANG=en_US.UTF-8
      

      Save and close the file.

      Reboot your server to apply all changes:

      Give your server a few minutes to reboot and then use ssh to reenter your instance. You are now ready to install your database.

      Step 3 — Installing MariaDB

      Now you will add MariaDB to your server stack. ERPNext 12 requires MariaDB 10.2+ for proper operation. Because Ubuntu 20.04 includes MariaDB 10.3 in its official repositories you can install this version using the apt command:

      • sudo apt install mariadb-server

      Alternatively, if prefer a newer MariaDB version, you can follow Step 3 of our guide on how to install an ERPNext Stack on Ubuntu 18.04. This will guide you through MariaDB’s online repository wizard, which will help you install the newest version—MariaDB 10.5.

      After installing mariadb-server, install the following packages:

      • sudo apt install python3-mysqldb libmysqlclient-dev

      ERPNext 12 is a Python application and thus it requires the python3-mysqldb library for database management. libmysqlclient-dev is required to access certain MariaDB developer features.

      Next, add an extra layer of security to the MariaDB server by running the mysql_secure_installation script:

      • sudo mysql_secure_installation

      The mysql_secure_installation script will prompt you with several questions:

      • The first prompt will ask you about the root password, but since there is no password configured yet, press ENTER.
      • Next, when asked about changing the MariaDB root password, answer N. Using the default password along with Unix authentication is the recommended setup for Ubuntu-based systems because the root account is closely related to automated system maintenance tasks.
      • The remaining questions have to do with removing the anonymous database user, restricting the root account to log in remotely on localhost, removing the test database, and reloading privilege tables. It is safe to answer Y to all those questions.

      After completing the mysql_secure_installation script, MariaDB will start running using its default configuration. The standard ERPNext installation uses MariaDB’s root user for all database operations. While that approach may be convenient on single server setups, it is not considered a good security practice. Therefore, in the next section you will learn how to avoid this issue by creating a new user with special privileges.

      Creating a MariaDB Super Admin User

      ERPNext expects to use MariaDB’s root user for managing database connections, but this is not always ideal. To overcome this limitation and let a non-root user manage MariaDB you will now manually create a database named after the user. Then you will be able to assign special privileges to the new user to drive ERPNext database operations.

      Open up the MariaDB prompt:

      Now create a new database named after the user you want to assign for MariaDB connections. This tutorial will use sammy but you can choose a different name:

      Confirm that the database was created using this SQL statement:

      You will see an output similar to this:

      Output

      +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sammy | +--------------------+

      Now create the MariaDB user sammy with privileges similar to root and then give the user a strong password of your choice. Keep the password in a secure place; you will need it later:

      • GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'%' IDENTIFIED BY 'mariadb_password' WITH GRANT OPTION;

      Now confirm both the user creation and the new user’s privileges:

      • SELECT host, user, Super_priv FROM mysql.user;

      You will see an output like this:

      Output

      +-----------+-------+------------+ | Host | User | Super_priv | +-----------+-------+------------+ | localhost | root | Y | | localhost | mysql | Y | | % | sammy| Y | +-----------+-------+------------+ 3 rows in set (0.001 sec)

      Now flush privileges to apply all changes:

      Once you finish, exit the session:

      Now that you have created a database user you only need to fine-tune MariaDB to ensure proper ERPNext 12 operation. Fortunately, the ERPNext team provides an excellent configuration template that you will use as a starting point for your implementation. In the next section, you will learn how to properly configure the MariaDB database using that template.

      Step 4 — Configuring MariaDB for ERPNext

      With MariaDB installed and secured it’s time to fine-tune it for ERPNext connections.

      First, stop mariadb.service:

      • sudo systemctl stop mariadb

      Now use nano or your favorite text editor to create a MariaDB configuration file called mariadb.cnf:

      • sudo nano /etc/mysql/mariadb.conf.d/mariadb.cnf

      Now add ERPNext’s official configuration template:

      /etc/mysql/mariadb.conf.d/mariadb.cnf

      [mysqld]
      
      # GENERAL #
      user                           = mysql
      default-storage-engine         = InnoDB
      socket                         = /var/lib/mysql/mysql.sock
      pid-file                       = /var/lib/mysql/mysql.pid
      
      # MyISAM #
      key-buffer-size                = 32M
      myisam-recover                 = FORCE,BACKUP
      
      # SAFETY #
      max-allowed-packet             = 256M
      max-connect-errors             = 1000000
      innodb                         = FORCE
      
      # DATA STORAGE #
      datadir                        = /var/lib/mysql/
      
      # BINARY LOGGING #
      log-bin                        = /var/lib/mysql/mysql-bin
      expire-logs-days               = 14
      sync-binlog                    = 1
      
      # REPLICATION #
      server-id                      = 1
      
      # CACHES AND LIMITS #
      tmp-table-size                 = 32M
      max-heap-table-size            = 32M
      query-cache-type               = 0
      query-cache-size               = 0
      max-connections                = 500
      thread-cache-size              = 50
      open-files-limit               = 65535
      table-definition-cache         = 4096
      table-open-cache               = 10240
      
      # INNODB #
      innodb-flush-method            = O_DIRECT
      innodb-log-files-in-group      = 2
      innodb-log-file-size           = 512M
      innodb-flush-log-at-trx-commit = 1
      innodb-file-per-table          = 1
      innodb-buffer-pool-size        = 5462M
      innodb-file-format             = barracuda
      innodb-large-prefix            = 1
      collation-server               = utf8mb4_unicode_ci
      character-set-server           = utf8mb4
      character-set-client-handshake = FALSE
      max_allowed_packet             = 256M
      
      # LOGGING #
      log-error                      = /var/lib/mysql/mysql-error.log
      log-queries-not-using-indexes  = 0
      slow-query-log                 = 1
      slow-query-log-file            = /var/lib/mysql/mysql-slow.log
      
      # CONNECTIONS #
      
      pid-file        = /var/run/mysqld/mysqld.pid
      socket          = /var/run/mysqld/mysqld.sock
      bind-address    = 0.0.0.0
      
      [mysql]
      default-character-set = utf8mb4
      
      [mysqldump]
      max_allowed_packet=256M
      

      Save and close the file. For more detailed information about these configurations, review this template file on ERPNext’s Github repo. This is a useful starting point for exploring these options.

      The configuration file, /etc/mysql/mariadb.conf.d/mariadb.cnf, complements and also overrides a few values included in the default MariaDB configuration located at /etc/mysql/my.cnf. This file gives you a curated template that greatly enhances database performance for ERPNext. Keep in mind, however, that while this template is a great starting point nothing prevents you from improving MariaDB’s performance even further by adjusting these parameters to fit your needs.

      Testing the MariaDB Connection

      Since ERPNext relies on the database connection for almost all of its internal operations, it is a good idea to test the connection before continuing.

      Start mariadb.service:

      • sudo systemctl start mariadb

      To test the connection you can use the following command. Remember to replace sammy and mariadb_password with your credentials:

      • mysql --user sammy --password mariadb_password --host=localhost --protocol=tcp --port=3306 test

      You will see an output showing MariaDB’s basic help content and several parameters. This means your connection was successful:

      Output

      mysql Ver 15.1 Distrib 10.4.13-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2 Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Usage: mysql [OPTIONS] [database] Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf ... --ssl-verify-server-cert Verify server's "Common Name" in its cert against hostname used when connecting. This option is disabled by default. -t, --table Output in table format. --tee=name Append everything into outfile. See interactive help (h) also. Does not work in batch mode. Disable with --disable-tee. This option is disabled by default. -u, --user=name User for login if not current user. -U, --safe-updates Only allow UPDATE and DELETE that uses keys. -U, --i-am-a-dummy Synonym for option --safe-updates, -U. -v, --verbose Write more. (-v -v -v gives the table output format). ... max-join-size 1000000 secure-auth FALSE show-warnings FALSE plugin-dir (No default value) default-auth (No default value) binary-mode FALSE connect-expired-password FALSE

      If you need to make any adjustments to MariaDB’s settings or fix any errors, remember to reload the service using the following command:

      • sudo systemctl restart mariadb

      Once you are done, enable MariaDB:

      • sudo systemctl enable mariadb

      Now that you have tested the database connection, you can continue with the installation of your ERPNext application.

      Step 5 — Setting Up ERPNext 12

      Now that your database backend is ready you can continue setting up your ERPNext web application. In this section, you will learn how to install and configure all components required by ERPNext 12 and then install the application itself.

      Start by preparing the server with all the system packages required by ERPNext 12. Install system-wide dependencies using the following command:

      • sudo DEBIAN_FRONTEND=noninteractive apt install -y curl build-essential python3-testresources python3-setuptools python3-dev libffi-dev python3-pip libcurl4 dnsmasq fontconfig git htop libcrypto++-dev libfreetype6-dev liblcms2-dev libwebp-dev libxext6 libxrender1 libxslt1-dev libxslt1.1 libffi-dev ntpdate postfix python3-dev python-tk screen vim xfonts-75dpi xfonts-base zlib1g-dev apt-transport-https libsasl2-dev libldap2-dev libcups2-dev pv libjpeg8-dev libtiff5-dev tcl8.6-dev tk8.6-dev libdate-manip-perl logwatch

      The DEBIAN_FRONTEND=noninteractive variable has been passed to the installation command in order to avoid Postfix prompts. For detailed information regarding Postfix configuration please read our guide on How To Install and Configure Postfix on Ubuntu 20.04

      Next, update pip3, which is Python’s standard package manager, and then install the latest versions of three additional Python modules:

      • sudo -H python3 -m pip install --upgrade setuptools cryptography psutil

      setuptools facilitates the installation and upgrading of Python packages, cryptography adds encryption capabilities to your stack, and psutil aids with system monitoring. Now that you have installed all necessary global dependencies, you will now install all the services and libraries required by ERPNext 12.

      Setting Up Node.js and Yarn

      ERPNext 12 can work with version 8+ of the Node.js server environment. In fact, at the time of this writing, the official ERPNext easy_install script uses Node 8. But from a security perspective, it’s advisable to install a newer version because Node 8 reached its End Of Life (EOL) in 2020 and thus will not receive any more security patches. At the time of this writing, Ubuntu 20.04 contains version 10.19 of Node.js. Although this version is still maintained, for similar reasons (EOL in less than a year) it’s highly advisable to avoid using it. For this guide, Node.js version 12 LTS will be installed along with the corresponding npm and yarn package managers. Please note that the Frappe framework uses yarn to install dependencies. If you decide to use an alternative installation method then make sure that you end up with version 1.12+ of yarn running in your system.

      Add the NodeSource repository to your system:

      • curl -sL https://deb.nodesource.com/setup_12.x -o nodesource_setup.sh

      Now you can inspect the contents of the downloaded script:

      • sudo nano nodesurce_setup.sh

      Once you are satisfied with the script’s contents you can run the script:

      • sudo bash nodesource_setup.sh

      This script will automatically update the apt list. Now you can install nodejs on your server:

      Next, install yarn globally using the npm package manager:

      Now that you have installed Node you can continue to configure wkhtmltopdf for your platform.

      ERPNext uses the wkhtmltopdf open source tool to convert HTML content into PDF using the Qt WebKit rendering engine. This feature is mostly used for printing invoices, quotations, and other reports. In the case of ERPNext 12, a specific version of wkhtmltopdf is required, 0.12.5 with patched Qt.

      To install wkhtmltopdf, start by switching to a suitable directory to download the package, in this case /tmp:

      Download the appropriate wkhtmltopdf version and package for Ubuntu 20.04 from the project’s page:

      • wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.5/wkhtmltox_0.12.5-1.bionic_amd64.deb

      Now install the package using the dpkg tool:

      • sudo dpkg -i wkhtmltox_0.12.5-1.bionic_amd64.deb

      Next, copy all relevant executables to your /usr/bin/ directory:

      • sudo cp /usr/local/bin/wkhtmlto* /usr/bin/

      Once the files are in place, change their permissions to make them executable:

      • sudo chmod a+x /usr/bin/wk*

      Now that wkhtmltopdf is properly installed we will add Redis to our database stack.

      Installing Redis

      ERPNext 12 uses Redis to enhance MariaDB’s performance. Specifically, Redis assists with caching.

      First, install Redis from the official Ubuntu 20.04 repository:

      • sudo apt install redis-server

      Then enable Redis on startup:

      • sudo systemctl enable redis-server

      Now that you have added Redis to your stack let’s take a moment to summarize what you have accomplished so far. Up to this point, you have installed all the major components required by ERPNext 12, which include:

      • A MariaDB database backend
      • The Node.js JavaScript server environment
      • The Yarn package manager
      • A Redis database cache
      • The wkhtmltopdf PDF documents generator

      Whether you are installing the ERP system for development or for production, you are now ready for the next step, which is installing the Frappe full-stack framework and the actual ERPNext 12 web application.

      Step 6 — Installing Frappe Bench CLI

      Now that you have installed all of ERPNext’s stack requirements you can unleash the flexibility of Frappe’s bench command-line utility. The bench CLI was designed with the purpose of assisting users in the process of installing, setting up, and managing applications like ERPNext that are based on the Frappe Framework. In the coming sections, you will install the bench CLI and then use it to complete the process of setting up ERPNext 12.

      Make sure that the Frappe user (in this case sammy) has the proper rights on its home directory:

      • sudo chown sammy -R /home/sammy

      Now clone the frappe/bench repository to your home directory. Remember to replace sammy with your system username:

      • git clone https://github.com/frappe/bench /home/sammy/.bench --depth 1 --branch master

      Install the bench CLI:

      • sudo pip3 install -e /home/sammy/.bench

      This guide is assuming that you are installing ERPNext 12 for testing/production scenarios and thus that you are using the master branch. But if your intention is to develop applications or custom ERPNext modules, then the develop branch might be a better option. In either case, you are now prepared to install the Frappe Framework. This will be your final step before installing ERPNext itself.

      Setting Up Frappe Framework Environment

      In this section, you will create a Frappe environment using the bench CLI.

      During Frappe’s installation you may exceed Ubuntu’s file watch limit, which by default is set to 8192. To avoid this issue set a higher limit using the following command:

      • echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

      The tee command will append the contents of your echo command to the called file while also printing the output to your console.

      Next, initialize Frappe Framework 12. Replace Sammy with your system username:

      • bench init /home/sammy/frappe-bench --frappe-path https://github.com/frappe/frappe --frappe-branch version-12 --python python3

      During execution you may see one error about your path, along with several warnings. Let the process continue until the end. Once it’s finished, you will see an output similar to the following one, indicating that your environment was successfully created:

      Output

      ... Done in 82.23s. INFO:bench.utils:setting up backups no crontab for sammy SUCCESS: Bench /home/sammy/frappe-bench initialized

      Note: The bench init process could halt if a spawn ENOMEM error is encountered. This error is caused when your system runs out of memory. You must fix the issue before continuing, either by installing more physical memory or allocating SWAP space.

      Let’s take a closer look at the command used to create the environment:

      • /home/sammy/frappe-bench is the path where the Frappe Framework, the websites, and associated applications will be installed. A new directory, called frappe-bench in this example, will be created to accommodate all necessary files.
      • --frappe-path points to Frappe repository, which in this case is the official Github repository.
      • --frappe-branch is the Frappe version to be installed. Because you want to install ERPNext 12, the chosen version is Frappe 12.
      • --python is the Python version that will be used. ERPNext 12 requires Python 3.6+. Prior versions, however, still use Python 2.7.

      For more information regarding bench CLI commands please refer to the Bench Commands Cheatsheet.

      The flexibility offered by the Frappe framework goes way beyond using isolated environments. You can also create different websites and install applications into them.

      Step 7 — Installing the ERPNext 12 Web Application

      In this section, you will set up a Frappe-based site and then install the ERPNext 12 application on it.

      Change to the directory where Frappe was initialized.

      • cd /home/sammy/frappe-bench

      Before continuing, you will need to install specific versions of Python libraries numpy and pandas into the Frappe virtual environment. Install these packages using the following command:

      • ./env/bin/pip install numpy==1.18.5 && ./env/bin/pip install pandas==0.24.2

      At this point the installation might halt for about 10 to 20 minutes while displaying this message:

      Output

      ... Building wheel for pandas (setup.py) ... -

      This has to do with a bug related to pandas and Ubuntu 20.04, which, at the time of writing, is still rather new. Nevertheless the packages will build, and once they complete you will see an output like this:

      Output

      ... Successfully built pandas Installing collected packages: pandas Successfully installed pandas-0.24.2

      Now, you can continue with the installation. Download ERPNext 12 from its repository using the bench CLI:

      • bench get-app erpnext https://github.com/frappe/erpnext --branch version-12

      Next, create the new site, replacing your_domain with the domain that you have associated with this server’s IP:

      • bench new-site your_domain --admin-password 'erpnext_admin_password' --mariadb-root-username sammy --mariadb-root-password 'mariadb_password'

      Let’s take a moment to review the options used in the command above:

      • bench new-site creates a new site based on the Frappe Framework.
      • your_domain is the name for the new site. Make sure that your domain’s DNS has an A record pointing at your server’s IP.
      • erpnext_admin_password is the desired password for ERPNext’s Administrator user. Keep this password in a safe place—you will need it shortly.
      • mariadb_password is the password that you created at the beginning of the guide for the MariaDB user sammy.

      Following this, install the ERPNext application onto the site:

      • bench --site your_domain install-app erpnext

      Once the installation completes, you will have a working ERPNext 12 application. Now let’s test it using a bench command:

      The above will initiate a real-time monitoring console showing you various messages regarding the webserver and other services. Open a web browser and navigate to localhost:8000 (for local installations) or your_domain:8000 (if you are using a remote server). You will see the ERPNext login screen (we will proceed with login and setup in a later step, once we have made our site production-ready).

      After visiting your test deployment, return to your terminal and press CTRL+C. This will stop ERPNext and exit the monitoring console.

      If your main goal is creating modules or modifying ERPNext 12, then you could stop at this point. No more components are needed for development purposes. However, if what you need is a production-ready system that does not require a manual initialization, then you will need to install and configure a few additional components. This is your next step.

      Step 8 — Setting Up ERPNext 12 For Production

      Although your ERPNext 12 application is ready, the system as a whole is not yet prepared for production. To ensure ERPNext’s reliability and security you will need to enable a few additional services:

      • Fail2ban provides an extra layer of protection against brute force attempts from malicious users and bots.
      • Nginx functions mainly as a web proxy, redirecting all traffic from port 8000 to port 80 (HTTP) or port 443 (HTTPS)
      • Supervisor ensures that ERPNext’s key processes are constantly up and running, restarting them as necessary.

      Up to this point, you have installed and configured ERPNext 12 manually, which has allowed you to customize the process to match any particular use case. Nevertheless, for the rest of the production setup, you can leverage the convenience of the bench CLI and let it automate the installation and configuration of these remaining services.

      Ensure you are in the Frappe working directory:

      • cd /home/sammy/frappe-bench

      Now use the following command to finish setting up ERPNext 12 for production:

      • sudo bench setup production sammy --yes

      The above will install and configure Nginx, Supervisor, and Fail2Ban and set sammy as the production environment owner.

      The configuration files created by the bench command are:

      • Two Nginx configuration files located at /etc/nginx/nginx.conf and /etc/nginx/conf.d/frappe-bench.conf
      • One Fail2Ban proxy jail located at /etc/fail2ban/jail.d/nginx-proxy.conf and one filter located at /etc/fail2ban/filter.d/nginx-proxy.conf

      These default configurations will suffice for this tutorial, but you should feel free to explore and adjust these files to match your requirements. You can stop all services by running:

      • sudo supervisorctl stop all

      And then, once you are ready, you can restart your services:

      • sudo supervisorctl start all

      Now you are ready to test your installation.

      Testing Your ERPNext 12 Installation

      First of all, verify that key production services are running. Use the following systemctl command and then pipe it to grep:

      • systemctl list-unit-files | grep 'fail2ban|nginx|supervisor'

      You will see an output like this:

      Output

      fail2ban.service enabled nginx.service enabled supervisor.service enabled

      After confirming that everything is working as expected, you can test ERPNext 12 live on your server. Open your favorite browser and navigate your_domain, or whereever you are hosting your ERPNext 12 application.

      After a few seconds, you should see the ERPNext 12 login screen. Use Administrator for the username (email) and the erpnext_admin_password you created previously for the password.

      ERPNext Login Screen

      In the next screen you will see a dropdown menu where you can select the UI language for the application:

      Language Selection

      Following language selection, ERPNext will prompt you about your country, timezone, and currency:

      Select Your Region

      Once you complete your region information, you will be able to create your first ERPNext user. The information you provide will be used as the user’s login credentials.

      First ERPNext User

      In the next screen, you will be asked about what ERPNext calls Domains. If you are not sure what your domain is, then select Distribution and click the Next button.

      Select your Domains

      Next, you will need to provide a company name and abbreviation.

      Company Name

      On the last screen, ERPNext will ask you what your company does, its bank name, the type of charts of accounts, and the fiscal year period. You will be able to enter additional banks later. For now, fill in all the fields as you like and then click the Complete Setup button.

      Financial Information

      Next, you will see a progress bar.

      Setting Up ERPNext

      Once the setup process completes, the ERPNext 12 main Dashboard will appear.

      ERPNext 12 Dashboard

      You now have fully installed and configured an ERPNext 12 application.

      Conclusion

      Now that you have properly installed your ERPNext 12 application, you might want to start implementing the system for your business needs. A good starting point is clicking the Getting Started button on the ERPNext Dashboard. ERPNext will then help you configure the platform for all your business and e-commerce needs.

      Getting Started

      You may also wish to enhance ERPNext’s speed. If that is the case, then you can read about ERPNext performance tuning, which will guide you through best practices and how to debug performance-related issues.



      Source link