受欢迎的博客标签

How to Install MongoDB on on Ubuntu 18.04

一、准备工作

使用winscp工具,将project.json所在的文件夹,上传到Linux服务器。

https://winscp.net/download/WinSCP-5.15.3-Setup.exe

2.打开aliyun web控制台,选远程连接,输入远程连接密码。

3.用root 用户登录

 

4.Ubuntu修改密码

Ubuntu更改密码步骤:
1、进入Ubuntu,打开一个终端,输入 sudo su转为root用户。 注意,必须先转为root用户!!!
2、sudo passwd user(user 是对应的用户名)
3、输入新密码,确认密码。
4、修改密码成功,重启,输入新密码进入Ubuntu。

3. 连接主机

 

The author selected the Creative Commons Corporation to receive a $100 donation as part of the Write for DOnations program.

Introduction

MongoDB is a free and open-source NoSQL document database used commonly in modern web applications.

In this tutorial you’ll

Install MongoDB on Ubuntu 18.04 LTS

Configure MongoDB

manage its service, and optionally enable remote access.

 

Prerequisites

Ubuntu Server 18.04 - 64 bit:Buying a from a company (yourwebsite.com) to host that website This often involves picking a hosting provider.
Root privileges:One Ubuntu 18.04 server set up by following this initial server setup tutorial, including a sudo non-root user and a firewall.

 

Step 1 — Installing MongoDB

Mongodb Office  Install Document:

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

 

Ubuntu’s official package repositories include an up-to-date version of MongoDB, which means we can install the necessary packages using apt.

First, update the packages list to have the most recent version of the repository listings:

sudo apt update

Now install the MongoDB package itself:

sudo apt install -y mongodb

This command installs several packages containing the latest stable version of MongoDB, along with helpful management tools for the MongoDB server. The database server is automatically started after installation.

Next, let’s verify that the server is running and works correctly.

 

Step 2 — Checking the Service and Database

The installation process started MongoDB automatically, but let’s verify that the service is started and that the database is working.

2.1 check the service’s status:

sudo systemctl status mongod

You’ll see this output:

Output
● mongodb.service - An object/document-oriented database
   Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2018-05-26 07:48:04 UTC; 2min 17s ago
     Docs: man:mongod(1)
 Main PID: 2312 (mongod)
    Tasks: 23 (limit: 1153)
   CGroup: /system.slice/mongodb.service
           └─2312 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf

2.2 check that MongoDB has been started on port 27017 with the netstat command.

sudo netstat -plntu

output:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      9473/nginx: master  
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      8645/systemd-resolv 
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      695/sshd            
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      9473/nginx: master  
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      6441/mongod   

2.3 We can verify this further by actually connecting to the database server and executing a diagnostic command

Execute this command:

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

This will output the current database version, the server address and port, and the output of the status command:

Output
MongoDB shell version v3.6.3 
connecting to: mongodb://127.0.0.1:27017 
MongoDB server version: 3.6.3 {
 "authInfo" : 
{ 
"authenticatedUsers" : [ ],
"authenticatedUserRoles" : [ ]
},
 "ok" : 1
}

A value of 1 for the ok field in the response indicates that the server is working properly.

Next, we’ll look at how to manage the server instance.

 

Step 3 — Managing the MongoDB Service

MongoDB installs as a systemd service, which means that you can manage it using standard systemd commands alongside all other sytem services in Ubuntu.

sudo vi /lib/systemd/system/mongod.service

https://github.com/droppanel/examples/blob/207315f9afc66237f58a8ac559a4462f17b4e44f/mongodb/ubuntu/install.default.sh

To verify the status of the service, type:

sudo systemctl status mongod

You can stop the server anytime by typing:

sudo systemctl stop mongod

To start the server when it is stopped, type:

sudo systemctl start mongodb

You can also restart the server with a single command:

sudo systemctl restart mongodb

By default, MongoDB is configured to start automatically with the server. If you wish to disable the automatic startup, type:

sudo systemctl disable mongodb

It’s just as easy to enable it again. To do this, use:

sudo systemctl enable mongodb

Next, let’s adjust the firewall settings for our MongoDB installation.

step 4:Create MongoDB Database Root User and Password

4.1.1 Mongo shell

To add our user, we’ll connect to the Mongo shell:

mongo
mongo --port 27017 -u "lyl" -p "123456" --authenticationDatabase "admin"
mongo --host 106.15.393.334 -u admin -p adminadmi: --authenticationDatabase admin

Output

MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
Server has startup warnings:
2017-02-21T19:10:42.446+0000 I STORAGE  [initandlisten]
2017-02-21T19:10:42.446+0000 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-02-21T19:10:42.446+0000 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten]
2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten]
>
4.1.2 create  root user
First switch to the admin database, then create the root user using following commands.
> use admin
  > db.createUser({user:"root", pwd:"pass123", roles:[{role:"root", db:"admin"}]})
output
Successfully added user: {
          "user" : "root",
          "roles" : [
                  {
                          "role" : "root",
                          "db" : "admin"
                  }
          ]
  }

change User Password

use admin
db.changeUserPassword("admin", "Waddews")
 
Type ‘exit’ and press ENTER or use CTRL+C to leave the client.
 
other:
use stock
db.createUser({user:"stock", pwd:"pass5", roles:[{role:"dbOwner", db:"stock"}]})
 
