docker 运行 mongodb

1、准备工作:安装docker

2、docker 安装 mongodb

docker pull mongo
docker run -itd --name mongo -p 27017:27017 mongo --auth

–auth:需要密码才能访问容器服务。

$ docker exec -it mongo mongo admin
# 创建一个名为 admin,密码为 123456 的用户。
>  db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'}]});
# 尝试使用上面创建的用户信息进行连接。
> db.auth('admin', '123456')
# 指定某表管理员
> db.createUser({user:'user',pwd:'123456',roles:[{role:'readWrite',db:'mydb'}]});
# 所有表只读
> db.createUser({user:'user',pwd:'123456',roles:['read']});

3、mongo-express

docker run -it --name mongo-express --link mongo -d -p 8081:8081 -e ME_CONFIG_OPTIONS_EDITORTHEME="3024-night" -e ME_CONFIG_BASICAUTH_USERNAME="mongoexpress" -e ME_CONFIG_BASICAUTH_PASSWORD="mongoexpress" -e ME_CONFIG_MONGODB_ADMINUSERNAME="mongoadmin" -e ME_CONFIG_MONGODB_ADMINPASSWORD="mongoadmin" mongo-express

docker network ls 可以查看当前所有的 Docker NETWORK

4、Docker Compose 实现

创建文件 stack.yml

version: '3.1'

services:

  mongo:
    image: mongo:4.1.6
    ports:
      - 27017:27017
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: mongoadmin
      MONGO_INITDB_ROOT_PASSWORD: mongoadmin

  mongo-express:
    links:
      - mongo
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_OPTIONS_EDITORTHEME: 3024-night
      ME_CONFIG_BASICAUTH_USERNAME: mongoexpress
      ME_CONFIG_BASICAUTH_PASSWORD: mongoexpress
      ME_CONFIG_MONGODB_ADMINUSERNAME: mongoadmin
      ME_CONFIG_MONGODB_ADMINPASSWORD: mongoadmin
docker-compose -f stack.yml up

全文中涉及到的用户名、密码、版本视实际情况修改。
更多使用说明:https://hub.docker.com/_/mongo