当前位置: 首页 > 工具软件 > pam-mongodb > 使用案例 >

[安装配置启动]用MongoDB-4.0.2二进制包部署单实例

曹经业
2023-12-01

第1章 基本环境和基本优化

1.1 My操作系统环境

### 操作系统版本
[root@vm7-121 ~]# cat /etc/redhat-release;uname -r;uname -m
CentOS Linux release 7.9.2009 (Core)
3.10.0-1160.el7.x86_64
x86_64

### 网卡及配置
[root@vm7-121 ~]# ip addr show ens33
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:e3:4a:4d brd ff:ff:ff:ff:ff:ff
    inet 10.4.7.121/24 brd 10.4.7.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fee3:4a4d/64 scope link 
       valid_lft forever preferred_lft forever

### 能否访问互联网
[root@vm7-121 ~]# ping -l 10.4.7.121 -c 2 www.baidu.com
PING www.a.shifen.com (14.215.177.38) 56(84) bytes of data.
64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=1 ttl=128 time=34.2 ms
64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=2 ttl=128 time=34.4 ms

--- www.a.shifen.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 34.239/34.359/34.480/0.221 ms, pipe 2

1.2 系统的基本优化

### 更改主机名
hostnamectl set-hostname  \
   vm$(ip addr show ens33|awk -F "[ /]" 'NR==3{print $6}'|awk -F "." '{print $3"-"$4}').host.com

### 更改base源和epel源
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
yum install -y epel-release

### 安装常用工具
yum install -y  \
 tree telnet lrzsz wget ntpdate vim  nc namp dos2unix  tcpdump  expect elinks  \
 lsof net-tools iproute  bridge-utils \
 bind-utils nscd \
 gcc gcc-c++ make cmake libaio zlib-devel pcre-devel  \
 psmisclsof sysstat yum-utils 

### 关闭SELINUX
sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
setenforce 0

### 设置支持中文字符
echo "LANG=\"zh_CN.UTF-8\"" >/etc/locale.conf

### 资源描述符
cat >>/etc/security/limits.conf<<EOF
* soft nproc  65535
* hard nproc  65535
* soft nofile 65535
* hard nofile 65535
* soft stack  65535
* hard stack  65535
EOF

echo " * - nproc 65535" >/etc/security/limits.d/20-nproc.conf
echo "session    required    pam_limits.so" >>/etc/pam.d/login

################ 关闭大内存页
## 立即关闭
echo "never" >/sys/kernel/mm/transparent_hugepage/defrag
echo "never" >/sys/kernel/mm/transparent_hugepage/enabled

## 让其下次开机时执行后生效
cat >>/etc/rc.local<<'EOF'
#### Transparent Huge Pages(THP)
echo "never" >/sys/kernel/mm/transparent_hugepage/defrag
echo "never" >/sys/kernel/mm/transparent_hugepage/enabled
EOF

第2章 安装MongoDB软件

2.1 软件从哪里下载

因为我的操作系统是CentOS 7.9,所以我这里只给出相应平台下相应软件版本的下载地址

https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.0.2.tgz

2.2 软件部署的规划

/data/apps/mongodb
	# 它是个软件链接,指向的是/data/apps/mongodb-linux-x86_64-rhel70-4.0.2
	# 后面的实例我用app用户来启动,所以在安装软件阶段要先创建,后面让其属主/组为app

2.3 软件部署的步骤

#### 创建app用户,后面在app用户下面来启动MongoDB实例
chattr -i /etc/passwd /etc/shadow /etc/group /etc/gshadow
useradd app  
echo "app123456"|passwd --stdin app
id app


#### 创建软件的安装目录
mkdir -p /data//apps/
ls -ld /data/apps/


#### 上传软件包进行安装
ll mongodb-linux-x86_64-rhel70-4.0.2.tgz
tar xf mongodb-linux-x86_64-rhel70-4.0.2.tgz -C /data/apps/
cd /data/apps
ln -sv mongodb-linux-x86_64-rhel70-4.0.2   mongodb
chown -R app:app /data/apps/mongodb/


#### 配置环境变量
ls -ld /data/apps/mongodb/bin

cat >>/etc/bashrc<<'EOF'
export PATH=/data/apps/mongodb/bin:$PATH
EOF

source /etc/bashrc
which mongo mongos mongod

#### 查看其版本
mongod --version|head -1

