MongoDB on AWS EC2 - Step-by-Step Guide

A beginner-friendly guide to setting up MongoDB on an AWS EC2 instance.

Introduction

MongoDB is a widely used NoSQL database known for its flexibility, scalability, and ease of use. This guide is designed for beginners looking to set up their own MongoDB database on an AWS EC2 instance in simple and clear steps.

Prerequisites
  • MongoDB Compass (Free Software)
  • PuTTY (For SSH Connection)
  • AWS Account
Setting Up Your EC2 Instance

Amazon Elastic Compute Cloud (EC2) is a cloud-based service that provides resizable computing power, allowing users to deploy and manage virtual machines easily. It is widely used for hosting applications, running development environments, and managing databases. In this guide, we will set up an EC2 instance running Ubuntu 22.04 LTS. Ubuntu is a popular choice for cloud servers due to its stability, security, and strong community support. Specifically, for MongoDB, Ubuntu provides official repositories, making installation and maintenance straightforward. Additionally, its compatibility with modern cloud environments ensures optimal performance and security updates.

Note: The instance configuration in this guide is selected to remain within the AWS Free Tier. If your application requires more storage capacity or higher computational power, consider exploring other instance types and storage options to better suit your needs.

Let's proceed with launching our EC2 instance and configuring it for MongoDB deployment.

Steps:

  1. Log into AWS and go to the EC2 dashboard.
  2. Click on Launch Instances.
  3. Choose a name and select Ubuntu 22.04 LTS (Free Tier Eligible).
  4. launch-instance_os
  5. Select t3.micro as the instance type.
  6. instance_type
  7. Create a new key pair (use ED25519 for better security).

  8. Note: A key pair is a set of cryptographic keys used for secure authentication when connecting to your EC2 instance via SSH. AWS uses public-key cryptography, where:
    • The public key is stored on the EC2 instance.
    • The private key remains on your local machine and is required for authentication.
    We choose ED25519 over traditional RSA keys because:
    • It provides stronger security with a shorter key length.
    • It is faster in key generation and authentication.
    • It offers better resistance to brute-force attacks.
    However, ED25519 keys are not supported on all older systems, particularly some legacy SSH clients and embedded devices. If you anticipate compatibility issues, you may opt for an RSA (4096-bit) key instead.

  9. Choose .ppk format for PuTTY.
  10. key-pair
  11. Allow SSH access from your public IP.

  12. For security reasons, configure SSH access to allow connections only from your public IP address.

    Note: When setting up SSH access, it is crucial to allow connections only from your public IP rather than opening access to all traffic (0.0.0.0/0). This helps prevent unauthorized access and significantly reduces the risk of brute-force attacks.

    If SSH access is open to all, anyone on the internet can attempt to connect, making your instance vulnerable to security threats. Restricting access to your **specific public IP** ensures that only you (or trusted users) can connect.

    Later, in security groups, we can add additional rules if needed to allow access from other trusted sources. However, always consider security best practices, such as:
    • Creating stricter security group rules to limit access.
    • Modifying the MongoDB configuration file to restrict database connections to specific IPs.
    Implementing these precautions helps safeguard your EC2 instance and its services from unauthorized access.

    network-settings
  13. Launch the instance and wait for status to show checks passed - your instance is now ready for MonogDB installation.
Connecting to EC2 Using PuTTY

To securely connect to your EC2 instance, we use PuTTY, a popular SSH client for Windows that allows secure remote access to Linux servers.

What is PuTTY? PuTTY is a free, open-source SSH client that enables users to remotely access Linux servers from Windows. Since Windows does not include a built-in SSH client with key authentication support in older versions, PuTTY provides an easy way to establish a secure connection.

