使用Docker-Compose安装MongoDB
安装Docker-Compose
Compose 安装
Linux 上我们可以从 Github 上下载它的二进制包来使用,最新发行的版本地址:https://github.com/docker/compose/releases。
运行以下命令以下载 Docker Compose 的当前稳定版本:
$ sudo curl -L "https://github.com/docker/compose/releases/download/v2.2.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
要安装其他版本的 Compose,请替换 v2.2.2。
Docker Compose 存放在 GitHub,不太稳定。
你可以也通过执行下面的命令,高速安装 Docker Compose。
curl -L https://get.daocloud.io/docker/compose/releases/download/v2.4.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
将可执行权限应用于二进制文件:
$ sudo chmod +x /usr/local/bin/docker-compose
创建软链:
$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
测试是否安装成功:
$ docker-compose version
cker-compose version 1.24.1, build 4667896b
配置MongoDB的目录和文件。
新建MongoDB目录,子目录database和docker-compose.yml.
docker-compose.yml内容如下:
version: "3"
services:
mongodb:
image: mongo
container_name: mongodb
restart: always
ports:
- 27017:27017
volumes:
- ./data:/data/db
command: --wiredTigerCacheSizeGB 4 --auth # 限制内存大小, 需要认证
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=admin
mongo-express:
image: mongo-express
container_name: mongo-express
restart: always
ports:
- 8081:8081
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
- ME_CONFIG_MONGODB_ADMINPASSWORD=admin
- ME_CONFIG_MONGODB_SERVER=mongodb
networks:
default:
name: mongodb_network
启动docker-compose,运行MongoDB
[root@instance-1 MongoDB]# docker-compose up -d
Creating network "mongodb_network" with the default driver
Creating mongodb ... done
Creating mongo-express ... done
进入MongoDB容器, 进入MongoDB shell
docker exec -it mongodb bash
mongo mongodb://localhost:27017 -u admin -p admin
然后查看数据库
> show dbs;
admin 0.000GB
config 0.000GB
local 0.000GB
切换到admin的数据库,新建用户
> use admin
switched to db admin
> db.createUser({user:"root",pwd:"root",roles:[{role:'root',db:'admin'}]})
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
>
关闭数据库
[root@instance-1 MongoDB]# docker-compose down
Stopping mongo-express ... done
Stopping mongodb ... done
Removing mongo-express ... done
Removing mongodb ... done
Removing network mongodb_network