Hướng dẫn mongodb localhost:27017

Nội dung bài viết

Video học lập trình mỗi ngày

Connect server MongoDB từ xa hay từ một server khác đó là một mô hình bình thường hiện nay. Bài viết này sẽ hướng dẫn cho người mới làm quen với mongodb có thể làm được điều mà chỉ có những chuyên về admin mới làm được.

Bài viết này có trong Series - Mongodb.

Để hiểu được và có thể thao tác được, trước tiên tôi mong muốn về cơ bản, bạn phải hiểu MongoDB là gì? Và đương nhiên là phải có những thao tác trên LINUX.

Bài học này bạn được những gì?

  • Cách tạo một database và tạo quyền truy cập vào db trên Mongoodb.
  • Cách cho phép mọi ip address connect từ xa tới MongoDB
  • Chỉ cho phép một số ip address truy cập từ xa tới MongoDB

MongoDB create user

Đầu tiên chính xác là bạn truy cập và ssh, và tạo một user trên mongodb mà chúng ta đã nói đến ở Mongodb create database and user terminal:

> db.createUser( 
  {
    user: "new_user",
    pwd: "some_password",
    roles: [ { role: "readWrite", db: "anonystick" } ]
  }
)

Enable MongoDB Auth

Đến bước này thì việc duy nhất là bạn tìm tới file config mongodb /etc/mongod.conf. Sau đó sửa file này như sau:

sudo vim /etc/mongod.conf

Sau khi mở ra thì tìm đến line này:

# network interfaces
net:
    port: 27017
    bindIp: 127.0.0.1

bindIp: chính là nơi chứa những ip address được cho phép truy cập. Mặc định là chỉ có connect bằng localhost.Đến đây không thể không nhắc đến vấn đề bảo mật trong mongodb, đó là mỗi lần config vui lòng backup mongodb sử dụng mongodump. Cẩn thận trên hết nhé các đồng chí.

Warning: Đừng có comment lại #bindIp. Nếu bạn làm như vậy đồng nghĩa với việc bạn sẽ cho phép tất cả các nơi truy cập vào admin MongoDB của bạn.

Giờ bạn muốn thêm một Server A truy cập đến Server chứa MongoDB thì hãy làm như sau: Đầu tiên bạn phải làm là sử dụng lệnh:

anonystick:~# ip a |grep net
    inet 127.0.0.1/3 scope host lo
    inet6 xxxx scope host 
    inet 12.13.14.15/23 brd xxxxx scope global dynamic ens3
    inet6 xxxxx/64 scope link

Để làm gì? Để bạn có thể thấy được ip address đang xài là gì? Ở đây chính là dòng thứ 3 12.13.14.15. Khi lấy được rồi bạn sửa lại file config trên như tôi đã nói :

# network interfaces
net:
    port: 27017
    bindIp: 127.0.0.1,12.13.14.15

Nghĩa là server khác sẽ truy cập và connect mongodb qua 12.13.14.15 này.

Restart mongo daemon (mongod)

Sau khi edit thành công thì đương nhiên phải reload lại mongo.

sudo service mongod restart

Sau đó check lệnh mongo lên xem. Hoặc bạn có thể sử dụng

tail -f /var/log/mongodb/mongod.log

Để theo dõi log...

Kết nối mongodb từ xa Và sau cùng là ta lấy server A connect tới bằng nhiều cách như Connect mongodb Nodejs, nhưng ở đâu tôi dùng Sell cho nhanh:

mongo -u ian -p secretPassword 12.13.14.15/abc

MongoDB security

Ở đây 12.13.14.15 chính là ip mình đã config ở trên kia. Tới bước này rồi, có thể là tạm thời nói rằng bạn đã thành công. Nhưng còn một chuyện đó là vấn đề bảo mật. Có ai đặt câu hỏi rằng, nếu như vậy thì tất cả có thể truy cập vào database từ xa, cho dù là ai? Đúng là như vậy, chính vì vậy một bước cuối cùng để MongoDB security chính là phải cấu hình lại, ip address nào được phép truy cập. Đó là việc điều chỉnh lại Firewall trong hệ thống. Bài viết này đã dài, cho nên tôi nghĩ sẽ để vấn đề này cho một bài viết khác có tên là "Adjusting the Firewall'.

Và đó là tất cả bài hướng dẫn của chủ đề ngày hôm nay. Xin chào!

Docs HomeMongoDB Manual

This document describes the URI formats for defining connections between applications and MongoDB instances in the official MongoDB Drivers. For a list of drivers and links to driver documentation, see Drivers.

You can specify the MongoDB connection string using either:

  • the Standard Connection String Format or

  • the DNS Seed List Connection Format.

This section describes the standard format of the MongoDB connection URI used to connect to a MongoDB deployment: standalone, replica set, or a sharded cluster.

The standard URI connection scheme has the form:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

For more examples, see Examples.

The standard URI connection string includes the following components:

Component

Description

mongodb://

A required prefix to identify that this is a string in the standard connection format.

username:password@

Optional. Authentication credentials.

If specified, the client will attempt to authenticate the user to the authSource. If authSource is unspecified, the client will attempt to authenticate the user to the defaultauthdb. And if the defaultauthdb is unspecified, to the admin database.

Note

If the username or password includes the following characters:

: / ? # [ ] @

those characters must be converted using percent encoding.

See also authSource.

host[:port]

