Skip to content

Implementing "Secure database" issue

Jesus Galaz Reyes requested to merge 15-secure-database into main

Summary of Steps for Dockerizing Application with MongoDB

1. Adjust docker-compose.yml for Database Security

  • Added MongoDB authentication by setting MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in the mongodb service.

  • Configured the application’s environment in todo-app service to use a connection string with MongoDB credentials, ensuring it connects with authentication.

  • Updated the MONGO_URI to include the username, password, and authSource=admin to ensure MongoDB authenticates against the admin database:

    environment:
      - MONGO_URI=mongodb://mongoAdmin:someRandomPassword123$@mongodb:27017/todo-app?authSource=admin

2. Created a .env File for Sensitive Information

  • Moved sensitive credentials out of docker-compose.yml into a .env file, making it easier to manage securely.

  • The .env file contains:

    MONGO_INITDB_ROOT_USERNAME=mongoAdmin
    MONGO_INITDB_ROOT_PASSWORD=someRandomPassword123$
    MONGO_URI=mongodb://mongoAdmin:someRandomPassword123$@mongodb:27017/todo-app?authSource=admin

3. Update mongodb.js to Use Environment Variables

  • Adapted mongodb.js to use process.env.MONGO_URI, ensuring credentials are securely managed through environment variables and not hard-coded.
  • This file establishes the connection to MongoDB when called in the main application file (server.js), making it a reusable module.

4. Start the Application in Detached Mode

  • To run the application in the background without displaying logs, we used:

    docker-compose --env-file .env up -d
  • Verified MongoDB access by connecting via mongosh, ensuring authentication with the credentials in .env.

5. Accessing MongoDB via mongosh

  • From the Host: Connected to MongoDB from the host system using the credentials and authSource:
    > mongosh "mongodb://localhost:27017" --username mongoAdmin --password someRandomPassword123$ --authenticationDatabase admin
  • From the MongoDB Container: Alternatively, accessed mongosh within the MongoDB container directly:
    > mongosh -u mongoAdmin -p someRandomPassword123$ --authenticationDatabase admin

Final Files

  • Dockerfile: No changes made; retained the existing setup for the application image.
  • docker-compose.yml: Updated to include MongoDB authentication and connection string adjustments for secure access.
  • mongodb.js: Used to handle the MongoDB connection logic and configured to read from environment variables.
  • .env: Contains sensitive MongoDB credentials and the connection string for secure and flexible configuration.

Closes #15 (closed)

Merge request reports

Loading