Skip to main content

·

Deploying MongoDB with Docker on DigitalOcean (Part 1: Standalone)

PREFACE

Hello everyone! It's been a while, and here we are again, approaching the end of the year. Today, I'm returning to my usual content: sharing knowledge and experience from my professional journey.
For those who are new here, my articles generally cover topics related to Backend, Blockchain, and DevOps. Through sharing knowledge with the community, I hope to receive feedback that helps me improve my skills and deepen my expertise in the vast field of Information Technology.
After struggling for a while to get MongoDB running with Docker, I've decided to start this series to share what I've learned and help others understand the underlying principles. My goal is to make it easier for you to deploy databases on VPS instances hosted by DigitalOcean for your own projects.
This series will consist of two parts:
  • Part 1 (Standalone): A straightforward guide to setting up a standalone MongoDB database.
  • Part 2 (Replica Set): Coming soon! This part will cover configuring a MongoDB cluster to support data backup and improved system availability.

INTRODUCTION

MongoDB

MongoDB is a popular and widely adopted database belonging to the NoSQL family. It offers several notable features that make it easy for developers to get started, deploy applications, and scale their systems quickly and efficiently.
  • Flexibility: A flexible data structure that doesn't require a rigid schema to define all fields in advance.
  • Scalability: Supports horizontal scaling.
  • Querying: Offers efficient querying without requiring developers to manage as many rigid relationships as in traditional relational databases. Performance can also be improved through caching and appropriate indexing.
  • Indexing: Supports various indexing strategies to accommodate different query patterns and use cases.

Docker

A Docker container is an isolated, consistent environment for running an application along with all its required dependencies and configurations.
Imagine a large ZIP file containing everything needed to run your application on different operating systems and hardware. Docker provides the tools to package and run these containers.
From this, we can see several significant benefits of using Docker:
  • Consistency: Containerization helps ensure that everyone on your team uses the same configurations and runtime environment. It also significantly reduces deployment issues by making the production environment more consistent with staging.
  • Lightweight: Docker containers start quickly and generally consume fewer resources than virtual machines.
  • Ephemeral: Changes to a container's writable filesystem are discarded when the container is removed. This makes it easier to maintain a clean environment whenever an application is redeployed. Persistent data, however, should be stored in volumes or other external storage.

Running MongoDB in a Docker Container

If we think of a Docker container as an ordinary VPS, we can deploy virtually any service or application inside it—and MongoDB is no exception.
We can use existing MongoDB base images from Docker Hub, maintained by the community, or customize our own image with specific configurations.
In this tutorial, we'll deploy a Docker container based on the official MongoDB image and configure it using a file called docker-compose.yaml.

TUTORIAL

Step 1: Create the Setup Directory on Your VPS

The directory structure will look something like this:
  • /data: An empty directory used to mount database data from the Docker container to the VPS host, helping preserve data when the container is restarted or recreated.
  • /log: A directory for storing logs outside the Docker container.
  • /config: A directory containing the MongoDB configuration file.
    • mongod.conf: The MongoDB configuration file.
  • docker-compose.yaml: The Docker Compose configuration file used to define and run the MongoDB container.

Step 2: Configure MongoDB

By default, the MongoDB configuration file is typically located at /etc/mongod.conf in a standard MongoDB installation.
We'll create our own mongod.conf file and mount it into the Docker container, modifying several settings from the defaults:
  • Enable authorization: Strengthen database security by requiring authentication.
  • Configure the listening IP address: Set bindIp to 0.0.0.0 instead of 127.0.0.1 to allow connections through the container's network interface. External access must still be controlled through firewall rules and network security policies.
# mongod.conf # For documentation of all options, see: # http://docs.mongodb.org/manual/reference/configuration-options/ # Where to write logging data. systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log # Where and how to store data. storage: dbPath: /data/db journal: enabled: true # engine: # wiredTiger: # How the process runs. processManagement: # fork: true # pidFilePath: /var/run/mongodb/mongod.pid timeZoneInfo: /usr/share/zoneinfo # Network interfaces. net: port: 27017 bindIp: 0.0.0.0 security: authorization: enabled # keyFile: /etc/secret.kf # operationProfiling: # replication: # replSetName: "marketplace_nft" # sharding: ## Enterprise-Only Options # auditLog: # snmp:
Security note: Binding to 0.0.0.0 allows MongoDB to listen on all available IPv4 interfaces inside the container. It does not, by itself, make the database safely accessible from the internet. Avoid exposing MongoDB publicly without appropriate network restrictions, strong authentication, and secure credential management.

