One, command installation
1. Check the available MongoDB version
Link: hub.docker.com-mongo .
Use the latest version this time: latest
can use the docker search mongo command to view the available images
2. Installation steps
(1) Pull the image
docker pull mongo:latest
(2) Run the container
//持久化加--volume /usr/local/mongodata:/data/db
docker run -itd --name mongodb -p 27017:27017 mongo --auth
-p 27017:27017 :映射容器服务的 27017 端口到宿主机的 27017 端口。外部可以直接通过 宿主机 ip:27017 访问到 mongo 的服务。
--auth:需要密码才能访问容器服务。
(3) Test after successful installation.
View running information by command docker ps
Use the following commands to add users and set passwords, and try to connect.
$ docker exec -it mongo mongo admin
//创建一个名为 admin,密码为 123456 的用户。
> db.createUser({
user:'admin',pwd:'123456',roles:[ {
role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
//尝试使用上面创建的用户信息进行连接。
> db.auth('admin', '123456')
(4) Install mongo-express
//拉取镜像
docker pull mongo-express:latest
//运行容器
docker run -itd --name mongo-express -p 8081:8081 --link mongodb:mongo --env ME_CONFIG_MONGODB_ADMINUSERNAME='admin' --e
nv ME_CONFIG_MONGODB_ADMINPASSWORD='123456' mongo-express
Two, yml installation
Create a new stack.yml file in the installation directory
# Use root/example as user/password credentials
version: '3.1'
services:
mongo:
image: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: example
Execute the command
docker stack deploy -c stack.yml mongo
(or docker-compose -f stack.yml up)
background execution: -d
Reference link: docker-hub