Add a Mongo Database With Docker to Your Project
Tags: docker
Published: 2020-04-07 17:33:46

---
title: Add a Mongo Database With Docker to Your Project
published: true
date: 2020-04-06 00:00:00 UTC
tags: docker
cover_image: https://images.unsplash.com/photo-1523363110939-434120455ab9?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=420&ixid=eyJhcHBfaWQiOjF9&ixlib=rb-1.2.1&q=80&w=1000
canonical_url: https://www.rockyourcode.com/add-a-mongo-database-with-docker-to-your-project/
series: docker-databases
---

> Quickly Add MongoDB to Your App With Docker

MongoDB is an open-source NoSQL database that stores data in JSON-like documents.

NoSQL databases are a natural choice if you don't know your data requirements upfront.  
They are also a good fit for applications like product catalogs or blog content.  
That's where an object-oriented approach shines.

Let's see how we can easily add a Mongo database with Docker and Docker Compose.

Prerequisites:

- [Docker](https://docs.docker.com/)
- [Docker Compose](https://docs.docker.com/compose/)

## Run MongoDB with Docker

In your project folder, open the terminal and run:

```bash
docker run --name mongo -p 27017:27017 -d mongo
```

The command will pull the default image from [Dockerhub][dh] and start the database on port 27017 on localhost.

### Connect Your App to MongoDB

That's fine and dandy, but how can I _use the database_ from my app?

The easiest way is to use the [URL connection string](https://docs.mongodb.com/manual/reference/connection-string/).

For the default configuration, you have to use the following format with the library of your choice (TypeORM or similar):

```bash
mongodb://localhost/<db-name>
```

Replace `<db-name>` with the name of your database.

Please note that you don't have to supply a username or password. [The default setup has no user and no password][so].

## Docker Compose

You can add a `docker-compose.yml` file to your project. With Docker Compose, you don't have to remember the exact commands for `docker run`.

In your project folder, add the `docker-compose.yml` file with the following content:

```yaml
version: '2.4'

services:
  db:
    image: mongo:4.0.17-xenial
    ports:
      - 27017:27017
    environment:
      - MONGO_INITDB_DATABASE=${DB_NAME}
    restart: always
    volumes:
      - db-data:/data/db:delegated

volumes:
  db-data:
```

(For alternative MongoDB versions, check out [Dockerhub][dh].)

We create a service with the name `db` (name it however you want). The container runs on port 27017 and binds that port to localhost. That way, you can connect to the database _from outside_ of the container.

We also create a volume. Now the data persists between subsequent Docker runs. Volumes can be tricky, but for local development, that setup should suffice.

You can read more about volumes on the [Docker documentation site](https://docs.docker.com/storage/volumes/).

Now we need an environment file to create the database. Create a new file called `.env` in your project:

```
DB_NAME=school
```

You can reuse that file for your app, too. For example, with JavaScript, you can use [dotenv](https://www.npmjs.com/package/dotenv) to read the content of your file.

Here's an example of a TypeORM configuration:

```js
import { TypeOrmModuleOptions } from '@nestjs/typeorm'
import 'dotenv/config'

export const typeOrmConfig: TypeOrmModuleOptions = {
  type: 'mongodb',
  url: `mongodb://localhost/${process.env.DB_NAME}`,
  useUnifiedTopology: true,
}
```

### Docker Compose Commands

Inside the root directory, open the terminal and type:

```bash
docker-compose up -d
```

The command will start the container in detached mode (in the background).

If you want to stop the container:

```bash
docker-compose down -v
```

(`-v` for bringing down the volume as well.)

If you want to use the command line to connect to the database:

```bash
docker-compose exec db mongo
```

- `docker-compose exec`: execute a command inside a running container
- `db`: name of the service (see configuration in `docker-compose.yml`)
- `mongo`: terminal command to run, see [`mongo`](https://docs.mongodb.com/manual/reference/mongo-shell/)

Now you are in the Mongo shell. Let's say you want to see all entries in the database `school`.

Select database `school`:

```bash
use school
```

Show all data from the collection lessons:

```bash
db.lessons.find().pretty()
```

## Recap

You've seen how to set up a MongoDB instance on your computer with only a few lines of code.  
Now you can develop your application with a NoSQL database!

If you'd like to use a relational database, you can read my guide on [using Postgres with Docker][addpostgres].

## Further Reading

- [When to Use (and Not to Use) MongoDB][dzone]
- [Add a Postgres Database With Docker to Your Project][addpostgres]
- [MongoDB what are the default user and password?][so]
- [Mongo on Dockerhub][dh]

[addpostgres]: https://www.rockyourcode.com/add-a-postgres-database-with-docker-to-your-project/
[mongo]: https://www.mongodb.com/
[dzone]: https://dzone.com/articles/why-mongodb
[dh]: https://hub.docker.com/_/mongo
[so]: https://stackoverflow.com/questions/38921414/mongodb-what-are-the-default-user-and-password