Deploying a NestJS & MongoDB App with Docker

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 a docker-compose.yaml file was defined to orchestrate the solution.

      • 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.

      • 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”.

      • 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.

    How to Use It

        1. Verify that you have Docker and Docker Compose installed.

        1. Navigate to the folder containing the docker-compose.yaml file.

        1. Run the following command to build and start the containers in detached mode:Bashdocker compose up -d --build

        1. The application is exposed on port 3000 (mapped from the container to the host), so you can access it at: http://localhost:3000

        1. To check the logs and confirm the connection to MongoDB, you can run:Bashdocker compose logs app

      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.

      Scroll al inicio