在之前MongoDB 安装的博客中,实际上已经介绍了Mongodb 启动和关闭方法。
Redhat 7.7 平台 MongoDB 4.4.6 安装 配置 手册
https://www.cndba.cn/dave/article/4542
1 启动
启动这块比较简单,主要是配置文件中参数的指定,这个我们后面再说,这里假设配置文件已经配置完成。
直接在命令行执行如下命令启动:
mongod —config /etc/mongod.conf
mongod -f /etc/mongod.conf
[dave@www.cndba.cn ~]# mongod --config /etc/mongo.conf
about to fork child process, waiting until server is ready for connections.
forked process: 49945
child process started successfully, parent exiting
[dave@www.cndba.cn ~]# ps -ef|grep mongo
root 43880 17422 0 11:49 pts/2 00:00:00 mongo
root 49945 1 52 12:03 ? 00:00:04 mongod --config /etc/mongo.conf
root 50046 41028 0 12:03 pts/3 00:00:00 grep --color=auto mongo
[dave@www.cndba.cn ~]#
当然也可以参考之前安装博客的方法,配置成服务进行管理。
2 关闭
2.1 方法1:正常关闭
MongoDB的关闭方法有很多,我们之前安装博客里用的方法是使用mongod 选项,如下:
[dave@www.cndba.cn data]# ps -ef|grep -v grep|grep mongo
root 123056 1 0 13:13 ? 00:00:33 /usr/local/mongodb/bin/mongod -f /etc/mongo.conf
[dave@www.cndba.cn data]#
[dave@www.cndba.cn data]#
[dave@www.cndba.cn data]# mongod -f /etc/mongo.conf --shutdown
killing process with pid: 123056
[dave@www.cndba.cn data]# ps -ef|grep -v grep|grep mongo
[dave@www.cndba.cn data]#
2.2 方法2:正常关闭
连上数据库操作:
> use admin
switched to db admin
> db.auth('root','root')
1
> db.shutdownServer()
server should be down...
>
2.3 方法3: 强制关闭
登入MongoDB,强制关闭数据库:
> use admin
switched to db admin
> db.auth('root','root')
1
> db.adminCommand({shutdown : 1, force : true})
uncaught exception: Error: error doing query: failed: network error while attempting to run command 'shutdown' on host '127.0.0.1:27017' :
DB.prototype.runCommand@src/mongo/shell/db.js:169:19
DB.prototype.adminCommand@src/mongo/shell/db.js:186:16
@(shell):1:1
>
关于该命令的参数说明,可以参考官方手册:
https://www.mongodb.com/docs/manual/reference/command/shutdown/
亦可采用此种方式强制关闭:
> db.shutdownServer({force : true})
server should be down...
关于该命令的参数说明,可以参考官方手册:
https://www.mongodb.com/docs/manual/reference/method/db.shutdownServer
2.4 方法4: OS 级别Kill
这里要注意kill 的参数。
[dave@www.cndba.cn yum.repos.d]# ps -ef|grep -v grep|grep mongo
root 39028 16742 0 15:25 pts/2 00:00:00 mongo
root 40105 1 24 15:28 ? 00:00:00 /usr/local/mongodb/bin/mongod -f /etc/mongo.conf
[dave@www.cndba.cn yum.repos.d]#
我们这里MongoDB的进行pid 是:40105。
我们可以使用
- kill -2 40105(SIGINT)
或者 - kill 40105(SIGTERM) 来关闭DB。
因为当 mongod 收到 SIGINT 或者 SIGTERM 时,会安全的退出,会等到当前运行的操作或者文件预分配完成(需要一些时间),关闭所有打开的连接,将缓存的数据刷新到磁盘,最后停止。
这里注意,不要使用SIGKILL信号(kill -9)。这样会导致数据库直接关闭,这会使数据文件损毁。
我们在之前关于日志的博客的1.1 小结中,我们了解到一个知识点:
MongoDB 日志 管理
https://www.cndba.cn/dave/article/107961
就是WiredTiger 引擎从buffer 中刷journal records 到 journal log 的4个条件。 最基本的就是每100毫秒会刷新一次。 实际上,在2次写操作之间,如果WiredTiger buffers 的journal records 因为mongod 进程异常关闭而没有刷到日志文件,那么对应的写操作就会地址。
如果采用kill -9 的方式,很可能会导致数据丢失。
版权声明:本文为博主原创文章,未经博主允许不得转载。



