One place for hosting & domains

      How to Use APT to Manage Packages in Debian and Ubuntu


      Advanced Package Tool, more commonly known as
      APT, is a package management system for Ubuntu, Debian, Kali Linux, and other Debian-based Linux distributions. It acts as a front-end to the lower-level
      dpkg package manager, which is used for installing, managing, and providing information on .deb packages. In addition to these functions, APT interfaces with repositories to obtain packages and also provides very efficient dependency management.

      Most distributions that use APT also include a collection of command-line tools that can be used to interface with APT. These tools include apt-get, apt-cache, and the newer apt, which essentially combines both of the previous tools with some modified functionality. Other package managers and tools also exist for interacting with APT or dpkg. A popular one is called
      Aptitude. Aptitude includes both a command-line interface as well as an interactive user interface. While it does offer advanced functionality, it is not commonly installed by default and is not covered in this guide.

      This guide aims to walk you through using APT and its command-line tools to perform common functions related to package management. The commands and examples used throughout this guide default to using the apt command. Many of the commands interchangeable with either apt-get or apt-cache, though there may be breaking differences.

      Before You Begin

      Before running the commands within this guide, you will need:

      1. A system running on Debian or Ubuntu. Other Linux distributions that employ the APT package manager can also be used. Review the
        Creating a Compute Instance guide if you do not yet have a compatible system.

      2. Login credentials to the system for either the root user (not recommended) or a standard user account (belonging to the sudo group) and the ability to access the system through
        SSH or
        Lish. Review the
        Setting Up and Securing a Compute Instance guide for assistance on creating and securing a standard user account.

      Note

      Some commands in this guide require elevated privileges and are prefixed with the sudo command. If you are logged in as the root use (not recommended), you can omit the sudo prefix if desired. If you’re not familiar with the sudo command, see the
      Linux Users and Groups guide.

      What’s the difference between apt and apt-get/apt-cache?

      While there are more similarities than differences, there are a few important points to consider when decided which command to use.

      • apt: A newer end-user tool that consolidates the functionality of both apt-get and apt-cache. Compared to the others, the apt tool is more straightforward and user-friendly. It also has some extra features, such as a status bar and the ability to list packages. Both Ubuntu and Debian recommend the apt command over apt-get and apt-cache. See
        apt Ubuntu man pages
      • apt-get and apt-cache: The apt-get command manages the installation, upgrades, and removal of packages (and their dependencies). The apt-cache command is used to search for packages and retrieve details about a package. Updates to these commands are designed to never introduce breaking changes, even at the expense of the user experience. The output works well for machine readability and these commands are best limited to use within scripts. See
        apt-get Ubuntu man pages and
        apt-cache Ubuntu man pages.

      In short, apt is a single tool that encompasses most of the functionality of other APT-specific tooling. It is designed primarily for interacting with APT as an end-user and its default functionality may change to include new features or best practices. If you prefer not to risk breaking compatibility and/or prefer to interact with plainer output, apt-get and apt-cache can be used instead, though the exact commands may vary.

      Installing Packages

      Installs the specified package and all required dependencies. Replace [package] with the name of the package you wish to install. The apt install command is interchangeable with apt-get install.

      sudo apt install [package]
      

      Before installing packages, it’s highly recommended to obtain updated package version and dependency information and upgrade packages and dependencies to those latest version. See
      Updating Package Information and
      Upgrading Packages for more details. These actions can be performed quickly by running the following sequence of commands:

      sudo apt update && sudo apt upgrade
      

      Additional options, commands, and notes:

      • Install a specific version by adding an equal sign after the package, followed by the version number you’d like to install.

        sudo apt install [package]=[version]
        
      • Reinstall a package and any dependencies by running the following command. This is useful if an installation for a package becomes corrupt or dependencies were somehow removed.

        sudo apt reinstall [package]
        

      Updating Package Information

      Downloads package information from all the sources/repositories configured on your system (within /etc/apt/sources.list). This command obtains details about the latest version for all available packages as well as their dependencies. It should be the first step before installing or upgrading packages on your system.

      sudo apt update
      

      This command is equivalent to apt-get update.

      Upgrading Packages

      Upgrades all packages to their latest versions, including upgrading existing dependencies and installing new ones. It’s important to note that the currently installed versions are not removed and will remain on your system.

      sudo apt upgrade
      

      This command is equivalent to apt-get upgrade --with-new-pkgs. Without the --with-new-pkgs option, the apt-get upgrade command only upgrades existing packages/dependencies and ignores any packages that require new dependencies to be installed.

      Before upgrading packages, it’s highly recommended to obtain updated package version and dependency information. See
      Updating Package Information for more details. These two actions can be performed together through the following sequence of commands:

      sudo apt update && sudo apt upgrade
      

      Additional options, commands, and notes:

      • To view a list of all available upgrades, use the list command with the --upgradable option.

        apt list --upgradeable
        
      • To upgrade a specific package, use the install command and append the package name. If the package is already installed, it will be upgraded to the latest version your system knows about. To only upgrade (not install) a package, use the --only-upgrade option. In the below command, replace [package] with the name of the package you wish to upgrade.

        sudo apt install --only-upgrade [package]
        
      • The apt full-upgrade command (equivalent to apt-get dist-upgrade) can remove packages as well as upgrade and install them. In most cases, it is not recommended to routinely run these commands. To remove unneeded packages (including kernels), use apt autoremove instead.

      Uninstalling Packages

      Removes the specified package from the system, but retains any packages that were installed to satisfy dependencies as well as some configuration files. Replace [package] with the name of the package you’d like to remove.

      sudo apt remove [package]
      

      To remove the package as well as any configuration files, run the following command. This can also be used to just remove configuration files for previously removed packages.

      sudo apt purge [package]
      

      Both of these commands are equivalent to apt-get remove and apt-get purge, respectively.

      • To remove any unused dependencies, run apt autoremove (apt-get autoremove). This is commonly done after uninstalling a package or after upgrading packages and can sometimes help in reducing disk space (and clutter).

        sudo apt autoremove
        

      Common Command Options

      The following options are available for most of the commands discussed on this guide.

      • Multiple packages can be taken action on together by delimiting them with a space. For example:

        sudo apt install [package1] [package2]
        
      • Automatically accept prompts by adding the -y or --yes option. This is useful when writing scripts to prevent any user interaction when its implicit that they wish to perform the action on the specified packages.

        sudo apt install [package] -y
        

      Listing Packages

      The apt list command lists all available, installed, or upgradeable packages. This can be incredibly useful for locating specific packages – especially when combined with grep or less. There is no direct equivalent command within apt-cache.

      • List all packages that are installed

        apt list --installed
        
      • List all packages that have an upgrade available

        apt list --upgradeable
        
      • List all versions of all available packages

        apt list --all-versions
        

      Additional options, commands, and notes:

      • Use
        grep to quickly search through the list for specific package names or other strings. Replace [string] with the package name or other term you wish to search for.

        apt list --installed | grep [string]
        
      • Use a content viewer like
        less to interact with the output, which may help you view or search for your desired information.

        apt list --installed | less
        

      Searching for Available Packages

      Searches through all available packages for the specified term or regex string.

      apt search [string]
      

      The command apt-cache search is similar, though the output for apt search is more user-friendly.

      Additional options, commands, and notes:

      • Use the --full option to see the full description/summary for each package.

        apt search --full [string]
        
      • To find packages whose titles or short/long descriptions contain multiple terms, delimit each string with a space.

        apt search [string1] [string2]
        

      Viewing Information About Packages

      Displays information about an installed or available package. The following command is similar to apt-cache show --no-all-versions [package].

      apt show [package]
      

      The information in the output includes:

      • Package: The name of the package.
      • Version: The version of the package.
      • Installed-Size: The amount of space this package consumes on the disk, not including any dependencies.
      • Depends: A list of dependencies.
      • APT-Manual-Installed: Designates if the package was manually installed or automatically installed (for instance, like as a dependency for another package). This is visible within apt (not apt-cache).
      • APT-Sources: The repository where the package information was stored. This is visible within apt (not apt-cache).
      • Description: A long description of the package.

      Adding Repositories

      A repository is a collection of packages (typically for a specific Linux distribution and version) that are stored on a remote system. This enables software distributors to store a package (including new versions) in one place and enable users to quickly install that package onto their system. In most cases, we obtain packages from a repository – as opposed to manually downloading package files.

      Information about repositories that are configured on your system are stored within /etc/apt/sources.list or the directory /etc/apt/sources.list.d/. Repositories can be added manually by editing (or adding) a sources.list configuration file, though most repositories also require adding the GPG public key to APT’s keyring. To automate this process, it’s recommended to use the
      add-apt-repository utility.

      sudo add-apt-repository [repository]
      

      Replace [repository] with the url to the repository or, in the case of a PPA (Personal Package Archive), the reference to that PPA.

      Once a repository has been added, you can update your package list and install the package. See
      Updating Package Information and
      Installing Packages.

      Cloning Packages to Another System

      If you wish to replicate the currently installed packages to another system without actually copying over any other data, consider using the
      apt-clone utility. This software is compatible with Debian-based systems and is available through Ubuntu’s official repository.

      1. Install apt-clone.

        sudo apt install apt-clone
        
      2. Create a backup containing a list of all installed packages, replacing [name] with the name of the backup (such as my-preferred-packages)

        apt-clone clone [name]
        

        This command creates a new file using the name provided in the last step and appending .apt-clone.tar.gz.

      3. Copy the file to your new system. See the
        Download Files from Your Linode guide or the
        File Transfer section for more information.

      4. Install apt-clone on the new system (see Step 1).

      5. Using apt-clone, run the following command to restore the packages. Replace [name] with the name used in the previous step (or whatever the file is called). If the file is located within a different directly than your current directory, adjust the command to include the path.

        sudo apt-clone restore [name].apt-clone.tar.gz



      Source link

      Cómo instalar MongoDB desde los repositorios APT predeterminados de Ubuntu 20.04


      Introducción

      MongoDB es una base de datos de documentos gratuita y de código abierto utilizada comúnmente en las aplicaciones web modernas.

      En este tutorial, instalará MongoDB, administrará su servicio y, de forma opcional, habilitará el acceso remoto.

      Nota: Al momento de la publicación de este artículo, este tutorial instala la versión 3.6 de MongoDB, que es la versión disponible en los repositorios predeterminados de Ubuntu. Sin embargo, generalmente recomendamos instalar la versión más reciente de MongoDB, es decir, la versión 4.4 al momento de la publicación de este artículo. Si desea instalar la versión más reciente de MongoDB, le recomendamos que siga esta guía sobre Cómo instalar MongoDB en Ubuntu 20.04.

      Requisitos previos

      Para seguir este tutorial, necesitará lo siguiente:

      Paso 1: Instalar MongoDB

      En los repositorios oficiales de paquetes de Ubuntu se incluye MongoDB, lo que significa que podemos instalar los paquetes necesarios utilizando apt. Como se mencionó en la introducción, la versión disponible en los repositorios predeterminados no es la más reciente. Para instalar la versión más reciente de Mongo, siga este tutorial.

      Primero, actualice la lista de paquetes para tener la versión más reciente de listados de repositorios:

      A continuación, instale el propio paquete de MongoDB:

      Este comando le solicitará confirmar que quiere instalar el paquete mongodb y sus dependencias. Para hacerlo, presione Y y, luego, ENTER.

      Este comando instala varios paquetes que contienen una versión estable de MongoDB, junto con herramientas de administración útiles para el servidor de MongoDB. El servidor de la base de datos se inicia de forma automática tras la instalación.

      A continuación, comprobaremos que el servidor esté activo y funcione de forma correcta.

      Paso 2: Comprobar el servicio y la base de datos

      El proceso de instalación inició MongoDB de forma automática, pero verificaremos que el servicio se inicie y que la base de datos funcione.

      Primero, compruebe el estado del servicio:

      • sudo systemctl status mongodb

      Verá este resultado:

      Output

      ● mongodb.service - An object/document-oriented database Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2020-10-08 14:23:22 UTC; 49s ago Docs: man:mongod(1) Main PID: 2790 (mongod) Tasks: 23 (limit: 2344) Memory: 42.2M CGroup: /system.slice/mongodb.service └─2790 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf

      Según este resultado, el servidor MongoDB está funcionando.

      Podemos verificar esto en profundidad estableciendo conexión con el servidor de la base de datos y ejecutando el siguiente comando de diagnóstico. Con esto se mostrarán la versión actual de la base de datos, la dirección y el puerto del servidor, y el resultado del comando status:

      • mongo --eval 'db.runCommand({ connectionStatus: 1 })'

      Output

      MongoDB shell version v3.6.8 connecting to: mongodb://127.0.0.1:27017 Implicit session: session { "id" : UUID("e3c1f2a1-a426-4366-b5f8-c8b8e7813135") } MongoDB server version: 3.6.8 { "authInfo" : { "authenticatedUsers" : [ ], "authenticatedUserRoles" : [ ] }, "ok" : 1 }

      Un valor de 1 para el campo ok en la respuesta indica que el servidor funciona correctamente.

      A continuación, veremos la forma de administrar la instancia del servidor.

      Paso 3: Gestionar el servicio de MongoDB

      El proceso de instalación descrito en el Paso 1 configura MongoDB como servicio de systemd, lo que significa que puede administrarlo utilizando comandos systemctl estándares, junto con todos los demás servicios de sistema en Ubuntu.

      Para verificar el estado del servicio, escriba lo siguiente:

      • sudo systemctl status mongodb

      Puede detener el servidor en cualquier momento escribiendo lo siguiente:

      • sudo systemctl stop mongodb

      Para iniciar el servidor cuando esté detenido, escriba lo siguiente:

      • sudo systemctl start mongodb

      También puede reiniciar el servidor con el siguiente comando:

      • sudo systemctl restart mongodb

      Por defecto, MongoDB se configura para iniciarse de forma automática con el servidor. Si desea desactivar el inicio automático, escriba lo siguiente:

      • sudo systemctl disable mongodb

      Puede volver a habilitar el inicio automático en cualquier momento con el siguiente comando:

      • sudo systemctl enable mongodb

      A continuación, ajustaremos la configuración del firewall para nuestra instalación MongoDB.

      Paso 4: Ajustar el firewall (opcional)

      Suponiendo que siguió las instrucciones del tutorial de configuración inicial para servidores para habilitar el firewall en su servidor, no será posible acceder al servidor de MongoDB desde Internet.

      Si tiene intención de usar el servidor de MongoDB solo a nivel local con aplicaciones que se ejecuten en el mismo servidor, este es el ajuste recomendado y seguro. Sin embargo, si desea poder conectarse con su servidor MongoDB desde Internet, deberá permitir las conexiones entrantes añadiendo una regla UFW.

      Para permitir el acceso a MongoDB en su puerto predeterminado 27017 desde cualquier parte, podría ejecutar sudo ufw allow 27017. Sin embargo, permitir el acceso a Internet al servidor de MongoDB en una instalación predeterminada proporciona acceso ilimitado al servidor de la base de datos y a sus datos.

      En la mayoría de los casos, solo se debe acceder a MongoDB desde determinadas ubicaciones de confianza, como otro servidor que aloje una aplicación. Para permitir solo el acceso al puerto predeterminado de MongoDB mediante otro servidor de confianza, puede especificar la dirección IP del servidor remoto en el comando ufw. De esta manera, solo se permitirá que esa máquina se conecte de forma explícita:

      • sudo ufw allow from trusted_server_ip/32 to any port 27017

      Puede verificar el cambio en los ajustes del firewall con ufw:

      Debería ver la habilitación del tráfico hacia el puerto 27017 en el resultado. Tenga en cuenta que si decidió permitir que solo una dirección IP determinada se conecte con el servidor de MongoDB, en el resultado de este comando se enumerará la dirección IP de la ubicación autorizada en lugar de Anywhere.

      Output

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

      Puede encontrar ajustes de firewall más avanzados para restringir el acceso a servicios en Aspectos básicos de UFW: Reglas y comandos comunes de firewall.

      Aunque el puerto esté abierto, MongoDB seguirá escuchando solo en la dirección local 127.0.0.1. Para permitir conexiones remotas, agregue la dirección IP pública de su servidor al archivo mongodb.conf.

      Abra el archivo de configuración de MongoDB en su editor de texto preferido: Este comando de ejemplo utiliza nano:

      • sudo nano /etc/mongodb.conf

      Agregue la dirección IP de su servidor de MongoDB al valor bindIP: Asegúrese de colocar una coma entre la dirección IP existente y la que agregó.

      /etc/mongodb.conf

      ...
      logappend=true
      
      bind_ip = 127.0.0.1,your_server_ip
      #port = 27017
      
      ...
      

      Guarde el archivo y salga del editor. Si utilizó nano para editar el archivo, hágalo pulsando CTRL + X, Y y, luego, ENTER.

      Luego, reinicie el servicio de MongoDB:

      • sudo systemctl restart mongodb

      MongoDB ahora recibirá conexiones remotas, pero cualquiera podrá acceder a él. Siga el tutorial Cómo instalar y proteger MongoDB en Ubuntu 20.04 para agregar un usuario administrativo y ampliar el bloqueo.

      Conclusión

      Puede encontrar tutoriales más detallados sobre cómo configurar y utilizar MongoDB en estos artículos de la comunidad de DigitalOcean. La documentación oficial de MongoDB también es un gran recurso en el que se abordan las posibilidades que ofrece MongoDB.



      Source link

      Comment installer MongoDB à partir des référentiels APT par défaut sur Ubuntu 20.04


      Introduction

      MongoDB est une base de données de documents NoSQL gratuite et open source couramment utilisée dans les applications web modernes.

      Dans ce tutoriel, vous allez apprendre à installer MongoDB, gérer son service et activer l’option d’accès à distance.

      Remarque : au moment de sa rédaction, ce tutoriel installe la version 3.6 de MongoDB. Il s’agit de la version mise à disposition à partir des référentiels Ubuntu par défaut. Cependant, nous recommandons généralement d’installer plutôt la dernière version de MongoDB (la version 4.4 au moment de la rédaction). Si vous souhaitez installer la dernière version de MongoDB, nous vous encourageons à suivre le guide suivant sur Comment installer MongoDB sur Ubuntu 20.04 à partir de la source.

      Conditions préalables

      Pour suivre ce tutoriel, vous aurez besoin de :

      Étape 1 — Installation de MongoDB

      Les référentiels des paquets officiels d’Ubuntu incluent MongoDB. Nous pouvons donc installer les paquets nécessaires en utilisant apt. Comme nous l’avons mentionné dans l’introduction, la version disponible à partir des référentiels par défaut n’est pas la plus récente. Pour installer la dernière version de Mongo, veuillez plutôt suivre ce tutoriel.

      Tout d’abord, mettez à jour la liste des paquets pour obtenir la version la plus récente des listes du référentiel :

      Maintenant, installez le paquet MongoDB en lui-même :

      Cette commande vous invite à confirmer si vous souhaitez bien installer le paquet mongodb et ses dépendances. Pour ce faire, appuyez sur Y, puis sur ENTER.

      Cette commande installe plusieurs paquets qui contiennent une version stable de MongoDB, ainsi que des outils de gestion utiles pour le serveur MongoDB. Le serveur de la base de données démarre automatiquement après l'installation.

      Ensuite, vérifions si le serveur fonctionne correctement.

      Étape 2 — Vérification du service et de la base de données

      Le processus d'installation a démarré MongoDB automatiquement. Cependant, vérifions tout de même si le service a bien été lancé et si la base de données fonctionne.

      Tout d'abord, vérifiez l'état du service :

      • sudo systemctl status mongodb

      Vous verrez la sortie suivante :

      Output

      ● mongodb.service - An object/document-oriented database Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2020-10-08 14:23:22 UTC; 49s ago Docs: man:mongod(1) Main PID: 2790 (mongod) Tasks: 23 (limit: 2344) Memory: 42.2M CGroup: /system.slice/mongodb.service └─2790 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf

      Selon ce résultat, le serveur MongoDB est opérationnel.

      Pour vérifier cela de manière plus approfondie, en fait, nous allons nous connecter au serveur de base de données et exécuter la commande de diagnostic suivante. Cela générera la version actuelle de la base de données, l'adresse et le port du serveur et la sortie de la commande de l'état :

      • mongo --eval 'db.runCommand({ connectionStatus: 1 })'

      Output

      MongoDB shell version v3.6.8 connecting to: mongodb://127.0.0.1:27017 Implicit session: session { "id" : UUID("e3c1f2a1-a426-4366-b5f8-c8b8e7813135") } MongoDB server version: 3.6.8 { "authInfo" : { "authenticatedUsers" : [ ], "authenticatedUserRoles" : [ ] }, "ok" : 1 }

      Dans la réponse, une valeur de 1 dans le champ ok indique que le serveur fonctionne correctement.

      Ensuite, nous allons apprendre à gérer l'instance du serveur.

      Étape 3 — Gestion du service MongoDB

      Le processus d'installation décrit à l'étape 1 configure MongoDB en tant que service systemd. Cela signifie que vous pouvez le gérer en utilisant des commandes systemctl standard avec tous les autres services du système dans Ubuntu.

      Pour vérifier l'état du service, tapez :

      • sudo systemctl status mongodb

      Vous pouvez arrêter le serveur à tout moment en saisissant ce qui suit :

      • sudo systemctl stop mongodb

      Pour démarrer le serveur lorsqu'il est arrêté, tapez :

      • sudo systemctl start mongodb

      Vous pouvez également redémarrer le serveur en utilisant la commande suivante :

      • sudo systemctl restart mongodb

      Par défaut, MongoDB est configuré pour démarrer automatiquement avec le serveur. Si jamais vous souhaitez désactiver ce démarrage automatique, saisissez ce qui suit :

      • sudo systemctl disable mongodb

      Vous pouvez réactiver le démarrage automatique à tout moment en utilisant la commande suivante :

      • sudo systemctl enable mongodb

      Maintenant, réglons les paramètres du pare-feu de notre installation MongoDB.

      Étape 4 — Réglage du pare-feu (facultatif)

      En supposant que vous ayez suivi les instructions du tutoriel de configuration initiale de serveur pour activer le pare-feu sur votre serveur, le serveur MongoDB sera inaccessible à partir d'Internet.

      Si vous prévoyez d'utiliser MongoDB uniquement en local, avec des applications exécutées sur le même serveur, il s'agit de la configuration recommandée et sécurisée à utiliser. Cependant, si vous souhaitez vous connecter à votre serveur MongoDB à partir d'Internet, vous devez autoriser les connexions entrantes en ajoutant une règle UFW.

      Pour autoriser l'accès à MongoDB sur son port par défaut 27017 à partir de tout endroit, vous pouvez exécuter sudo ufw allow 27017. Cependant, en activant l'accès Internet au serveur MongoDB sur une installation par défaut, toute personne aura un accès sans restriction au serveur de la base de données et à ses données.

      Dans la plupart des cas, MongoDB ne doit être accessible qu'à partir de certains lieux de confiance (un autre serveur hébergeant une application, par exemple). Pour autoriser un autre serveur de confiance à accéder uniquement au port par défaut de MongoDB, vous pouvez spécifier l'adresse IP du serveur distant dans la commande ufw. Ainsi, seule la machine sera explicitement autorisée à se connecter :

      • sudo ufw allow from trusted_server_ip/32 to any port 27017

      Vous pouvez vérifier le changement dans les paramètres de pare-feu avec ufw :

      Vous devriez voir le trafic vers le port 27017 autorisé dans la sortie. Notez que si vous avez décidé d'autoriser une certaine adresse IP à se connecter au serveur MongoDB, l'adresse IP de l'emplacement autorisé sera référencée à la place de Anywhere dans la sortie de cette commande :

      Output

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

      Vous pouvez trouver des paramètres de pare-feu plus avancés pour restreindre l'accès aux services dans les Essentiels d'UFW : Règles et commandes communes du pare-feu.

      Même si le port est ouvert, MongoDB continuera toujours d'écouter uniquement l'adresse locale 127.0.0.1. Pour autoriser des connexions à distance, ajoutez l'adresse IP publique de votre serveur au fichier mongodb.conf.

      Ouvrez le fichier de configuration de MongoDB dans votre éditeur de texte préféré. Cet exemple de commande utilise nano :

      • sudo nano /etc/mongodb.conf

      Ajoutez l'adresse IP de votre serveur MongoDB à la valeur bindIP. Veillez à placer une virgule entre l'adresse IP existante et celle que vous avez ajoutée :

      /etc/mongodb.conf

      ...
      logappend=true
      
      bind_ip = 127.0.0.1,your_server_ip
      #port = 27017
      
      ...
      

      Enregistrez le fichier et quittez l'éditeur. Si vous avez modifié le fichier avec nano, faites-le en appuyant sur CTRL + X, Y, puis sur ENTER.

      Ensuite, redémarrez le service MongoDB :

      • sudo systemctl restart mongodb

      MongoDB écoute maintenant les connexions à distance, mais toute personne peut y accéder. Suivez le tutoriel Comment sécuriser MongoDB sur Ubuntu 20.04 pour ajouter un utilisateur administratif et verrouiller un peu plus l'accès.

      Conclusion

      Vous pouvez trouver d'autres tutoriels plus approfondis sur la façon de configurer et d'utiliser MongoDB dans ces articles publiés par la communauté DigitalOcean. La documentation officielle de MongoDB est également une excellente ressource pour découvrir les possibilités que MongoDB a à offrir.



      Source link