The host (and optional port number) where the mongod instance (or mongos instance for a sharded cluster) is running. You can specify a hostname, IP address, or UNIX domain socket. Specify as many hosts as appropriate for your deployment topology:

  • For a standalone, specify the hostname of the standalone mongod instance.

  • For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.

  • For a sharded cluster, specify the hostname(s) of the mongos instance(s).

If the port number is not specified, the default port 27017 is used.

/defaultauthdb

Optional. The authentication database to use if the connection string includes username:password@ authentication credentials but the authSource option is unspecified.

If both authSource and defaultauthdb are unspecified, the client will attempt to authenticate the specified user to the admin database.

?

Optional. A query string that specifies connection specific options as = pairs. See Connection String Options for a full description of these options.

If the connection string does not specify a database/ you must specify a slash (/) between the last host and the question mark (?) that begins the string of options.

In addition to the standard connection format, MongoDB supports a DNS-constructed seed list. Using DNS to construct the available servers list allows more flexibility of deployment and the ability to change the servers in rotation without reconfiguring clients.

In order to leverage the DNS seed list, use a connection string prefix of mongodb+srv rather than the standard mongodb. The +srv indicates to the client that the hostname that follows corresponds to a DNS SRV record. The driver or mongosh will then query the DNS for the record to determine which hosts are running the mongod instances.

Note

Use of the +srv connection string modifier automatically sets the tls (or the equivalent ssl) option to true for the connection. You can override this behavior by explicitly setting the tls (or the equivalent ssl) option to false with tls=false (or ssl=false) in the query string.

The following example shows a typical connection string for a DNS seed list connection string:

mongodb+srv://server.example.com/

The corresponding DNS configuration might resemble:

Record TTL Class Priority Weight Port Target
_mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27317 mongodb1.example.com.
_mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27017 mongodb2.example.com.

When a client connects to a member of the seed list, the client retrieves a list of replica set members it can connect to. Clients often use DNS aliases in their seed lists which means the host may return a server list that differs from the original seed list. If this happens, clients will use the hostnames provided by the replica set rather than the hostnames listed in the seed list to ensure that replica set members can be reached via the hostnames in the resulting replica set config.

Important

The hostnames returned in SRV records must share the same parent domain (in this example, example.com) as the given hostname. If the parent domains and hostname do not match, you will not be able to connect.

Like the standard connection string, the DNS seed list connection string supports specifying options as a query string. With a DNS seed list connection string, you can also specify the following options via a TXT record:

  • replicaSet

  • authSource

You may only specify one TXT record per mongod instance. If multiple TXT records appear in the DNS and/or if the TXT record contains an option other than replicaSet or authSource, the client will return an error.

The TXT record for the server.example.com DNS entry would resemble:

Record TTL Class Text
server.example.com. 86400 IN TXT "replicaSet=mySet&authSource=authDB"

Taken together, the DNS SRV records and the options specified in the TXT record resolve to the following standard format connection string:

mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?replicaSet=mySet&authSource=authDB

You can override the options specified in a TXT record by passing the option in the query string. In the following example, the query string has provided an override for the authSource option configured in the TXT record of the DNS entry above.

mongodb+srv://server.example.com/?connectTimeoutMS=300000&authSource=aDifferentAuthDB

Given the override for the authSource, the equivalent connection string in the standard format would be:

mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?connectTimeoutMS=300000&replicaSet=mySet&authSource=aDifferentAuthDB

Note

The mongodb+srv option will fail if there is no available DNS with records that correspond to the hostname identified in the connection string. In addition, use of the +srv connection string modifier automatically sets the tls (or the equivalent ssl) option to true for the connection. You can override this behavior by explicitly setting the tls (or the equivalent ssl) option to false with tls=false (or ssl=false) in the query string.

Tip

See:

This section lists all connection options.

Connection options are pairs in the following form: name=value.

  • The option name is case insensitive when using a driver.

  • The option name is case insensitive when using mongosh, or the version 4.2 or later legacy mongo shell.

  • The option name is case sensitive when using a version 4.0 and earlier legacy mongo shell.

  • The value is always case sensitive.

Separate options with the ampersand (i.e. &) character name1=value1&name2=value2. In the following example, a connection includes the replicaSet and connectTimeoutMS options:

mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000

Note

Semi-colon separator for connection string arguments

To provide backwards compatibility, drivers currently accept semi-colons (i.e. ;) as option separators.

The following connection string to a replica set named myRepl with members running on the specified hosts:

mongodb://db0.example.com:27017,db1.example.com:27017,db2.example.com:27017/?replicaSet=myRepl

Connection Option

Description

replicaSet

Specifies the name of the replica set, if the mongod is a member of a replica set.

When connecting to a replica set, provide a seed list of the replica set member(s) to the host[:port] component of the uri. For specific details, refer to your driver documentation.

The following connection string to a replica set includes tls=true option (available starting in MongoDB 4.2):

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&tls=true

Alternatively, you can also use the equivalent ssl=true option:

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&ssl=true

Connection Option

Description

tls

Enables or disables TLS/SSL for the connection:

  • true: Initiate the connection with TLS/SSL. Default for DNS Seed List Connection Format.

  • false: Initiate the connection without TLS/SSL. Default for Standard Connection String Format.

Note

The tls option is equivalent to the ssl option.

If the mongo shell specifies additional tls/ssl options from the command-line, use the --tls command-line option instead.

New in version 4.2.

ssl

A boolean to enable or disables TLS/SSL for the connection:

  • true: Initiate the connection with TLS/SSL. Default for DNS Seed List Connection Format.

  • false: Initiate the connection without TLS/SSL. Default for Standard Connection String Format.

Note

The ssl option is equivalent to the tls option.