How to start mongodb linux

Install MongoDB¶

Author: MongoDB Documentation Team

This guide describes how to install MongoDB locally. If you would like to use MongoDB in the Cloud using Atlas , our managed database product, see Get Started with Atlas.

Time required: 10 minutes

What You’ll Need¶

MongoDB supports a variety of 64-bit platforms. Refer to the Supported Platforms table to verify that MongoDB is supported on the platform to which you wish to install it.

Procedure¶

Install MongoDB¶

Download the binaries from the MongoDB Download Center.

Open Windows Explorer/File Explorer.

Change the directory path to where you downloaded the MongoDB .msi file. By default, this is %HOMEPATH%\Downloads .

Double-click the .msi file.

The Windows Installer guides you through the installation process.

If you choose the Custom installation option, you may specify an installation directory.

MongoDB does not have any other system dependencies. You can install and run MongoDB from any folder you choose.

This tutorial assumes that you installed MongoDB in C:\Program Files\MongoDB\Server\4.2\ .

MongoDB only supports macOS versions 10.11 and later on Intel x86-64.

Download the binary files for the desired release of MongoDB.В¶

Download the binaries from the MongoDB Download Center.

Extract the files from the downloaded archive.В¶

For example, from a system shell, you can extract through the tar command:

Copy the extracted archive to the target directory.В¶

Copy the extracted folder to the location from which MongoDB will run.

Ensure the location of the binaries is in the PATH variable.В¶

The MongoDB binaries are in the bin/ directory of the archive. To ensure that the binaries are in your PATH , you can modify your PATH .

