For faster application development and delivery, Docker can be a good choice. MongoDB image has been available in the Docker registry. You can run MongoDB in Docker container then connect your application or service to it. To make the MongoDB service becomes available in the container's network and its data can be persisted, there are several steps for configuration.
1. Create named volumes for MongoDB data and a configuration file, then create a network for containers in your application system. For example, the volumes are my-mongo-data
and my-mongo-config
, and the network is named my-net
.
docker volume create my-mongo-data
docker volume create my-mongo-config
docker network create my-net
2. As mentioned in MongoDB for Docker' site, database data is stored in the /data/db
directory in the container. MongoDB for Docker also accepts environment variables for setting up initial username and password for root user which are named MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
. To make the service can be simply accessible, in this case, the network alias is set to my-mongodb
.
docker run -it -d --rm --network my-net -v my-mongodb-data:/data/db -v my-mongodb-config:/data/configdb -p 27017:27017 --network-alias my-mongodb --name my-mongodb -e MONGO_INITDB_ROOT_USERNAME=luki -e MONGO_INITDB_ROOT_PASSWORD=qwerty mongo
3. For setting up MongoDB connection string, we take sample parameters from the previous step, then it becomes as follows.
mongodb://luki:qwerty@my-mongodb:27017/?authMechanism=DEFAULT&authSource=admin
4. You can run your main application with additional environment variables. For example, we set MONGO_CONNECTION_STRING
as MongoDB connection parameter and MONGO_DB
as database name of the main application, in this sample its name is appDb
.
docker run -it -d --rm --network my-net --network-alias app --name app -p 3000:5000 -e MONGO_CONNECTION_STRING=mongodb://luki:qwerty@mna-mongodb:27017/?authMechanism=DEFAULT"&"authSource=admin -e MONGO_DB=appDb your-app-image
Comments
Post a Comment