Problem Description
The challenge was to develop an application using NestJS that connects to a MongoDB database. The task required configuring the development and production environments using Docker and Docker Compose, ensuring communication between services and the proper handling of environment variables.
Implemented Solution
I implemented the solution as follows:
-
- Containerization: A
Dockerfile
was created to build the NestJS application image, and adocker-compose.yaml
file was defined to orchestrate the solution.
- Containerization: A
-
- Database: An official MongoDB image was used, pulled from DockerHub, for the database container, which listens on port
27017
. Additionally, a volume is assigned for data persistence.
- Database: An official MongoDB image was used, pulled from DockerHub, for the database container, which listens on port
-
- Container Connection: The containers (the NestJS one, named “app”, and the MongoDB one, named “db”) are connected via a Docker network. The application connects to MongoDB on port
27017
using the username “root” and the password “password”.
- Container Connection: The containers (the NestJS one, named “app”, and the MongoDB one, named “db”) are connected via a Docker network. The application connects to MongoDB on port
-
- Connection Verification: Within the NestJS application, a call was made to MongoDB to check the connection, the result of which is reflected when accessing
http://localhost:3000
.
- Connection Verification: Within the NestJS application, a call was made to MongoDB to check the connection, the result of which is reflected when accessing
How to Use It
-
- Verify that you have Docker and Docker Compose installed.
-
- Navigate to the folder containing the
docker-compose.yaml
file.
- Navigate to the folder containing the
-
- Run the following command to build and start the containers in detached mode:Bash
docker compose up -d --build
- Run the following command to build and start the containers in detached mode:Bash
-
- The application is exposed on port 3000 (mapped from the container to the host), so you can access it at:
http://localhost:3000
- The application is exposed on port 3000 (mapped from the container to the host), so you can access it at:
-
- To check the logs and confirm the connection to MongoDB, you can run:Bash
docker compose logs app
- To check the logs and confirm the connection to MongoDB, you can run:Bash
Evidence
Application Logs:

Browser Results

Terminal

Diagram

Conclusion
This solution allows the NestJS application to connect to MongoDB using Docker containers that communicate over a defined network. The port mapping (3000
for the application and 27017
for MongoDB), along with the use of volumes for data persistence, ensures an isolated and scalable development environment that is ready for production.