MySQL二进制安装1、概述此次二进制安装是针对Linux操作系统无法使用root权限，只能使用普通用户部署安装MySQL；本次MySQL二进制安装采用的版本：5.7.372、环境操作系统为centos7.x安装必要的依赖包，此项由管理员安装，提前让管理员安装以下依赖包$ yum install bison bison-devel zlib-devel libcurl-devel libarchive-devel boost-devel gcc gcc-c++ cmake ncurses-devel gnutls-devel libxml2-devel openssl-devel libevent-devel libaio-devel perl perl-Data-Dumper libaio -y3、登陆服务器使用普通账户 mysql所有数据操作都将存在/home/mysql下，或有mysql账户权限的目录；4、创建数据目录# 创建数据目录 $ pwd /home/mysql $ mkdir hdata/mysql_data/{data,logs} -p # 创建MySQL软件存放目录 $ pwd /home/mysql $ mkdir software/{src,mysql} -p5、下载MySQL二进制包登陆MySQL官网下载通用版mysql 5.7.37网址 https://downloads.mysql.com/archives/community/6、解压安装包# 解压 $ pwd /home/mysql $ cd software/src $ tar xf mysql-5.7.37-linux-glibc2.12-x86_64.tar $ mv mysql-5.7.37-linux-glibc2.12-x86_64 mysql $ mv mysql ../7、创建MySQL配置文件# 创建mysql配置文件 $ cd software/mysql $ mkdir conf $ vi my.cnf [client] port = 3308 socket = /tmp/mysql.sock [mysqld] port = 3308 user = mysql character-set-server = utf8 default_storage_engine = innodb log_timestamps = SYSTEM basedir = /home/mysql/software/mysql datadir=/home/mysql/hdata/mysql_data/data max_connections = 5000 max_connect_errors = 1000 table_open_cache = 1024 max_allowed_packet = 128M open_files_limit = 65535 socket=/tmp/mysql.sock # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 binlog_format = MIXED query_cache_size = 128M query_cache_limit = 4M sort_buffer_size = 16M join_buffer_size = 16M wait_timeout=31536000 interactive_timeout=31536000 innodb_buffer_pool_size = 1024M innodb_file_per_table = 1 innodb_write_io_threads = 4 innodb_read_io_threads = 4 innodb_purge_threads = 2 innodb_flush_log_at_trx_commit = 1 innodb_log_file_size = 512M innodb_log_files_in_group = 2 innodb_log_buffer_size = 16M innodb_max_dirty_pages_pct = 80 innodb_rollback_on_timeout = on innodb_lock_wait_timeout = 28800 innodb_data_file_path=ibdata1:1024M:autoextend innodb_undo_tablespaces=3 lower_case_table_names = 1 slow_query_log = 1 long_query_time = 3 log-queries-not-using-indexes slow_query_log_file =/home/mysql/hdata/mysql_data/logs/mysql-slow.log sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES [mysqld_safe] log-error=/home/mysql/hdata/mysql_data/logs/mysqld.log pid-file=/tmp/mysqld.pid8、初始化MySQL$ cd software/mysql $ ./bin/mysqld --defaults-file=/home/mysql/software/mysql/conf/my.cnf --initialize --user=mysql --basedir=/home/mysql/software/mysql --datadir=/home/mysql/hdata/mysql_data/data --innodb_undo_tablespaces=3 --explicit_defaults_for_timestamp初始化完后mysql密码记得保存9、启动MySQL因无root权限，用普通账户启动mysql$ cd software/mysql/bin $ nohup ./mysqld --defaults-file=/home/mysql/software/mysql/conf/my.cnf --user=mysql --basedir=/home/mysql/software/mysql --datadir=/home/mysql/hdata/mysql_data/data &10、登陆并设置MySQL# 登陆MySQL $ cd software/mysql/bin # 密码是刚才初始化记录的密码 $ ./mysql -uroot -p -P3308 # 更新MySQL账户密码 mysql> set password for 'root'@'localhost'=password('1qaz@WSX3edc'); Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '1qaz@WSX3edc' WITH GRANT OPTION; Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | +--------------------+ 4 rows in set (0.00 sec) mysql> exit Bye此次MySQL二进制安装完成
[TOC]概述mysql5.7.32增加审计日志功能，记录数据库的操作获取审计功能插件下载5.5.68-MariaDB插件路径： /usr/lib64/mysql/plugin/server_audit.so 配置mysql5.7.321、获取mysql插件路径mysql> show global variables like '%plugin_dir%'; +---------------+--------------------------+ | Variable_name | Value | +---------------+--------------------------+ | plugin_dir | /usr/lib64/mysql/plugin/ | +---------------+--------------------------+ 1 row in set (0.01 sec)2、分发插件# 将插件放置此目录 $ cd /usr/lib64/mysql/plugin/ $ ll server_audit.so3、安装插件INSTALL PLUGIN server_audit SONAME 'server_audit.so';4、查看变量开启情况，默认都是关闭mysql> show variables like '%audit%';5、配置开启$ vim /etc/my.cnf # 新增以下配置 server_audit_logging=on server_audit_file_path =/hdata/mysql_data/log/server_audit.log server_audit_file_rotate_size=10000000 server_audit=FORCE_PLUS_PERMANEN6、重启mysql$ systemctl restart mysqld7、查看配置情况mysql> show variables like '%audit%'; +-------------------------------+----------------------------------------+ | Variable_name | Value | +-------------------------------+----------------------------------------+ | server_audit_events | | | server_audit_excl_users | | | server_audit_file_path | /hdata/mysql_data/log/server_audit.log | | server_audit_file_rotate_now | OFF | | server_audit_file_rotate_size | 10000000 | | server_audit_file_rotations | 9 | | server_audit_incl_users | | | server_audit_loc_info | | | server_audit_logging | ON | | server_audit_mode | 1 | | server_audit_output_type | file | | server_audit_query_log_limit | 1024 | | server_audit_syslog_facility | LOG_USER | | server_audit_syslog_ident | mysql-server_auditing | | server_audit_syslog_info | | | server_audit_syslog_priority | LOG_INFO | +-------------------------------+----------------------------------------+ 16 rows in set (0.00 sec)
mongodb备份与恢复备份恢复mongodb备份与恢复备份mongodump --host=127.0.0.1 --port=27017 -u root -p passwd --authenticationDatabase admin -d dbname -o /data/mongodb_data恢复mongorestore --host 127.0.0.1 --port 27017 -u root -p passwd --authenticationDatabase admin -d dbname /data/mongodb_data/dbnameCSDN地址：https://blog.csdn.net/qq_16125927/article/details/119111402
redis编译安装1.下载redis源码包2.编译安装3.同样操作放到另外5台服务器4.启动6台redis5.创建redis集群redis编译安装1.下载redis源码包下载源码包http://download.redis.io/releases/redis-5.0.12.tar.gz解决依赖yum install epel-release gcc make wget -y关闭防火墙及selinux2.编译安装解压源码包mkdir -pv /opt/software && tar xf redis-5.0.12.tar.gz -C /opt/software编译cd /opt/software/redis-5.0.12 make PREFIX=/opt/software/redis install创建配置文件及日志目录mkdir /opt/software/redis/{etc,log} -pv复制配置文件cd /opt/software/redis-5.0.12 cp redis.conf ../redis/etc/修改日志路径sed -i 's@logfile ""@logfile "/opt/software/redis/log/redis.log"@' /opt/software/redis/etc/redis.conf修改配置文件vim /opt/software/redis/etc/redis.conf 69 bind 0.0.0.0 136 daemonize yes 158 pidfile /var/run/redis_6379.pid 171 logfile "/opt/software/redis/log/redis.log" 263 dir /opt/software/redis/data 294 masterauth 1qaz@WSX 295 requirepass 1qaz@WSX 834 cluster-enabled yes 842 cluster-config-file nodes-6379.conf修改系统配置vim /etc/sysctl.conf net.core.somaxconn = 512 vm.overcommit_memory = 1 # 生效 sysctl -p其他系统参数echo never > /sys/kernel/mm/transparent_hugepage/enabled echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.local chmod a+x /etc/rc.local创建redis账户useradd -r redis -s /sbin/nologin chown -R redis.redis /opt/software/redis编写service文件[Unit] Description=Redis persistent key-value database After=network.target After=network-online.target Wants=network-online.target [Service] ExecStart=/opt/software/redis/bin/redis-server /opt/software/redis/etc/redis.conf --supervised systemd ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s QUIT $MAINPID Type=notify User=redis Group=redis RuntimeDirectory=redis RuntimeDirectoryMode=0755 [Install] WantedBy=multi-user.target讲redis.service放到指定路径/etc/systemd/system/3.同样操作放到另外5台服务器4.启动6台redis5.创建redis集群cd /opt/software/redis/bin ./redis-cli -a 1qaz@WSX --cluster create 192.168.103.245:6379 192.168.103.248:6379 192.168.103.214:6379 192.168.103.193:6379 192.168.103.119:6379 192.168.103.134:6379 --cluster-replicas 1登陆redis./redis-cli # 检查集群 127.0.0.1:6379> CLUSTER nodes b6409f0efb890e66b48d7b6dbb03787397d1f836 192.168.103.134:6379@16379 master - 0 1617762487000 9 connected 5461-10922 10ab3da13ec588eb96101d4c5ebec8be8f9f05bc 192.168.103.248:6379@16379 myself,slave b6409f0efb890e66b48d7b6dbb03787397d1f836 0 1617762488000 8 connected f9151756c823c1eb49962086f1bd512f68884593 192.168.103.245:6379@16379 master - 0 1617762487000 11 connected 0-5460 69a1f57e56641c7c612da8c8f6137936aea3c97f 192.168.103.193:6379@16379 master - 0 1617762489154 15 connected 10923-16383 dd35afb1d70a70559107ea2eafee181b50641988 192.168.103.214:6379@16379 slave 69a1f57e56641c7c612da8c8f6137936aea3c97f 0 1617762487667 15 connected 15090a833ae74e85ab6997b5b74c2eb3dbafaa89 192.168.103.119:6379@16379 slave f9151756c823c1eb49962086f1bd512f68884593 0 1617762486000 11 connected
1. 数据库安装1.1 mysql安装1.1.1 安装mysqld1.1.2 创建mysql主主复制1.1.3 安装keepalived1. 数据库安装1.1 mysql安装1.1.1 安装mysqldPS ：分别在docloud008和docloud012上按照以下步骤安装mysqld配置mysql yum源并安装 yum install http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm -y安装mysqlyum install mysql-community-server -y启动mysqlsystemctl start mysqld && systemctl enable mysqld修改mysql密码#获取默认密码 sudo grep 'temporary password' /var/log/mysqld.log # 登陆mysql mysql -uroot -p #修改mysql密码 set password for 'root'@'localhost'=password('MyNewPass4!'); # 修改远程登录密码 GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root用户的密码' WITH GRANT OPTION; # 刷新 flush privileges;配置mysql的配置文件#停止mysql服务 systemctl stop mysqld # 修改配置文件 vim /etc/my.cnf [mysqld] port=3308 #设置UTF-8编码 character_set_server=utf8 init_connect='SET NAMES utf8' #datadir=/var/lib/mysql #修改数据存储目录 datadir=/hdata/mysql_data/mysql socket=/var/lib/mysql/mysql.sock # Disabling symbolic-links is recommended to prevent assorted #security risks symbolic-links=0 #修改日志存储目录 log-error=/hdata/mysql_data/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid #开启binlog #binlog日志，即binary log，是二进制日志文件。它有两个作用，一是增量备份，#即只备份新增的内容；二是用于主从复制等，即主节点维护了一个binlog日志文#件，从节点从binlog中同步数据。 #当数据被误操作删除时，我们可以通过binlog日志恢复数据。 server-id=1 # 注意，集群没唯一id，master01为1，master02为2 log-bin=/hdata/mysql_data/binlog/bin-log #修改最大写入包 max_allowed_packet=10485760 #最大连接数 max_connections=1000 #设置默认时区 default-time-zone = '+08:00'将/var/lib/mysql拷贝到/hdata/mysql_datacd /var/lib sudo cp -r mysql /hdata/mysql_data/创建存储目录mkdir -pv /hdata/mysql_data/{log,binlog}修改mysql数据目录和日志目录文件夹属性sudo chown -R mysql:mysql /hdata/mysql_data重启mysqlsystemctl start mysqld1.1.2 创建mysql主主复制在master01上增加以下配置[root@docloud008 ~]# vim /etc/my.cnf # 主主复制配置 binlog_format = mixed relay-log = relay-bin relay-log-index = slave-relay-bin.index auto-increment-increment = 2 auto-increment-offset = 1在master02上增加以下配置[root@docloud012 ~]# vim /etc/my.cnf # 主主复制配置 binlog_format = mixed relay-log = relay-bin relay-log-index = slave-relay-bin.index auto-increment-increment = 2 auto-increment-offset = 2分别重启master01和master02的mysqld服务# master01 [root@docloud006 ~]# systemctl restart mysqld # master02 [root@docloud012 ~]# systemctl restart mysqld在master01上创建同步账户mysql> GRANT REPLICATION SLAVE ON *.* TO 'rep'@'172.20.0.44' IDENTIFIED BY '1qaz@WSX';在master01上查看binlog状态信息mysql> show master status; +------------------+----------+--------------+------------------+-------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | +------------------+----------+--------------+------------------+-------------------+ | mysql-bin.000001 | 154 | | | | +------------------+----------+--------------+------------------+-------------------+ 1 row in set (0.00 sec)在master02上将master01设置为主服务器并开启slavemysql> CHANGE MASTER TO -> MASTER_HOST='172.20.0.44', -> MASTER_USER='rep', -> MASTER_PASSWORD='1qaz@WSX', -> MASTER_PORT=3306, -> MASTER_LOG_FILE='mysql-bin.000001', -> MASTER_LOG_POS=154; Query OK, 0 rows affected, 2 warnings (0.00 sec) mysql> start slave; Query OK, 0 rows affected (0.00 sec)查看同步状态，都为yes为成功Slave_IO_Running和Slave_SQL_Running这两个值必须为Yes，代表从服务器能正常连接服务器在master02上创建授权账户mysql> GRANT REPLICATION SLAVE ON *.* TO 'rep'@'172.20.0.41' IDENTIFIED BY '1qaz@WSX'在master02上查看binlog状态mysql> show master status; +------------------+----------+--------------+------------------+-------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | +------------------+----------+--------------+------------------+-------------------+ | mysql-bin.000001 | 154 | | | | +------------------+----------+--------------+------------------+-------------------+ 1 row in set (0.00 sec)在master01上设置master02为主服务器并开启slavemysql> CHANGE MASTER TO -> MASTER_HOST='172.20.0.41', -> MASTER_USER='rep', -> MASTER_PASSWORD='1qaz@WSX', -> MASTER_PORT=3306, -> MASTER_LOG_FILE='mysql-bin.000001', -> MASTER_LOG_POS=154; Query OK, 0 rows affected, 2 warnings (0.00 sec) mysql> start slave; Query OK, 0 rows affected (0.00 sec)查看同步状态1.1.3 安装keepalived在master01上安装$ yum install keepalived -y # 修改配置文件 $ vim /etc/keepalived/keepalived.conf global_defs { notification_email { acassen@firewall.loc failover@firewall.loc sysadmin@firewall.loc } notification_email_from Alexandre.Cassen@firewall.loc smtp_server 192.168.200.1 smtp_connect_timeout 30 router_id LVS_DEVEL vrrp_skip_check_adv_addr # vrrp_strict # 关闭组播 vrrp_garp_interval 0 vrrp_gna_interval 0 } vrrp_instance VI_2 { state BACKUP # 服务状态；MASTER（工作状态）BACKUP（备用状态） interface eth0 # VIP绑定网卡 virtual_router_id 52 # 虚拟路由ID，主、备节点必须一致 mcast_src_ip 172.20.0.41 # 本机IP priority 100 # 优先级；取值范围：0~254；MASTER > BACKUP advert_int 1 # 组播信息发送间隔，主、备节点必须一致，默认1s nopreempt # 开启非抢占模式 unicast_src_ip 172.20.0.41 # 单播源地址 unicast_peer { 172.20.0.44 # 单播目的地址 } authentication { # 验证信息；主、备节点必须一致 auth_type PASS # VRRP验证类型，PASS、AH两种 auth_pass 1111 # VRRP验证密码，在同一个vrrp_instance下，主、从必须使用相同的密码才能正常通信 } virtual_ipaddress { # 虚拟IP池，主、备节点必须一致，可以定义多个VIP 172.20.0.102 # 虚拟IP } } 在master02上安装keepalived$ yum install keepalived -y # 修改配置文件 $ vim /etc/keepalived/keepalived.conf global_defs { notification_email { acassen@firewall.loc failover@firewall.loc sysadmin@firewall.loc } notification_email_from Alexandre.Cassen@firewall.loc smtp_server 192.168.200.1 smtp_connect_timeout 30 router_id LVS_DEVEL vrrp_skip_check_adv_addr # vrrp_strict # 关闭组播 vrrp_garp_interval 0 vrrp_gna_interval 0 } vrrp_instance VI_2 { state BACKUP # 服务状态；MASTER（工作状态）BACKUP（备用状态） interface eth0 # VIP绑定网卡 virtual_router_id 52 # 虚拟路由ID，主、备节点必须一致 mcast_src_ip 172.20.0.44 # 本机IP priority 100 # 优先级；取值范围：0~254；MASTER > BACKUP advert_int 1 # 组播信息发送间隔，主、备节点必须一致，默认1s nopreempt # 开启非抢占模式 unicast_src_ip 172.20.0.44 # 单播源地址 unicast_peer { 172.20.0.41 # 单播目的地址 } authentication { # 验证信息；主、备节点必须一致 auth_type PASS # VRRP验证类型，PASS、AH两种 auth_pass 1111 # VRRP验证密码，在同一个vrrp_instance下，主、从必须使用相同的密码才能正常通信 } virtual_ipaddress { # 虚拟IP池，主、备节点必须一致，可以定义多个VIP 172.20.0.102 # 虚拟IP } }分别重启master01和master02的keepalivedsystemctl restart keepalived # 查看ip,会显示172.20.0.102的ip地址 ip a
1、mongodb副本集部署服务器信息1.1、 集群拓扑图1.2、下载二进制包1.3、规划数据目录1.4、其他服务器部署1.5、创建mongodb配置文件1.6、 分别启动mongodb1.7、登陆任意一个节点1.8、测试1.9、开启用户认证1.10、启动集群1.11、验证集群状态1.12、导入数据测试账户密码认证及数据是否同步1、mongodb副本集部署服务器信息序号hostnameip配置1mongodb01192.168.0.2164核8g1T2mongodb02192.168.0.2174核8g1T3mongodb03192.168.0.2184核8g1T1.1、 集群拓扑图1.2、下载二进制包本次部署集群所使用mongodb版本为3.6.20官网下载地址：https://www.mongodb.com/try/download/community1.3、规划数据目录在mongodb_01上创建安装目录[root@mongodb_01 ~]# mkdir /hdata/mongo_data/{data,log,conf,keyfile} -pv mkdir: 已创建目录 "/hdata" mkdir: 已创建目录 "/hdata/mongo_data" mkdir: 已创建目录 "/hdata/mongo_data/data" mkdir: 已创建目录 "/hdata/mongo_data/log" mkdir: 已创建目录 "/hdata/mongo_data/conf" mkdir: 已创建目录 "/hdata/mongo_data/keyfile"软件路径[root@mongodb_01 ~]# mkdir /opt/software -pv mkdir: 已创建目录 "/opt/software"将mongodb二进制文件解压到/opt/software[root@mongodb_01 software]# tar xf mongodb-linux-x86_64-rhel70-3.6.20.tgz -C /opt/software/ [root@mongodb_01 software]# ll 总用量 119116 drwxr-xr-x. 3 root root 135 9月 21 15:03 mongodb-linux-x86_64-rhel70-3.6.20 -rw-r--r--. 1 root root 121973145 9月 21 15:00 mongodb-linux-x86_64-rhel70-3.6.20.tgz1.4、其他服务器部署分别在mongodb02和03上安装第五章3节3.3操作1.5、创建mongodb配置文件创建配置文件[root@mongodb_01 ~]# vim /hdata/mongo_data/conf/mongod.conf # mongod.conf systemLog: destination: file logAppend: true path: /hdata/mongo_data/log/mongod.log storage: dbPath: /hdata/mongo_data/data journal: enabled: true processManagement: fork: true # fork and run in background pidFilePath: /hdata/mongo_data/log/mongod.pid # location of pidfile timeZoneInfo: /usr/share/zoneinfo net: port: 27018 bindIp: 0.0.0.0 # Listen to local interface only, comment to listen on all interfaces. #security: # authorization: enabled # keyFile: /home/mongodb/37017/keyfile/keyfile # 设置副本集名称 replication: replSetName: "rs01"将mongodb_01的配置文件拷贝到另外2个节点# 拷贝到mongodb_02 [root@mongodb_01 ~]# scp /hdata/mongo_data/conf/mongod.conf mongodb_02:/hdata/mongo_data/conf/ # 拷贝到mongodb_03上 [root@mongodb_01 ~]# scp /hdata/mongo_data/conf/mongod.conf mongodb_03:/hdata/mongo_data/conf/1.6、 分别启动mongodbmongodb_01[root@mongodb_01 ~]# /opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongod -f /hdata/mongo_data/conf/mongod.conf about to fork child process, waiting until server is ready for connections. forked process: 2402 child process started successfully, parent exiting [root@mongodb_01 ~]# ss -nutl | grep 27018 tcp LISTEN 0 128 *:27018 *:*mongodb_02[root@mongodb_02 ~]# /opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongod -f /hdata/mongo_data/conf/mongod.conf about to fork child process, waiting until server is ready for connections. forked process: 4418 child process started successfully, parent exiting [root@mongodb_02 ~]# ss -nutl | grep 27018 tcp LISTEN 0 128 *:27018 *:*mongodb_03[root@mongodb_03 ~]# /opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongod -f /hdata/mongo_data/conf/mongod.conf about to fork child process, waiting until server is ready for connections. forked process: 4453 child process started successfully, parent exiting [root@mongodb_03 ~]# ss -nutl | grep 27018 tcp LISTEN 0 128 *:27018 *:*1.7、登陆任意一个节点a> 开启副本集集群[root@mongodb_01 ~]# /opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongo --port 27018 # 创建副本集配置文件 > conf={"_id":"rs01","members":[{"_id":0,"host":"192.168.0.216:27018"},{"_id":1,"host":"192.168.0.217:27018"},{"_id":2,"host":"192.168.0.218:27018"}]} { "_id" : "rs01", "members" : [ { "_id" : 0, "host" : "192.168.0.216:27018" }, { "_id" : 1, "host" : "192.168.0.217:27018" }, { "_id" : 2, "host" : "192.168.0.218:27018" } ] } # 初始化副本集配置文件 > rs.initiate(conf) { "ok" : 1, "operationTime" : Timestamp(1600674253, 1), "$clusterTime" : { "clusterTime" : Timestamp(1600674253, 1), "signature" : { "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId" : NumberLong(0) } } }b> 查看副本集集群状态rs01:SECONDARY> rs.status() { "set" : "rs01", "date" : ISODate("2020-09-21T07:45:25.575Z"), "myState" : 1, "term" : NumberLong(1), "syncingTo" : "", "syncSourceHost" : "", "syncSourceId" : -1, "heartbeatIntervalMillis" : NumberLong(2000), "optimes" : { "lastCommittedOpTime" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) }, "readConcernMajorityOpTime" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) }, "appliedOpTime" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) }, "durableOpTime" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) } }, "members" : [ { "_id" : 0, #第一个节点的id号 "name" : "192.168.0.216:27018", #第一个节点的ip+port "health" : 1, #第一个节点的健康情况：1表示正常，0表示不正常 "state" : 1, "stateStr" : "PRIMARY", #第一个节点在副本集的集群状态，primary表示主节点，secondary表示从节点 "uptime" : 1087, "optime" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) }, "optimeDate" : ISODate("2020-09-21T07:45:16Z"), "syncingTo" : "", "syncSourceHost" : "", "syncSourceId" : -1, "infoMessage" : "could not find member to sync from", "electionTime" : Timestamp(1600674264, 1), "electionDate" : ISODate("2020-09-21T07:44:24Z"), "configVersion" : 1, "self" : true, "lastHeartbeatMessage" : "" }, { "_id" : 1, "name" : "192.168.0.217:27018", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 72, "optime" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) }, "optimeDurable" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) }, "optimeDate" : ISODate("2020-09-21T07:45:16Z"), "optimeDurableDate" : ISODate("2020-09-21T07:45:16Z"), "lastHeartbeat" : ISODate("2020-09-21T07:45:24.593Z"), "lastHeartbeatRecv" : ISODate("2020-09-21T07:45:25.379Z"), "pingMs" : NumberLong(0), "lastHeartbeatMessage" : "", "syncingTo" : "192.168.31.11:27017", "syncSourceHost" : "192.168.31.11:27017", "syncSourceId" : 0, "infoMessage" : "", "configVersion" : 1 }, { "_id" : 2, "name" : "192.168.0.218:27018", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 72, "optime" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) }, "optimeDurable" : { "ts" : Timestamp(1600674316, 1), "t" : NumberLong(1) }, "optimeDate" : ISODate("2020-09-21T07:45:16Z"), "optimeDurableDate" : ISODate("2020-09-21T07:45:16Z"), "lastHeartbeat" : ISODate("2020-09-21T07:45:24.592Z"), "lastHeartbeatRecv" : ISODate("2020-09-21T07:45:25.379Z"), "pingMs" : NumberLong(0), "lastHeartbeatMessage" : "", "syncingTo" : "192.168.31.11:27017", "syncSourceHost" : "192.168.31.11:27017", "syncSourceId" : 0, "infoMessage" : "", "configVersion" : 1 } ], "ok" : 1, "operationTime" : Timestamp(1600674316, 1), "$clusterTime" : { "clusterTime" : Timestamp(1600674316, 1), "signature" : { "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId" : NumberLong(0) } } }c> 查看副本集集群配置rs01:PRIMARY> rs.conf() { "_id" : "rs01", "version" : 1, "protocolVersion" : NumberLong(1), "members" : [ { "_id" : 0, "host" : "192.168.0.216:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, #该节点的优先级 "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 }, { "_id" : 1, "host" : "192.168.0.217:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 }, { "_id" : 2, "host" : "192.168.0.218:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 } ], "settings" : { "chainingAllowed" : true, "heartbeatIntervalMillis" : 2000, "heartbeatTimeoutSecs" : 10, "electionTimeoutMillis" : 10000, "catchUpTimeoutMillis" : -1, "catchUpTakeoverDelayMillis" : 30000, "getLastErrorModes" : { }, "getLastErrorDefaults" : { "w" : 1, "wtimeout" : 0 }, "replicaSetId" : ObjectId("5f6859cde1d641b3427af2a7") } }d> 修改mongodb01和02优先级，03优先级保持不变，只参与选举及数据同步#自定义服务配置信息 rs01:PRIMARY> cfg=rs.conf() { "_id" : "rs01", "version" : 1, "protocolVersion" : NumberLong(1), "members" : [ { "_id" : 0, "host" : "192.168.0.216:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 }, { "_id" : 1, "host" : "192.168.0.217:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 }, { "_id" : 2, "host" : "192.168.0.218:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 } ], "settings" : { "chainingAllowed" : true, "heartbeatIntervalMillis" : 2000, "heartbeatTimeoutSecs" : 10, "electionTimeoutMillis" : 10000, "catchUpTimeoutMillis" : -1, "catchUpTakeoverDelayMillis" : 30000, "getLastErrorModes" : { }, "getLastErrorDefaults" : { "w" : 1, "wtimeout" : 0 }, "replicaSetId" : ObjectId("5f6859cde1d641b3427af2a7") } } # mongodb_02服务器优先级，id=1，优先级是2 或 如果做高可用，1宕机，2提升主，3一直为SECONDARY，可以把1和2的优先级都设置为2,3还是1，保持不变 # 这样就可以实现1宕机，2提升主，3参与选举，并且1恢复后以从节点加入，避免不必要的主从切换，确保2的数据能及时同步到1 rs01:PRIMARY> cfg.members[1].priority=2 2 rs01:PRIMARY> cfg.members[0].priority=2 2 # 重新加载配置信息 rs01:PRIMARY> rs.reconfig(cfg) { "ok" : 1, "operationTime" : Timestamp(1600675177, 1), "$clusterTime" : { "clusterTime" : Timestamp(1600675177, 1), "signature" : { "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId" : NumberLong(0) } } }e> 重新查看集群配置信息rs01:SECONDARY> rs.conf() { "_id" : "rs01", "version" : 2, "protocolVersion" : NumberLong(1), "members" : [ { "_id" : 0, "host" : "192.168.0.216:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 }, { "_id" : 1, "host" : "192.168.0.217:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 2, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 }, { "_id" : 2, "host" : "192.168.0.218:27018", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 } ], "settings" : { "chainingAllowed" : true, "heartbeatIntervalMillis" : 2000, "heartbeatTimeoutSecs" : 10, "electionTimeoutMillis" : 10000, "catchUpTimeoutMillis" : -1, "catchUpTakeoverDelayMillis" : 30000, "getLastErrorModes" : { }, "getLastErrorDefaults" : { "w" : 1, "wtimeout" : 0 }, "replicaSetId" : ObjectId("5f6859cde1d641b3427af2a7") } }f> 重新查看集群状态rs01:SECONDARY> rs.status() { "set" : "rs01", "date" : ISODate("2020-09-21T08:04:54.966Z"), "myState" : 2, "term" : NumberLong(2), "syncingTo" : "192.168.0.216:27018", "syncSourceHost" : "192.168.0.216:27018", "syncSourceId" : 2, "heartbeatIntervalMillis" : NumberLong(2000), "optimes" : { "lastCommittedOpTime" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) }, "readConcernMajorityOpTime" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) }, "appliedOpTime" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) }, "durableOpTime" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) } }, "members" : [ { "_id" : 0, "name" : "192.168.0.216:27018", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 2256, "optime" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) }, "optimeDate" : ISODate("2020-09-21T08:04:48Z"), "syncingTo" : "192.168.0.216:27018", "syncSourceHost" : "192.168.0.216:27018", "syncSourceId" : 2, "infoMessage" : "", "configVersion" : 2, "self" : true, "lastHeartbeatMessage" : "" }, { "_id" : 1, "name" : "192.168.0.217:27018", "health" : 1, "state" : 1, "stateStr" : "PRIMARY", #id为1的服务已提升为主节点 "uptime" : 1241, "optime" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) }, "optimeDurable" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) }, "optimeDate" : ISODate("2020-09-21T08:04:48Z"), "optimeDurableDate" : ISODate("2020-09-21T08:04:48Z"), "lastHeartbeat" : ISODate("2020-09-21T08:04:53.510Z"), "lastHeartbeatRecv" : ISODate("2020-09-21T08:04:54.489Z"), "pingMs" : NumberLong(0), "lastHeartbeatMessage" : "", "syncingTo" : "", "syncSourceHost" : "", "syncSourceId" : -1, "infoMessage" : "", "electionTime" : Timestamp(1600675187, 1), "electionDate" : ISODate("2020-09-21T07:59:47Z"), "configVersion" : 2 }, { "_id" : 2, "name" : "192.168.0.218:27018", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 1241, "optime" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) }, "optimeDurable" : { "ts" : Timestamp(1600675488, 1), "t" : NumberLong(2) }, "optimeDate" : ISODate("2020-09-21T08:04:48Z"), "optimeDurableDate" : ISODate("2020-09-21T08:04:48Z"), "lastHeartbeat" : ISODate("2020-09-21T08:04:53.436Z"), "lastHeartbeatRecv" : ISODate("2020-09-21T08:04:52.966Z"), "pingMs" : NumberLong(0), "lastHeartbeatMessage" : "", "syncingTo" : "192.168.0.216:27018", "syncSourceHost" : "192.168.0.216:27018", "syncSourceId" : 1, "infoMessage" : "", "configVersion" : 2 } ], "ok" : 1, "operationTime" : Timestamp(1600675488, 1), "$clusterTime" : { "clusterTime" : Timestamp(1600675488, 1), "signature" : { "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId" : NumberLong(0) } } }1.8、测试主节点插入数据rs01:PRIMARY> for(var i=0;i<10000;i++){db.customer.insert({"name":"user"+i})} WriteResult({ "nInserted" : 1 }) rs01:PRIMARY> db.customer.count() 10000从节点查数据rs01:SECONDARY> rs.secondaryOk() #开启从节点可查询条件 rs01:SECONDARY> db.customer.count() 100001.9、开启用户认证a> 在主节点创建用户rs01:PRIMARY> use admin switched to db admin rs01:PRIMARY> db.createUser({user:"root",pwd:"root@0321",roles:[{role:"root",db:"admin"}]}) Successfully added user: { "user" : "root", "roles" : [ { "role" : "root", "db" : "admin" } ] }b> 创建安全认证依次停止mongodb副本集集群首先停从节点，然后停止主节点#主节点是mongodb_02,从节点是mongodb_01和mongodb_03 #停止从节点 /opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongod -shutdown -dbpath=/hdata/mongo_data/data #停止主节点 /opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongod -shutdown -dbpath=/hdata/mongo_data/datac> 创建keyfile文件在任意一台服务器上创建，再复制到其他服务器上[root@mongodb_01 keyfile]# pwd /hdata/mongo_data/keyfile [root@mongodb_01 keyfile]# openssl rand -base64 756 > keyfile [root@mongodb_01 keyfile]# ll 总用量 4 -rw-r--r--. 1 root root 1024 9月 21 16:32 keyfile [root@mongodb_01 keyfile]# chmod 600 keyfile [root@mongodb_01 keyfile]# ll 总用量 4 -rw-------. 1 root root 1024 9月 21 16:32 keyfile [root@mongodb_01 keyfile]# scp keyfile 192.168.0.217:/hdata/mongo_data/keyfile/ root@192.168.0.217's password: keyfile 100% 1024 1.1MB/s 00:00 [root@mongodb_01 keyfile]# scp keyfile 192.168.0.218:/hdata/mongo_data/keyfile/ root@192.168.0.218's password: keyfile 100% 1024 994.4KB/s 00:00 [root@mongodb_01 keyfile]#配置mongodb配置文件，然后分发到其他2台服务器上vim /hdata/mongo_data/conf/mongod.conf # mongod.conf systemLog: destination: file logAppend: true path: /hdata/mongo_data/log/mongod.log storage: dbPath: /hdata/mongo_data/data journal: enabled: true processManagement: fork: true # fork and run in background pidFilePath: /hdata/mongo_data/log/mongod.pid # location of pidfile timeZoneInfo: /usr/share/zoneinfo net: port: 27018 bindIp: 0.0.0.0 # Listen to local interface only, comment to listen on all interfaces. #开启认证 security: authorization: enabled keyFile: /hdata/mongo_data/keyfile/keyfile # 设置副本集名称 replication: replSetName: "rs01"1.10、启动集群先启动主节点，再启动从节点启动mongodb02主节点/opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongod -f /hdata/mongo_data/conf/mongod.conf启动从节点01和03/opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongod -f /hdata/mongo_data/conf/mongod.conf1.11、验证集群状态rs01:PRIMARY> use admin switched to db admin rs01:PRIMARY> db.auth("root","root@0321") 1 rs01:PRIMARY> rs.status()1.12、导入数据测试账户密码认证及数据是否同步主节点导入数据#主节点导入数据 [root@mongodb_02 mongo_data]# /opt/software/mongodb-linux-x86_64-rhel70-3.6.20/bin/mongoimport --host 127.0.0.1 --port 27017 -d testa -u root -p root@0321 --authenticationDatabase admin -c thumb_image --file thumb_image.json 2020-09-21T16:52:28.555+0800 connected to: 127.0.0.1:27017 2020-09-21T16:52:31.328+0800 imported 178 documents检查从节点数据rs01:SECONDARY> db.auth("root","root@0321") 1 rs01:SECONDARY> rs.secondaryOk() rs01:SECONDARY> show dbs admin 0.000GB config 0.000GB local 0.027GB test 0.000GB testa 0.026GB rs01:SECONDARY> use testa switched to db testa rs01:SECONDARY> show collections thumb_image