In this recipe, we introduced Docker containers and worked with the official MondoDB container. We could just as easily have used a MySql container or some other database. Using the MongoDB container (or indeed any other containerized infrastructure) is very simple. There's no need for compilation steps, nor installation of binaries or libraries on our local system. The MongoDB container came preconfigured with everything it needed to run in an encapsulated manner.
When a user fills out the HTML form at the /add route, the browser submits a POST request to the /add/calculate route. The POST request is handled in micro/webapp/routes/add.js, where a request to the adderservice and the auditservice is made. The auditservice is sent a POST request to the /append route, and the route handler in micro/auditservice/wiring.js calls the service.append method, which is in the micro/auditservice/service.js file. The service.append function uses the mongodb module to interface with the MongoDB database within the mongo container and inserts a new record.
When the /audit/list route is loaded in the browser, the route handler in micro/webapp/routes/audit.js makes a GET request to the auditservice/list route. The route handler in micro/auditservice/wiring.js file calls the service.list function, which is written in micro/auditservice/service.js. This in turn makes a request to MongoDB to fetch a list of entries. This list is ultimately fed into the micro/webapp/views/audit.ejs template for rendering.
While this approach to using infrastructure is convenient in development, containers are a game changer when it comes to production deployment. We will investigate this topic in more detail in Chapter 11, Deploying Systems.
Our auditservice process was able to connect to the MongoDB container in just the same way as if there were a local installation of MongoDB, so no changes to the code were required in order to use the Docker container.
While containers are incredibly useful for deployment and infrastructure encapsulation in development, working with Node processes natively tends to allow for more rapid iteration. This is why we use Fuge to run both our container and our Node processes.
We connected to the Mongo container using the following URL:
const url = `mongodb://${MONGO_SERVICE_HOST}:${MONGO_SERVICE_PORT}/audit`
Fuge generated these environment variables from the service definition for us, which means that we do not have to have a separate configuration file for our service. This is important to ensure a smooth transition for our service from development to a production environment, as should become apparent in the following recipe, Service discovery with DNS, and in Chapter 11, Deploying Systems.