Step 5:Enable MongoDB authentication
5.1.1 Open the mongod.conf file in vi editor:
Edit the mongodb service file '/ect/mongodb.conf' with your editor.
 
# Turn on/off security.  Off is currently the default
#noauth = true
auth = true
 
5.1.2 restart the MongoDB daemon
sudo systemctl restart mongodb

or

/usr/bin/mongod --config /etc/mongod.conf

5.1.3 check  the MongoDB has been started.

systemctl doesn’t provide output, we’ll use its status option to be sure that it did:

sudo systemctl status mongodb

If we see Active: active (running) in the output and it ends with something like the text below, we can be sure the restart command was successful.

before:

MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
Server has startup warnings:
2017-02-21T19:10:42.446+0000 I STORAGE  [initandlisten]
2017-02-21T19:10:42.446+0000 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-02-21T19:10:42.446+0000 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten]
2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten]
>

now:

MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
> 

5.1.4 Verifying the Administrative User’s Access

mongo -u admin -p adminadmin: --authenticationDatabase admin

 

Step6:Configuring Remote Access for client

Configuring a Public bindIP

To allow remote connections, we will add our host’s publically-routable IP address to the mongod.conf file.

To bind to all IPv4 addresses, you can specify the bind ip address of 0.0.0.0. To bind to all IPv4 and IPv6 addresses, you can specify the bind ip address of ::,0.0.0.0 or alternatively.

IP Binding — MongoDB Manual.https://docs.mongodb.com/manual/core/security-mongodb-configuration/

vi /etc/mongodb.conf

change 

bind_ip = 127.0.0.1

to

bind_ip = 0.0.0.0

Testing the Remote Connection

mongo --host 106.15.393.334 -u admin -p adminadmi: --authenticationDatabase admin

output

MongoDB shell version v4.0.9
connecting to: mongodb://116.15.393.134:27017/?authSource=admin&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("a1fd541b-357a-46bb-87a1-2e3f9ddca5af") }
MongoDB server version: 3.6.3
WARNING: shell and server versions do not match
Server has startup warnings: 
2019-10-07T21:23:54.150+0800 I STORAGE  [initandlisten] 
2019-10-07T21:23:54.150+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2019-10-07T21:23:54.150+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem

 

Uninstall MongoDB

sudo service mongod stop #Stop the mongod process
sudo apt-get purge mongodb* #Remove any MongoDB packages that you had previously installed.
sudo rm -r /var/log/mongodb #Remove MongoDB databases and log files.
sudo rm -r /var/lib/mongodb

Step 7 — Adjusting the Firewall (Optional)

Assuming you have followed the initial server setup tutorial instructions to enable the firewall on your server, the MongoDB server will be inaccessible from the internet.

If you intend to use the MongoDB server only locally with applications running on the same server, this is the recommended and secure setting. However, if you would like to be able to connect to your MongoDB server from the internet, you have to allow the incoming connections in ufw.

To allow access to MongoDB on its default port 27017 from everywhere, you could use sudo ufw allow 27017. However, enabling internet access to MongoDB server on a default installation gives anyone unrestricted access to the database server and its data.

In most cases, MongoDB should be accessed only from certain trusted locations, such as another server hosting an application. To accomplish this task, you can allow access on MongoDB’s default port while specifying the IP address of another server that will be explicitly allowed to connect:

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

You can verify the change in firewall settings with ufw:

  • sudo ufw status

You should see traffic to port 27017 allowed in the output:

Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
27017                      ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
27017 (v6)                 ALLOW       Anywhere (v6)

If you have decided to allow only a certain IP address to connect to MongoDB server, the IP address of the allowed location will be listed instead of Anywhere in the output.

You can find more advanced firewall settings for restricting access to services in UFW Essentials: Common Firewall Rules and Commands.

Even though the port is open, MongoDB is currently only listening on the local address 127.0.0.1. To allow remote connections, add your server’s publicly-routable IP address to the mongod.conf file.

Open the MongoDB configuration file in your editor:

  • sudo nano /etc/mongodb.conf

Add your server’s IP address to the bindIP value:

 
...
logappend=true

bind_ip = 127.0.0.1,your_server_ip
#port = 27017

...

Be sure to place a comma between the existing IP address and the one you added.

Save the file, exit the editor, and restart MongoDB:

  • sudo systemctl restart mongodb

MongoDB is now listening for remote connections, but anyone can access it. Follow Part 2 of How to Install and Secure MongoDB on Ubuntu 16.04 to add an administrative user and lock things down further.

 
 
error:
wiredtiger_open: /var/lib/mongodb/WiredTiger.turtle: handle-open: open: Permission denied Raw: [1530772324:204155][15656:0x7fb5cb734a00], wiredtiger_open: /var/lib/mongodb/WiredTiger.turtle: handle-open: open: Permission denied
2018-07-05T14:32:04.204+0800 E STORAGE [initandlisten] WiredTiger
 
run these command, the problem has been solved.
 [sudo] chown mongodb.mongodb -R /var/lib/mongodb
 

Conclusion

You can find more in-depth tutorials on how to configure and use MongoDB in these DigitalOcean community articles. The official MongoDB documentation is also a great resource on the possibilities that MongoDB provides.