What's in this article
The goal is to take a basic MEAN application generated by Yeoman, package it as a container using Docker and run it with the help of an instance of MongoDB also running in a container.
Tools and versions used in this article
Generating the project
The following commands install the generator and run it to create a mean project.
Yeoman will ask you a bunch of questions. You can just hit Enter to accept the default settings or bend the project to your will.
Once that's finished you can run it by typing
Setting up a development database
Unless you already have a MongoDB instance running on your computer, listening to the default port 27017, the previous command will generate a few errors. To fix them, either you can use your favorite package manager to install and start an instance, or you can use Docker.
Now you should be able to run the project.
Testing and Building
The project has a few tests — written in Jasmine or Karma + Chai + Sinon depending on what you chose — that require the local database to be running.
Building the project is straightforward and puts everything in the
Building a Docker image
In order to build a Docker image, you need to specify how the image should be constructed. One rarely builds an image from scratch. Instead you can take a base image that's close to what you need, and then add the rest. The following
Dockerfile specifies just this.
We take an image that already contains a specific version of Node, then we add the
package.json file, ask
npm to install all dependencies, before copying the rest of the built files. The last two instructions indicate that the process in the container will be listening on port 8080, and that the process is started by running the command
You can build the image with the following command.
Running the application in Docker
Once the application image is available, we just need to start a container with MongoDB, then start the application as another container. We'll need to feed the database connection URL to the application. The easiest way to do this is using an environment variable.
We'll also need to tell our application that is running in production mode. Again setting an environment variable does the job.
We could run each container using individual commands, but it is far easier to write a composition that Docker Compose can manage. This makes starting and stopping the containers over and over much easier.
The following is the contents of a docker-compose.yml file that tells Docker Compose how to configure and run the containers needed by our application.
This composition is run by the command
and torn down by the command