Implementing "Secure database" issue
Summary of Steps for Dockerizing Application with MongoDB
docker-compose.yml
for Database Security
1. Adjust -
Added MongoDB authentication by setting
MONGO_INITDB_ROOT_USERNAME
andMONGO_INITDB_ROOT_PASSWORD
in themongodb
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, andauthSource=admin
to ensure MongoDB authenticates against theadmin
database:environment: - MONGO_URI=mongodb://mongoAdmin:someRandomPassword123$@mongodb:27017/todo-app?authSource=admin
.env
File for Sensitive Information
2. Created a -
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
mongodb.js
to Use Environment Variables
3. Update - Adapted
mongodb.js
to 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
.
mongosh
5. Accessing MongoDB via -
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)