For example, you can add the following line to your shell’s rc file (e.g.

Replace with the path to the extracted MongoDB archive.

These instructions are for installing MongoDB directly from an archive file. If you would rather use your linux distribution’s package manager, refer to the installation instructions for your distribution in the MongoDB Manual.

Download the binary files for the desired release of MongoDB.В¶

Download the binaries from the MongoDB Download Center.

Extract the files from the downloaded archive.В¶

Extract the archive by double-clicking on the tar file or using the tar command from the command line, as in the following:

Copy the extracted archive to the target directory.В¶

Copy the extracted folder to the location from which MongoDB will run.

Ensure the location of the binaries is in the PATH variable.В¶

The MongoDB binaries are in the bin/ directory of the archive. To ensure that the binaries are in your PATH , you can modify your PATH .

For example, you can add the following line to your shell’s rc file (e.g.

Replace with the path to the extracted MongoDB archive.

Run MongoDB¶

Do not make mongod.exe visible on public networks without running in “Secure Mode” with the auth setting. MongoDB is designed to be run in trusted environments, and the database does not enable “Secure Mode” by default.

Set up the MongoDB environment.В¶

MongoDB requires a data directory to store all data. MongoDB’s default data directory path is the absolute path \data\db on the drive from which you start MongoDB. Create this folder by running the following command in a Command Prompt :

You can specify an alternate path for data files using the —dbpath option to mongod.exe , for example:

Читайте также:  Face distortion pack для windows

If your path includes spaces, enclose the entire path in double quotes, for example:

You may also specify the dbpath in a configuration file.

Start MongoDB.В¶

To start MongoDB, run mongod.exe . For example, from the Command Prompt :

This starts the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.

Depending on the security level of your system, Windows may pop up a Security Alert dialog box about blocking “some features” of C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe from communicating on networks. All users should select Private Networks, such as my home or work network and click Allow access . For additional information on security and MongoDB, please see the Security Documentation.

Verify that MongoDB has started successfully¶

Verify that MongoDB has started successfully by checking the process output for the following line:

The output should be visible in the terminal or shell window.

You may see non-critical warnings in the process output. As long as you see the log line shown above, you can safely ignore these warnings during your initial evaluation of MongoDB.

Connect to MongoDB.В¶

To connect to MongoDB through the

bin.mongo.exe shell, open another Command Prompt .

Create the data directory¶

Before you start MongoDB for the first time, create the directory to which the mongod process will write data. By default, the mongod process uses the /data/db directory. If you create a directory other than this one, you must specify that directory in the dbpath option when starting the mongod process later in this procedure.

The following example command creates the default /data/db directory:

Set permissions for the data directory¶

Before running mongod for the first time, ensure that the user account running mongod has read and write permissions for the directory.

Run MongoDB¶

To run MongoDB, run the mongod process at the system prompt. If necessary, specify the path of the mongod or the data directory. See the following examples.

Run without specifying paths¶

If your system PATH variable includes the location of the mongod binary and if you use the default data directory (i.e., /data/db ), simply enter mongod at the system prompt:

Specify the path of the mongod В¶

If your PATH does not include the location of the mongod binary, enter the full path to the mongod binary at the system prompt:

Источник

Установка и подключение к MongoDB

В данной инструкции мы рассмотрим процесс установки MongoDB на Linux Ubuntu (Debian). Также будут приведены примеры настройки подключения по сети, защита соединения с помощью шифрования и аутентификации.

Установка

На странице MongoDB Community Downloads смотрим стабильные версии программного продукта. На момент обновления инструкции это была 4.4.

Обратите внимание, установка MongoDB возможна на большое число популярных операционных систем — Amazon, Debian, Ubuntu, macOS, CentOS, Red Hat, Windows и другие.

Переходим на страницу загрузки ключей для проверки подлинности репозитория. Копируем ссылку для версии MongoDB, которую мы планируем установить:

* в данном примере мы скопировали ссылку на ключ для версии 4.4. Обратите внимание, что также есть возможность загрузки ключей для более свежих и менее стабильных версий.

С помощью скопированной ссылки скачиваем и устанавливаем ключ:

wget -qO — https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add —

Создаем файл для настройки репозитория Ubuntu:

deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse

* focal — название релиза Ubuntu. В данном примере, версия 20.04. На данный момент возможны варианты:

  • focal: 20.04.
  • bionic: 18.04.
  • xenial: 16.04.

Обновляем список пакетов:

apt-get install mongodb-org

Стартуем сервис и разрешаем его автозапуск:

systemctl start mongod

systemctl enable mongod

Для подключения к СУБД вводим команду:

Можно для проверки ввести команду, которая покажет созданные базы данных:

После первой установки мы должны увидеть следующее:

admin 0.000GB
config 0.000GB
local 0.000GB

В качестве примера работы мы можем попробовать создать новую базу данных и коллекцию. Объекты в MongoDB создаются автоматически при первом к ним обращении.

Для создания базы просто обращается к ней:

* в данном примере будут создана база newDB.

Для создания коллекции, выполняем команду на вставку данных:

Выходим из оболочки SQL:

Доступ по сети

По умолчанию к установленной базе можно подключиться только с локального компьютера. Рассмотрим процесс настройки сетевого доступа.

Для начала, откроем порт в брандмауэре:

iptables -I INPUT -p tcp —dport 27017 -j ACCEPT

* по умолчанию, MongoDB работает на TCP-порту 27017.

В системах на базе Ubuntu и Debian брандмауэр работает по принципу разрешения. Если мы не меняли данной настройки, то нам не обязательно создавать разрешающее правило для Mongo.

Читайте также:  Linux mount virtualbox disk

Открываем конфигурационный файл СУБД:

Находим директиву net и в ней опцию bindIp — добавляем IP-адрес, на котором наш сервер должен принимать запросы для MongoDB:

net:
port: 27017
bindIp: 127.0.0.1, 192.168.1.15

* в нашем примере мы добавили к 127.0.0.1 адрес 192.168.1.15 — это сетевой адрес нашего сервера, на котором он должен принимать запросы.

Перезапускаем сервис mongod:

systemctl restart mongod

Чтобы проверить подключение, на другом компьютере должен быть установлен клиент для подключения к Mongo. Процесс его установки схож с установкой сервера. Рассмотрим пример для Ubuntu.

Устанавливаем ключ для репозитория:

wget -qO — https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add —

deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse

* как в случае с сервером, focal — название релиза Ubuntu. В данном примере, версия 20.04. Другие варианты: bionic: 18.04, xenial: 16.04.

Обновляем список пакетов:

Устанавливаем клиентскую часть:

apt-get install mongodb-org-shell

Теперь можно подключиться к нашему серверу:

* в данном примере мы подключаемся к серверу MongoDB 192.168.1.15.

Также мы можем использовать MongoDB Compass — это приложение под Windows, Linux и macOS для работы с базой Mongo в графическом интерфейсе. Скачать его можно на странице официального сайта.

Аутентификация

По умолчанию, мы можем подключиться к СУБД без авторизации. Если нам необходимо повысить безопасность работы с базой, можно требовать ввода логина и пароля.

Заходим в командную оболочку Mongo:

Подключаемся к базе admin:

Создаем пользователя, под которым будем авторизовываться:

* в данном примере мы создадим пользователя с правами доступа на все базы. Логин root, пароль будет запрошен после ввода.

Придумываем и вводим пароль

После создания пользователя мы должны увидеть, примерно, следующую картину:

Successfully added user: <
«user» : «root»,
«roles» : [
<
«role» : «userAdminAnyDatabase»,
«db» : «admin»
>,
«readWriteAnyDatabase»
]
>

Выходим из командной оболочки:

Открываем конфигурационный файл:

Находим директиву security и задаем параметр authorization:

security:
authorization: enabled

Перезапускаем сервис mongod:

systemctl restart mongod

Теперь пробуем подключиться к mongo. Мы можем авторизоваться несколькими способами.

а) Авторизация при подключении:

mongo —authenticationDatabase «admin» -u «root» -p

* в данном примере мы подключимся к базе под пользователем root. Пароль будет запрошен системой после ввода команды.

б) Авторизация после подключения:

Теперь усилим безопасность, зашифровав передачу данных. Для этого нам понадобиться сертификат. В нашем примере, мы будем использовать самоподписанный сертификат, но в продуктивной среде, лучше его купить или запросить у Let’s Encrypt.

Создаем каталог, в котором разместим наши сертификаты:

mkdir -p /etc/ssl/mongodb

Сгенерируем самоподписанный сертификат:

openssl req -new -x509 -days 1461 -nodes -out /etc/ssl/mongodb/cert.pem -keyout /etc/ssl/mongodb/cert.pem -subj «/C=RU/ST=SPb/L=SPb/O=Global Security/OU=IT Department/CN=mongo.dmosk.local/CN=mongo»

Выставим в качестве владельца на файлы сертификата пользователя mongodb:

chown mongodb:mongodb /etc/ssl/mongodb/cert.pem

Открываем конфигурационный файл СУБД:

В директиву net дописываем опции TLS:

net:
.
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/mongodb/cert.pem

* в данном примере мы указали необходимость шифрования данных при передаче, а также путь до сгенерированного нами сертификата.

Перезапускаем сервис mongod:

systemctl restart mongod

Для подключения к базе с использованием шифрования используем команду:

mongo —tls —tlsAllowInvalidCertificates

* в данном примере мы указываем при подключении использовать шифрование с использованием TLS. Опция tlsAllowInvalidCertificates говорит, что клиент должен принять неправильный сертификат (так как у нас он самоподписанный).

Так как у нас еще настроена аутентификация, для подключения введем такую команду:

mongo —tls —tlsAllowInvalidCertificates —authenticationDatabase «admin» -u «root» -p

Для подключения к нашему серверу по сети, полная команда будет такой:

mongo «mongodb://192.168.1.15:27017» —tls —tlsAllowInvalidCertificates —authenticationDatabase «admin» -u «root» -p

Примеры подключения из языков программирования

Рассмотрим небольшие примеры для подключения к MongoDB из языков программирования PHP и Python.

Для возможности работы PHP с Mongo необходимо установить соответствующее расширение. Выполняем пошагово следующие действия:

apt-get install php-pear php-dev

pecl channel-update pecl.php.net

pecl install mongodb

Для каждого возможного варианта использования PHP необходимо создать отдельный конфигурационной файл. В данном примере, под php 7.4 для cli, php-fpm, apache.

Источник

Install MongoDB Community Edition on Ubuntu¶

MongoDB Atlas is a hosted MongoDB service option in the cloud which requires no installation overhead and offers a free tier to get started.

Overview¶

Use this tutorial to install MongoDB 5.0 Community Edition on LTS (long-term support) releases of Ubuntu Linux using the apt package manager.

MongoDB Version¶

This tutorial installs MongoDB 5.0 Community Edition. To install a different version of MongoDB Community , use the version drop-down menu in the upper-left corner of this page to select the documentation for that version.

Considerations¶

