Docker containerization
The benefits of using Docker: flexible, lightweight, portable, loosely coupled.
They can be built locally to the cloud and run anywhere, and finally containers are loosely coupled, which means containers are highly self-sufficient and encapsulated. This allows us to replace or upgrade containers without disrupting any other containers. Essentially, a container is just a running process with some additional encapsulation features applied. This helps keep containers isolated from the host and other containers.
Docker compose: is a tool for defining and running multiple container docker applications, through docker compose we can use yaml files to configure our application services.
Configure MongoDB
Use the Docker Compose tool and its YAML configuration to set up everything you need.
Create a docker-compose.yml file in the root directory. Spacing/indentation/dashes in YAML all matter. The most important thing in the file is the db service, the Docker image using ‘Mongo’.
A Docker image is a multi-layered file that will execute code in our docker container. In this case, it will create a Mongo database.
1
2
3
4
5
6
7
8
9
10version: "3"
services:
db:
image: mongo
restart: always
environment:
- MONGODB_DATABASE=nest-course //database name
ports:
- 27017:27017 //Default port. Docker sets up the database on port 27017 and we can also access it outside of docker.Use the docker compose CLI to run the db service:
docker-compose up -d
. The d flag means we want to run the containers in detached mode, meaning they run in the background.If there are other services here and you want to run a specific service, you can do so by entering its name. When nothing is passed in, docker compose will generate all defined services.
Use mongoose in nest
Install:
npm i mongoose @nestjs/mongoose
. @nestjs/mongoose is for integrating nest with mongoose.Type safety:
npm i -D @type/mongoose
. Install the mongoose typescript definition as a ‘dev’ dependency.@nestjs/mongoose comes with a set of useful decorators and MongooseModule.
set mongoose
In app.module.ts in the root directory, add
MongooseModule.forRoot('mongodb://localhost:27017/nest-course')
in imports: [ ] . The second parameter is not present here, it is a configuration option. nest-course is the database name.At this point, use
npm run start:dev
to start the application, and mongodb can connect.