Howto run MongoDB within Docker using an external volume

Recently, we have been asked to maintain an application that we have not developed, and to deploy it on our infrastructure. It's a MEAN stack: MongoDB, Express, Angular and Nodejs. To do so, I had to deploy MongoDB within a Docker Container. It's been ridiculously hard.

My goal was to use an OVH block storage volume to store MongoDb data. My initial idea was to format (in xfs), mount the volume and attach it to the container as a bind-mount.

  docker run -v /mnt/mongodata:/data/db mongo-image 

As you may know, this is not the right choice, as the host remains responsible of the mount point.

Regarding MongoDb, the things turn bad very quickly as it won't create a database pretexting insufficient privileges.

I tried every chmod and chown you could think of, except chmod 777.

However, when I create a volume and attach it to the MongoDB container it starts and creates its database...

What I didn't know is that you can create a volume with the directory of your choice. You can create a volume from a filesystem. Docker will mount it for you when you start the container. Something like:

  docker volume create --opt type=xfs --opt device=/dev/sdc1 mongo_data 

Here the volume will be mounted under /var/lib/docker/volumes only while the container is running. I use the type xfs as it is recommended in MongoDB documentation.

Actually I don't know if it's the right command as I set it up in an Ansible playbook

So, takeaway: create a volume with options allows you to create a volume from everything. It simplify the use of an external object storage.

Posted on 2025-09-17

Tags: docker, mongodb

Previous Back