Follow these steps to establish an SSH connection:

  1. Open PuTTY.
  2. Enter the Public IPv4 of your EC2 instance.
    Each EC2 instance is assigned a unique public IP address, which is required to connect to it over the internet.
    Where to find it? In the AWS EC2 dashboard, select your instance and check the "Public IPv4 Address" field.

  3. putty

  4. Go to Connection → SSH → Auth → Credentials and add your .ppk private key.
    AWS uses public-key authentication, meaning you must use the private key (.ppk file) that corresponds to the public key associated with your instance.
    Why this step? Without this, PuTTY cannot authenticate you, and the SSH connection will fail.

  5. putty_connection

  6. Click Open.
    This initiates the SSH connection to your EC2 instance. If all settings are correct, a terminal window will appear.
  7. When prompted, type ubuntu as the login username.
    The default username for an Ubuntu-based EC2 instance is ubuntu. This grants you access to the server with SSH privileges.
    Note: If you’re using a different Linux distribution (e.g., Amazon Linux), the default username may be different (e.g., ec2-user).
Downloading & Configuring MongoDB

Installation Steps:

Copy and pase the following commands into the PuTTY terminal (make sure you are connected to the EC2 instance).

  1. Update the system - this ensures that the system is up to date before installing new software.
    sudo apt update && sudo apt upgrade -y


  2. Import the MongoDB GPG key - required to verify MongoDB packages before installation.
    curl -fsSL https://pgp.mongodb.com/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg


  3. Add the official MongoDB repository - ensures that MongoDB packages are fetched from the official source.
    echo "deb [signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list


  4. Install MongoDB - downloads and installs the MongoDB package.
    sudo apt update && sudo apt install -y mongodb-org


  5. Enable and start the MongoDB service:

    sudo systemctl enable mongod && sudo systemctl start mongod


  6. Edit the MongoDB configuration file - launches the text editor to modify the configuration file.
    sudo nano /etc/mongod.conf


  7. Inside the text editor, modify the bindIp and security setting:

    bindIp: 0.0.0.0 
    security:
    authorization: enabled


  8. Restart MongoDB to apply changes:

    sudo systemctl restart mongod


Creating an Admin User in MongoDB

After enabling authentication in MongoDB, you need to create an administrative user to manage database access.

Follow these steps:

  1. Open the MongoDB shell:

    mongosh

  2. Switch to the admin database:

    use admin

  3. Create a new admin user:

    db.createUser({
                                    user: "admin",
                                    pwd: "securepassword",
                                    roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
                                })

  4. Explanation of roles:
    • userAdminAnyDatabase: Grants the user permission to manage users and roles on any database.
    • db: "admin": Specifies that the user is created in the admin database.
  5. Exit the MongoDB shell:

    exit

Security Considerations:
- Use a strong password instead of securepassword.
- Do not expose MongoDB to the public internet without additional security measures.
- For production environments, consider using **role-based access control (RBAC)** to limit user permissions.
- If remote access is required, configure **IP restrictions** in MongoDB and AWS security groups.
Connecting via MongoDB Compass

MongoDB Compass is a graphical interface that allows you to visually interact with your MongoDB database. It provides an easy way to explore your collections, run queries, and manage your data.

Follow these steps to connect:

  1. Download and install MongoDB Compass:

    If you haven’t already, download it from the official website: MongoDB Compass Download.
  2. Open MongoDB Compass.

    Once installed, launch MongoDB Compass to establish a connection.
  3. Enter the connection string:

    mongodb://admin:securepassword@EC2_Public_IP:27017

    Replace EC2_Public_IP with your actual EC2 instance’s public IP address.
  4. Click Connect.

    If the credentials and IP settings are correct, MongoDB Compass will establish a connection to your database.

Security Considerations:
- Never expose MongoDB to the public internet without strict firewall rules or IP whitelisting.
- Replace securepassword with a strong, unique password.
- For production environments, consider setting up **TLS encryption** and **role-based access control (RBAC)** to limit database access.

Next Steps

Now that you’re connected, you can start creating databases and collections. Refer to the official MongoDB documentation for best practices on structuring your data efficiently:

MongoDB Official Documentation