{"id":366123,"date":"2021-11-12T15:45:39","date_gmt":"2021-11-12T12:45:39","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/how-to-run-mongodb-in-a-docker-container-cloudsavvy-it\/"},"modified":"2021-11-12T15:45:39","modified_gmt":"2021-11-12T12:45:39","slug":"how-to-run-mongodb-in-a-docker-container-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/how-to-run-mongodb-in-a-docker-container-cloudsavvy-it\/","title":{"rendered":"#How to Run MongoDB in a Docker Container \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_84 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a2f20b9b8077\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a2f20b9b8077\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-run-mongodb-in-a-docker-container-cloudsavvy-it\/#Starting_a_MongoDB_Container\" >Starting a MongoDB Container<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-run-mongodb-in-a-docker-container-cloudsavvy-it\/#Connecting_From_Another_Container\" >Connecting From Another Container<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-run-mongodb-in-a-docker-container-cloudsavvy-it\/#Persisting_Data_With_Volumes\" >Persisting Data With Volumes<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-run-mongodb-in-a-docker-container-cloudsavvy-it\/#Adding_Authentication\" >Adding Authentication<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-run-mongodb-in-a-docker-container-cloudsavvy-it\/#Configuring_Your_Server\" >Configuring Your Server<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-run-mongodb-in-a-docker-container-cloudsavvy-it\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#How to Run MongoDB in a Docker Container \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"type:primaryImage aligncenter size-full wp-image-12810\" srcset=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/07\/f5932bc2.jpg?width=398&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1 400w, https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/07\/f5932bc2.jpg?width=1198&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1 1200w\" sizes=\"auto, 400w, 1200w\" src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/07\/f5932bc2.jpg?width=1198&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"Illustration showing the MongoDB logo\" width=\"1602\" height=\"902\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.mongodb.com\">MongoDB is<\/a> a document-oriented NoSQL database engine that\u2019s gained popularity with developers for its JSON-like storage model. MongoDB often provides a more direct m<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">app<\/a>ing between code and persisted data, facilitating rapid iteration and helping address the sizable impedance mismatch of traditional SQL databases.<\/p>\n<p>Docker is a platform that packages your application components as isolated containers. Containerizing your MongoDB database makes it portable across environments, letting you spin up an instance anywhere Docker is available.<\/p>\n<p>In this guide, we\u2019ll show you how to get started running MongoDB in Docker. The key consideration is data storage: Docker containers are ephemeral by default and lose their data when they stop. You\u2019ll need to mount a volume into your MongoDB container to enable persistence.<\/p>\n<h2 id=\"starting-a-mongodb-container\"><span class=\"ez-toc-section\" id=\"Starting_a_MongoDB_Container\"><\/span>Starting a MongoDB Container<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>You can start a throwaway MongoDB container with <code>docker run<\/code>:<\/p>\n<pre escaped=\"true\" lang=\"\">docker run -d -p 27017:27017 --name example-mongo mongo:latest<\/pre>\n<p>This will give you a live server running the latest version of MongoDB. It uses the official image available <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/hub.docker.com\/_\/mongo\">on Docker Hub<\/a>. The <code>-d<\/code> (detach) flag means the container will run in the background, separately to your shell process.<\/p>\n<p>The container port <code>27017<\/code>, the MongoDB default, is bound back to port <code>27017<\/code> on your host. You\u2019ll be able to connect to your Mongo instance on <code>localhost:27017<\/code>. If you want to change the port number, modify the first part of the <code>-p<\/code> flag, such as <code>9000:27017<\/code> to use <code>localhost:9000<\/code>.<\/p>\n<p>The MongoDB image also includes the <code>mongo<\/code> shell. The <code>docker exec<\/code> command provides a way to access it in a running container:<\/p>\n<pre escaped=\"true\" lang=\"\">docker exec -it example-mongo mongo<\/pre>\n<p>This will launch an interactive <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/docs.mongodb.com\/v4.4\/mongo\">Mongo shell session<\/a> in your terminal. It\u2019s ideal for quickly interacting with your database instance without adding any external dependencies.<\/p>\n<p>\u00a0<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-14794\" src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/11\/00bf23e1.png?trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"\" width=\"929\" height=\"404\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>You can inspect Mongo\u2019s logs with the <code>docker logs<\/code> command:<\/p>\n<pre escaped=\"true\" lang=\"\">docker logs example-mongo --follow<\/pre>\n<p>The <code>--follow<\/code> flag means logs will be continually streamed to your terminal.<\/p>\n<h2 id=\"connecting-from-another-container\"><span class=\"ez-toc-section\" id=\"Connecting_From_Another_Container\"><\/span>Connecting From Another Container<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>If you\u2019re deploying Mongo in Docker, chances are you\u2019ll be wanting to connect from another container such as your API server. It\u2019s best to join both to a shared Docker network. This means you won\u2019t need to publish Mongo ports to your host, reducing your attack surface.<\/p>\n<pre escaped=\"true\" lang=\"\">docker network create mongo-network&#13;\ndocker run -d --network mongo-network --name example-mongo mongo:latest<\/pre>\n<p>Your \u201cclient\u201d container should join to the <code>mongo-network<\/code> too. It\u2019ll be able to reference the container by name within MongoDB connection strings. In this example, it could reach the database by contacting <code>example-mongo:27017<\/code>.<\/p>\n<h2 id=\"persisting-data-with-volumes\"><span class=\"ez-toc-section\" id=\"Persisting_Data_With_Volumes\"><\/span>Persisting Data With Volumes<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>You must use Docker volumes if you\u2019ll be hosting a real database in your Mongo container. Using a volume persists your data so it\u2019s not lost when you stop the container or restart the Docker daemon.<\/p>\n<p>The MongoDB image is configured to store all its data in the <code>\/data\/db<\/code> directory in the container filesystem. Mounting a volume to this location will ensure data is persisted outside the container.<\/p>\n<pre escaped=\"true\" lang=\"\">docker run -d &#13;\n    -p 27017:27017 &#13;\n    --name example-mongo &#13;\n    -v mongo-data:\/data\/db &#13;\n    mongo:latest<\/pre>\n<p>This version of the <code>docker run<\/code> command creates a new Docker volume called <code>mongo-data<\/code> and mounts it into the container. The volume will be managed by Docker; you can see it by running <code>docker volumes ls<\/code>.<\/p>\n<p>Add some data to Mongo:<\/p>\n<pre escaped=\"true\" lang=\"\">use test-db&#13;\ndb.demos.save({foo: \"bar\"})<\/pre>\n<p>Next restart your container:<\/p>\n<pre escaped=\"true\" lang=\"\">docker restart example-mongo<\/pre>\n<p>The previously added data will remain intact as Docker reattaches the volume after the restart. You can check this by reconnecting to Mongo and querying the <code>demos<\/code> collection:<\/p>\n<pre escaped=\"true\" lang=\"\">use test-db&#13;\ndb.demos.find({foo: \"bar\"})<\/pre>\n<p>You can remove the container and run an entirely new one with the same <code>mongo-data<\/code> volume. As the volume\u2019s files will still exist on your host, Docker will mount them back into the replacement container. Mongo automatically skips its usual database initialization routine when the data directory is already populated at container startup.<\/p>\n<p>Volumes persist until you remove them with the <code>docker volumes rm<\/code> command or use the <code>--volumes<\/code> flag when destroying a container with <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/docs.docker.com\/engine\/reference\/commandline\/rm\"><code>docker rm<\/code><\/a>.<\/p>\n<h2 id=\"adding-authentication\"><span class=\"ez-toc-section\" id=\"Adding_Authentication\"><\/span>Adding Authentication<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Fresh MongoDB containers lack authentication so anyone can connect to your server. Don\u2019t expose the container\u2019s ports on a networked system that an attacker could access. Mongo\u2019s authentication system should be used to properly secure your database.<\/p>\n<p>The Mongo Docker image provides a convenient quickstart for Mongo\u2019s relatively complex <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/docs.mongodb.com\/manual\/reference\/program\/mongod\/#cmdoption-mongod-auth\">authentication system<\/a>. You can add an initial user account by setting the <code>MONGO_INITDB_ROOT_USERNAME<\/code> and <code>MONGODB_INITDB_ROOT_PASSWORD<\/code> environment variables when you create your container:<\/p>\n<pre escaped=\"true\" lang=\"\">docker run -d &#13;\n    -p 27017:27017 &#13;\n    --name example-mongo &#13;\n    -v mongo-data:\/data\/db &#13;\n    -e MONGODB_INITDB_ROOT_USERNAME=example-user &#13;\n    -e MONGODB_INITDB_ROOT_PASSWORD=example-pass &#13;\n    mongo:latest<\/pre>\n<p>This will start the database with a new user account called <code>example-user<\/code>. The user will be assigned the <code>root<\/code> role in the <code>admin<\/code> authentication database, granting superuser privileges.<\/p>\n<p>Considering the powers associated with this account, providing its password as a plain-text environment variable can be problematic. A more secure approach is to inject the password as a file:<\/p>\n<pre escaped=\"true\" lang=\"\">docker run -d &#13;\n    -p 27017:27017 &#13;\n    --name example-mongo &#13;\n    -v mongo-data:\/data\/db &#13;\n    -e MONGODB_INITDB_ROOT_USERNAME=example-user &#13;\n    -e MONGODB_INITDB_ROOT_PASSWORD_FILE=\/run\/secrets\/mongo-root-pw &#13;\n    mongo:latest<\/pre>\n<p>Suffixing the image\u2019s environment variables with <code>_FILE<\/code> instructs Mongo to read the contents of the referenced file, instead of using the value as-is. The actual file path is arbitrary \u2013 either mount a file from your host machine or use Docker Secrets. Either way, your password won\u2019t be visible when using <code>docker inspect<\/code> to view the container\u2019s variables.<\/p>\n<h2 id=\"configuring-your-server\"><span class=\"ez-toc-section\" id=\"Configuring_Your_Server\"><\/span>Configuring Your Server<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The easiest way to supply custom Mongo config values is to use the flags offered by <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/docs.mongodb.com\/manual\/reference\/program\/mongod\/#core-options\">the <code>mongod<\/code> binary<\/a>. The Docker image is preconfigured to pass its <code>docker run<\/code> flags through to <code>mongod<\/code>.<\/p>\n<p>Here\u2019s an example where Mongo is <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/docs.mongodb.com\/manual\/reference\/program\/mongod\/#std-option-mongod.--port\">set to listen on<\/a> port 9000 instead of the default 27017:<\/p>\n<pre escaped=\"true\" lang=\"\">docker run -d &#13;\n    --name example-mongo &#13;\n    -v mongo-data:\/data\/db &#13;\n    mongo:latest --port 9000<\/pre>\n<p>You can add a Mongo config file by mounting one into your container, then using the <code>--config<\/code> flag to tell Mongo where to look:<\/p>\n<pre escaped=\"true\" lang=\"\">docker run -d &#13;\n    --name example-mongo &#13;\n    -v mongo-data:\/data\/db &#13;\n    -v .\/mongo.conf:\/etc\/mongo\/mongo.conf&#13;\n    mongo:latest --config \/etc\/mongo\/mongo.conf<\/pre>\n<p>The <code>--config<\/code> flag must be used \u2013 Mongo doesn\u2019t load settings from any file path by default.<\/p>\n<p>The Docker image provides a mechanism to seed your database and run bootstrap scripts on first run. Any <code>.sh<\/code> or <code>.js<\/code> files placed in the <code>\/docker-entrypoint-initdb.d<\/code> directory will be executed in alphabetical order. <code>.js<\/code> files will be treated as Mongo scripts and run against the <code>test<\/code> database. You can change this default database by setting the <code>MONGODB_INITDB_DATABASE<\/code> environment variable to a custom schema name.<\/p>\n<h2 id=\"conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Running MongoDB in Docker gives you isolation and portability for your database. You can quickly spin up new instances without manually installing the Mongo server. Your application containers can link directly to Mongo over a shared Docker network.<\/p>\n<p>The Mongo image on Docker Hub has <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/hub.docker.com\/_\/mongo?tab=tags\">tags for<\/a> all actively supported versions including 4.4 and 5.0. The <code>latest<\/code> tag always points to the newest release, currently <code>5.0<\/code>, so using it puts you at risk of receiving unwanted major version bumps. It\u2019s safer to indicate a specific version when starting your containers.<\/p>\n<p>The official image can also be used as the base for custom preconfigured ones. Building a <code>Dockerfile<\/code> that adds your config file, overrides the <code>COMMAND<\/code> to include it, and copies in your seeding scripts would give you a way to bring up a new database instance with fewer <code>docker run<\/code> flags.\n<\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/14792\/how-to-run-mongodb-in-a-docker-container\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#How to Run MongoDB in a Docker Container \u2013 CloudSavvy IT&#8221; MongoDB is a document-oriented NoSQL database engine that\u2019s gained popularity with developers for its JSON-like storage model. MongoDB often provides a more direct mapping between code and persisted data, facilitating rapid iteration and helping address the sizable impedance mismatch of traditional SQL databases. Docker&#8230;<\/p>\n","protected":false},"author":1,"featured_media":366124,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/07\/f5932bc2.jpg","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-366123","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/366123","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=366123"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/366123\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/366124"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=366123"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=366123"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=366123"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}