#### 相关命令/工具的介绍
[root@vm7-121~]# ll /data/apps/mongodb/bin/
total 251580
-rwxr-xr-x 1 app app 12393712 Aug 28  2018 bsondump
-rwxr-xr-x 1 app app     5792 Aug 28  2018 install_compass
-rwxr-xr-x 1 app app 39682368 Aug 28  2018 mongo            # 客户端工具,跟MySQL的mysql命令一样
-rwxr-xr-x 1 app app 61947728 Aug 28  2018 mongod           # 服务端工具,跟MySQL的mysqld命令一样
-rwxr-xr-x 1 app app 14702936 Aug 28  2018 mongodump        # 客户端工具,跟MySQL的mysqldump命令一样
-rwxr-xr-x 1 app app 12733096 Aug 28  2018 mongoexport      # 
-rwxr-xr-x 1 app app 12634648 Aug 28  2018 mongofiles
-rwxr-xr-x 1 app app 12892232 Aug 28  2018 mongoimport
-rwxr-xr-x 1 app app 13972728 Aug 28  2018 mongoreplay
-rwxr-xr-x 1 app app 15821536 Aug 28  2018 mongorestore
-rwxr-xr-x 1 app app 35269760 Aug 28  2018 mongos           # 
-rwxr-xr-x 1 app app 12947464 Aug 28  2018 mongostat
-rwxr-xr-x 1 app app 12589240 Aug 28  2018 mongotop

第3章 部署mongodb单实例

3.1 实例部署前规划

/data/mongodb/27017/     # 以端口区分每个实例
├── conf                 # 存放27017实例的配置文件
├── data                 # 存放27017实例的数据文件
├── logs                 # 存放27017实例的日志文件
├── run                  # 存放27017实例的pid和socket文件
└── scripts              # 存放27017实例的相关脚本(启停脚本、数据备份脚本等)

3.2 实例部署的步骤

#### 创建相关的目录
mkdir -p /data/mongodb/27017/{data,conf,logs,run,scripts}
tree /data/mongodb/27017

#### 更改/data/mongodb/目录极其子目录的属主/组
chown -R app:app  /data/mongodb/

#### 准备27017实例的配置文件(简化版,注意,IP地址填你自己服务器的IP地址)
cat >>/data/mongodb/27017/conf/mongod.conf<<'EOF'
## network
net:
  port: 27017
  ipv6: false
  bindIpAll: false
  bindIp: 10.4.7.121,127.0.0.1
  maxIncomingConnections: 3000
  wireObjectCheck: true
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/27017/run
    filePermissions: 0700

## storage
storage:
  dbPath: /data/mongodb/27017/data
  journal:
    enabled: true
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 1

## log
systemLog:
  destination: file
  logAppend: true
  path:  /data/mongodb/27017/logs/mongod.log
  quiet: false

## process
processManagement:
  fork: true
  pidFilePath:  /data/mongodb/27017/run/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

## security
security:
  authorization: enabled
  javascriptEnabled: false
EOF

3.3 准备其启停脚本

编写启停脚本 /data/mongodb/27017/scripts/mongod.sh

#!/bin/bash
#
# Explain: MongoDB start、stop scripts 
#
# Define variables
RETVAL=0
MonPort="27017"
MonConf="/data/mongodb/$MonPort/conf/mongod.conf"
MonCommPath="/data/apps/mongodb/bin"

# Load local funcation
[ -f /etc/init.d/functions ] && source /etc/init.d/functions

# Define functions
start(){
	MonStatusCheck="$(ss -lntup|grep -w "$MonPort"|wc -l)"
	if [ "$MonStatusCheck" -eq 0 ];then
           $MonCommPath/mongod -f $MonConf --fork >/dev/null 2>&1
           RETVAL=$?
           if [ $RETVAL -eq 0 ];then
              action "Start mongodb service[$MonPort]" /bin/true
             else
              action "Start mongodb service[$MonPort]" /bin/false
	   fi
          else
           echo "mongodb service[$MonPort] is running"
	fi
	return $RETVAL
}

stop(){
	MonStatusCheck="$(ss -lntup|grep -w "$MonPort"|wc -l)"
	if [ "$MonStatusCheck" -ne 0 ];then
           $MonCommPath/mongod --shutdown -f $MonConf  >/dev/null 2>&1
           RETVAL=$?
	   if [ $RETVAL -eq 0 ];then
              action "Stop mongodb service[$MonPort]" /bin/true
             else
              action "Stop mongodb service[$MonPort]" /bin/false
	   fi
          else
	   echo "mongodb service[$MonPort] is not running"
	fi
	return $RETVAL
}

status(){
	MonStatusCheck="$(ss -lntup|grep -w "$MonPort"|wc -l)"
	if [ "$MonStatusCheck" -ne 0 ];then
	   echo "mongodb service[$MonPort] is running"
	  else
	   echo "mongodb service[$MonPort] is not running"
	fi
	return $RETVAL
}

# case call define functiosn
case "$1" in
	start)
		start
		RETVAL=$?
		;;
	stop)
		stop
		RETVAL=$?
		;;
	restart)
		stop
		sleep 5
		start
		RETVAL=$?
		;;
	status)
		status
		RETVAL=$?
		;;
	*)
		echo "USAGE:$0{start|stop|restart|status}"
		exit 1
esac

给启停脚本加权限,更改相应的属主/组

