1. 配置docker-compose.yml
# 該Yaml文件改編自DockerHub中的配置文件 version: '3.8' services: mongo: image: mongo:4.4.0 #根據需要選擇自己的鏡像 restart: always ports: - 27017:27017 #對外暴露停供服務的端口,正式生產的時候理論不用暴露。 volumes: - /docker/mongodb/data/db:/data/db # 掛載數據目錄 - /docker/mongodb/data/log:/var/log/mongodb # 掛載日志目錄 - /docker/mongodb/data/config:/etc/mongo # 掛載配置目錄 # command: --config /docker/mongodb/mongod.conf # 配置文件
2. 創建配置文件
# mongod.conf # for documentation of all options, see: # http://docs.mongodb.org/manual/reference/configuration-options/ # Where and how to store data. storage: dbPath: /data/db journal: enabled: true directoryPerDB: true engine: wiredTiger wiredTiger: engineConfig: cacheSizeGB: 8 directoryForIndexes: true # where to write logging data. systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log # network interfaces net: port: 27017 bindIp: 0.0.0.0 # how the process runs processManagement: timeZoneInfo: /usr/share/zoneinfo #replication: replication: oplogSizeMB: 51200 replSetName: rs0
3. 運行mongodb
docker-compose -f docker-compose.yml up -d
4. 進入mongodb
docker exec -it mongo /bin/bash
5. 添加用戶
mongo use admin db.createUser({user:"root",pwd:"root",roles:[{role:'root',db:'admin'}]}) exit exit