linux 使用docker安装mongodb方法

1、到home目录下新建Mongotest文件夹,进入这个文件夹,执行vi docker-compose.yml,插入如下内容

[root@server02 ~]# cat docker-compose.yml 
version: '3.1'
services:
 mongo:
  image: mongo
  restart: always
  environment: 
    MONGO_INITDB_ROOT_USERNAME: root
    MONGO_INITDB_ROOT_PASSWORD: example
  ports:
    - 27017:27017
  volumes:
    - /home/mongtest:/data/db

2、执行docker-compose up -d

[root@server02 ~]# docker-compose up -d
Creating network "root_default" with the default driver
Pulling mongo (mongo:)...
latest: Pulling from library/mongo
f22ccc0b8772: Pull complete
3cf8fb62ba5f: Pull complete
e80c964ece6a: Pull complete
329e632c35b3: Pull complete
3e1bd1325a3d: Pull complete
4aa6e3d64a4a: Pull complete
035bca87b778: Pull complete
874e4e43cb00: Pull complete
0e50e71d834e: Pull complete
27768a0d0c67: Pull complete
be4e0bd8b992: Pull complete
c887415d0643: Pull complete
Digest: sha256:7722bd2778a299b6f4a62b93a0d2741c734ba7332a090131030ca28261a9a198
Status: Downloaded newer image for mongo:latest
Creating root_mongo_1 ... done

3、启动数据库 docker exec -it ${进程名称,例如root_mongo_1} mongo

[root@server02 ~]# docker exec -it root_mongo_1 mongo
MongoDB shell version v4.4.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("70a345f7-4001-4b7c-bcd4-69b1c703e07f") }
MongoDB server version: 4.4.3
> 

第一次进入,执行
use admin //使用admin权限
user testdb //新建一个“表”
db.createUser({user:‘yyx01',pwd:‘123456',roles:[{role:‘dbOwner',db:‘testdb'}]}) //新建一个用户
show dbs //查看所有表
user testdb //切换到一个“表”
db.auth(‘yyx01',‘123456') //使用新建的用户操作新建的表
db.users.insertOne({name:‘yeyanxi',age:30,email:‘489448521@qq.com'}) //插入一条数据
db.users.find({}) //查询数据
db.users.updateOne({name:‘yeyanxi1'},{$set: {sex:‘man'}}) //修改数据
db.users.deleteOne({name:‘yeyanxi1'}) //删除数据

更多表的操作指令,可以查看官网:https://docs.mongodb.com/manual/crud/

4、使用GUI客户端(robo 3t),下载地址:https://robomongo.org/download
在本地可以连接到服务器上的数据库

如果有需要,可以备份数据库:docker exec -it root_mongo_1 mongodump -h localhost -u root -p example -o /tmp/test

docker cp ${进程id,例如acc79ae5b628}:/tmp/test /tmp/test

posted @ 2021-01-05 16:43  星火撩原  阅读(224)  评论(0编辑  收藏  举报