#### 更改属主/组为app用户
chown -R app:app /data/mongodb

#### 给脚本加可执行权限
ll /data/mongodb/27017/scripts/mongod.sh 
chmod 744 /data/mongodb/27017/scripts/mongod.sh
ll /data/mongodb/27017/scripts/mongod.sh 

启动服务是否正常

#### 检查shell脚本(重启mongodb实例)
[root@vm7-121 ~]#
[root@vm7-121 ~]# sudo su - app -s /bin/bash -c "/data/mongodb/27017/scripts/mongod.sh"
USAGE:/data/mongodb/27017/scripts/mongod.sh{start|stop|restart|status}
[root@vm7-121 ~]#
[root@vm7-121 ~]# sudo su - app -s /bin/bash -c "/data/mongodb/27017/scripts/mongod.sh status"
mongodb service[27017] is not running
[root@vm7-121 ~]#
[root@vm7-121 ~]# sudo su - app -s /bin/bash -c "/data/mongodb/27017/scripts/mongod.sh start"
Start mongodb service[27017] [  确定  ]
[root@vm7-121 ~]#
[root@vm7-121 ~]# sudo su - app -s /bin/bash -c "/data/mongodb/27017/scripts/mongod.sh status"
mongodb service[27017] is running
[root@vm7-121 ~]#
[root@vm7-121 ~]# sudo su - app -s /bin/bash -c "/data/mongodb/27017/scripts/mongod.sh stop"
Stop mongodb service[27017] [  确定  ]
[root@vm7-121 ~]#
[root@vm7-121 ~]# sudo su - app -s /bin/bash -c "/data/mongodb/27017/scripts/mongod.sh restart"
mongodb service[27017] is not running
Start mongodb service[27017] [  确定  ]


#### 检查mongod服务是否正常运行
[root@vm7-121 tools]# ss -lntup|grep 27017
tcp    LISTEN     0      128    127.0.0.1:27017                 *:*                   users:(("mongod",pid=2597,fd=12))
tcp    LISTEN     0      128    10.4.7.121:27017                 *:*                  users:(("mongod",pid=2597,fd=11))
[root@vm7-121 tools]#
[root@vm7-121 tools]#
[root@vm7-121 tools]# ss -lntup|grep mongod
tcp    LISTEN     0      128    127.0.0.1:27017                 *:*                   users:(("mongod",pid=2597,fd=12))
tcp    LISTEN     0      128    10.4.7.121:27017                 *:*                  users:(("mongod",pid=2597,fd=11))

将脚本加入开机自启动(我是放在)

#### 将脚本放在/etc/rc.local文件中
cat >>/etc/rc.local<<EOF

# Boot start mongodb service. USER:chenliang TIME:$(date +%F)
chown -R app:app /data/mongodb/
su - app -s /bin/bash -c "/data/mongodb/27017/scripts/mongod.sh start"
EOF

#### 查看/etc/rc.local文件的后三行
[root@vm7-200 ~]#
[root@vm7-200 ~]# tail -3 /etc/rc.local 
# Boot start mongodb service. USER:chenliang TIME:2021-11-17
chown -R app:app /data/mongodb/
su - app -s /bin/bash -c "/data/mongodb/27017/scripts/mongod.sh start"


#### 给/etc/rc.local文件所指定的文件加执行权限
[root@vm7-121 ~]#
[root@vm7-121 ~]# chmod 744 /etc/rc.d/rc.local 
[root@vm7-121 ~]# ll /etc/rc.d/rc.local 
-rwx------. 1 root root 614 3月  28 21:36 /etc/rc.d/rc.local
[root@vm7-121 ~]#

3.4 创建两个超级用户

给mongod实例本身创建一个超级用户,给我自己创建一个超级用户。

给MongoDB实例创建一个超级用户

mongo 127.0.0.1:27017                   // 为啥要这样连接,因为我启动前开了访问控制的,你不这样连接,你进行后无法创建用户哈;

use admin;
db.createUser(
{
    user: "root",
    pwd: "root123456",
    roles: [
			{role: "root",db: "admin"}
	 ]
}
);

db.auth("root","root123456");   // 进行认证

exit;                            // 退出当前连接

给我这个管理员创建一个超级用户

// 用前面创建的root用户登录
mongo --host=10.4.7.121 --port=27017 --username=root --password=root123456 --authenticationDatabase=admin

db.getName();

use admin;

db.createUser(
{
    user: "chenliang",
    pwd: "chenliang123456",
    roles: [
			{role: "root",db: "admin"}
	]
}
);

exit;

// 验证chenliang用户
mongo --host=10.4.7.121 --port=27017 --username=chenliang --password=chenliang123456 --authenticationDatabase=admin
db.getName();   // 是处于test库下的,而不是在admin下哈;
show dbs;       // 查看有哪些数据库
exit;           // 退出当前连接
 类似资料: