Docker Mastery

Build Apps That Deploy Anywhere

Setting Up MongoDB Atlas for Container Deployment

Why Use MongoDB Atlas Instead of a Container?

When deploying applications, we'll containerize our web applications but not our database. Here's why:

Databases are stateful - they store persistent data that needs to survive container restarts and deployments. Containerizing a database requires setting up persistent storage, backups, and complex configuration that's difficult to manage.

MongoDB Atlas is easier - It's a managed database service that handles all the complexity for us (hosting, backups, scaling, maintenance).

The Goal

We need to create a MongoDB database that our containerized applications can connect to. By the end of this setup, we'll have a connection URL that our applications will use to access the database.

Step-by-Step Setup

1. Create MongoDB Atlas Account

  1. Go to https://www.mongodb.com/atlas
  2. Sign up for an account
  3. Complete the registration process

2. Create a New Project

  1. Once logged in, create a new project or use the default one (should be named something like Project 0)
  2. Give it a name (e.g., "My App Project")

3. Create a Free Database Cluster

  1. Select the option to create a "Database" cluster.
  2. Choose the FREE tier (M0 Sandbox)
  3. The free tier is generous and allows up to 25 MB of storage.
  4. Select a cloud provider (i.e aws) and region (choose one closest to you)
  5. Name your cluster (e.g., "Cluster0")
  6. Click "Create"

4. Create Database User

  1. You'll be prompted to create a database user
  2. Choose "Username and Password"
  3. Create a username (e.g., "appuser")
  4. Create a strong password and save it somewhere safe
  5. Click "Create User"

5. Get Your Connection String

  1. Click "Connect" on your cluster
  2. Select "Drivers"
  3. Choose any programming language/driver (doesn't matter)
  4. Copy the connection string

It will look like:

mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/?retryWrites=true&w=majority

6. Configure Network Access

  1. On the left sidebar, click on Network Access (Under Security)
  2. Click add IP address and enter 0.0.0.0/0 to the access list entry (allows database access from any IP address)
  3. Click confirm to add the entry
  4. Click "Finish and Close"

7. Complete Your Connection URL

Replace the placeholders in your connection string if not already filled in:

  • <username> → your database username
  • <password> → your database password

Final result:

mongodb+srv://appuser:[email protected]/?retryWrites=true&w=majority&appName=Cluster0

8. Verify

Please make sure you have completed every step before proceeding.

You're Done!

Save this connection URL - this is what your containerized applications will use to connect to MongoDB. Your database is now ready to receive connections from your deployed containers.