Step 3: Configure docker-compose.yaml

Before starting the container, we need to mount the necessary configuration files, data directories, and log storage. Docker Compose allows us to define these settings in a single configuration file.
version: "3.9" services: mongodb: image: mongo:5.0.6 container_name: gateway_MBCtest_DB ports: - "27016:27017" volumes: - "./config/mongod.conf:/data/configdb/mongod.conf:ro" - "./data:/data/db" - "log:/var/log/mongodb" command: ["/usr/bin/mongod", "-f", "/data/configdb/mongod.conf"] restart: always volumes: log: null
Here are the key parameters in the Docker Compose configuration:
  • image: Specifies the base image used to create the container.
  • container_name: Sets the container's name.
  • ports: Maps a port on the host to a port inside the container. In this example, host port 27016 maps to container port 27017. Using a non-default port alone does not provide meaningful security.
  • volumes: Mounts data and configuration between the VPS and the container.
  • command: Specifies the command executed when the container starts.
  • restart: Configures the container to restart automatically if it stops unexpectedly, improving recovery from certain failures.

Step 4: Build and Start the Docker Container

Run the following command to create and start the MongoDB container using the configuration we've prepared:
docker-compose up -d --build --force-recreate

Step 5: Check Whether the Container Is Running

docker ps
This command lists running containers so you can verify that MongoDB has started successfully.

Step 6: Execute a Shell Inside the Container

docker exec -it container_id bash
Replace container_id with the actual container ID or use the container name.

Step 7: Set Up the Database

First, connect to the MongoDB shell:
mongo
Switch to the admin database:
use admin
Create an administrative user:
db.createUser({ user: "superadmin", pwd: "REPLACE_WITH_A_STRONG_ADMIN_PASSWORD", roles: [ { role: "root", db: "admin" } ] })
Next, create an application user with read and write permissions for the database_test database:
db.createUser({ user: "app_user", pwd: "REPLACE_WITH_A_STRONG_APPLICATION_PASSWORD", roles: [ { role: "readWrite", db: "database_test" } ] })
Important: Replace the example passwords with strong, unique credentials. Never publish real database credentials in a public article or commit them to a source code repository. If any credentials shown in an existing public article are real, rotate them immediately.

Step 8: Configure the VPS Firewall

The original setup uses the following command to open port 27016:
sudo ufw allow 27016
However, opening this port to everyone can expose your database to unauthorized access. A safer approach is to restrict access to a trusted IP address:
sudo ufw allow from YOUR_TRUSTED_IP to any port 27016 proto tcp
Replace YOUR_TRUSTED_IP with the public IP address of the machine that needs database access.
For production environments, consider keeping MongoDB on a private network or connecting through a VPN or SSH tunnel instead of exposing it directly to the public internet.

Step 9: Connect to MongoDB Using a Connection URI

Once everything is configured, you can connect to MongoDB using a connection URI like the following:
mongodb://app_user:YOUR_APPLICATION_PASSWORD@VPS_IP:27016/database_test?authSource=admin
Replace the username, password, and VPS_IP with your actual connection details.
The authSource=admin parameter tells MongoDB to authenticate the application user against the admin database, where the user was created.

Step 10: Leave a Like and Follow! ^^

CONCLUSION

This article has introduced the essential concepts and steps for running MongoDB inside a Docker container.
Here's a quick summary of what we've covered:
  • Core concepts: MongoDB and Docker.
  • Deployment: A step-by-step tutorial for setting up MongoDB on a VPS using Docker Compose.
  • Practical experience: Personal insights and lessons incorporated throughout the tutorial.
I hope this article has been helpful, and I'd love to hear your feedback and suggestions.
See you in Part 2: Replica Set, where we'll explore how to configure a MongoDB replica set in a future article.
:))

Subscribe to the newsletter

Get new posts on Backend, Blockchain, DevOps, and life notes.

Loading Comments...