Platform Support¶

  • MongoDB 5.0 Community Edition removes support for Ubuntu 16.04 on x86_64
  • MongoDB 5.0 Community Edition removes support for Ubuntu 18.04 on s390x

MongoDB 5.0 Community Edition supports the following 64-bit Ubuntu LTS (long-term support) releases on x86_64 architecture:

  • 20.04 LTS («Focal»)
  • 18.04 LTS («Bionic»)
  • 16.04 LTS («Xenial»)
Читайте также:  Wpcap dll для windows

MongoDB only supports the 64-bit versions of these platforms.

MongoDB 5.0 Community Edition on Ubuntu also supports the ARM64 architecture on select platforms.

See Supported Platforms for more information.

To run MongoDB in Windows Subsystem for Linux (WSL), refer to the WSL documentation.

Production Notes¶

Before deploying MongoDB in a production environment, consider the Production Notes document which offers performance considerations and configuration recommendations for production MongoDB deployments.

Official MongoDB Packages¶

To install MongoDB Community on your Ubuntu system, these instructions will use the official mongodb-org package, which is maintained and supported by MongoDB Inc. The official mongodb-org package always contains the latest version of MongoDB, and is available from its own dedicated repo.

The mongodb package provided by Ubuntu is not maintained by MongoDB Inc. and conflicts with the official mongodb-org package. If you have already installed the mongodb package on your Ubuntu system, you must first uninstall the mongodb package before proceeding with these instructions.

See MongoDB Community Edition Packages for the complete list of official packages.

Install MongoDB Community Edition¶

Follow these steps to install MongoDB Community Edition using the apt package manager.

Import the public key used by the package management system.В¶

From a terminal, issue the following command to import the MongoDB public GPG Key from https://www.mongodb.org/static/pgp/server-5.0.asc:

The operation should respond with an OK .

However, if you receive an error indicating that gnupg is not installed, you can:

Install gnupg and its required libraries using the following command:

Once installed, retry importing the key:

Create a list file for MongoDB.В¶

Create the list file /etc/apt/sources.list.d/mongodb-org-5.0.list for your version of Ubuntu.

Click on the appropriate tab for your version of Ubuntu. If you are unsure of what Ubuntu version the host is running, open a terminal or shell on the host and execute lsb_release -dc .

Reload local package database.В¶

Issue the following command to reload the local package database:

Install the MongoDB packages.В¶

You can install either the latest stable version of MongoDB or a specific version of MongoDB.

Optional. Although you can specify any available version of MongoDB, apt-get will upgrade the packages when a newer version becomes available. To prevent unintended upgrades, you can pin the package at the currently installed version:

For help with troubleshooting errors encountered while installing MongoDB on Ubuntu, see our troubleshooting guide.

Run MongoDB Community Edition¶

If you installed via the package manager, the data directory /var/lib/mongodb and the log directory /var/log/mongodb are created during the installation.

By default, MongoDB runs using the mongodb user account. If you change the user that runs the MongoDB process, you must also modify the permission to the data and log directories to give this user access to these directories.

Configuration File The official MongoDB package includes a configuration file ( /etc/mongod.conf ). These settings (such as the data directory and log directory specifications) take effect upon startup. That is, if you change the configuration file while the MongoDB instance is running, you must restart the instance for the changes to take effect.

Procedure¶

Follow these steps to run MongoDB Community Edition on your system. These instructions assume that you are using the official mongodb-org package — not the unofficial mongodb package provided by Ubuntu — and are using the default settings.

Init System

To run and manage your mongod process, you will be using your operating system’s built-in init system. Recent versions of Linux tend to use systemd (which uses the systemctl command), while older versions of Linux tend to use System V init (which uses the service command).

If you are unsure which init system your platform uses, run the following command:

Then select the appropriate tab below based on the result:

  • systemd — select the systemd (systemctl) tab below.
  • init — select the System V Init (service) tab below.

Uninstall MongoDB Community Edition¶

To completely remove MongoDB from a system, you must remove the MongoDB applications themselves, the configuration files, and any directories containing data and logs. The following section guides you through the necessary steps.

This process will completely remove MongoDB, its configuration, and all databases. This process is not reversible, so ensure that all of your configuration and data is backed up before proceeding.

Stop MongoDB.В¶

Stop the mongod process by issuing the following command:

Источник

Оцените статью