Implementing "Secure database" issue
Summary of Steps for Dockerizing Application with MongoDB
1. Adjust docker-compose.yml for Database Security
-
Added MongoDB authentication by setting
MONGO_INITDB_ROOT_USERNAMEandMONGO_INITDB_ROOT_PASSWORDin themongodbservice. -
Configured the application’s environment in
todo-appservice to use a connection string with MongoDB credentials, ensuring it connects with authentication. -
Updated the
MONGO_URIto include the username, password, andauthSource=adminto ensure MongoDB authenticates against theadmindatabase: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.ymlinto a.envfile, making it easier to manage securely. -
The
.envfile 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.jsto useprocess.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
mongoshwithin 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)