Data does not persist to host volume with docker-compose.yml for MongoDB

Viewed 2675

Have docker installed on my Mac along with MongoDB image. When I start the container with volume specified directly in the docker run command, the data gets persisted even after I stop the container. But the same does not work when I do it via docker-compose.yml. Can someone suggest what's wrong with the docker-compose.yml file?

When I do this, the data gets persisted:

docker run --name mongodb -v /Users/shrap7/projects/mongodb/data:/data/db --rm -d mongo

But when I try the same with docker-compose.yml - it does not persist data.

version: '3.4'
services:
    mongodb:
       image: mongo:latest
       container_name: "mongodb"
       volumes:
          - /Users/shrap7/projects/mongodb/data:/data/db
       ports:
          - 27017:27017

I tried with double quotes, tried relative path, i.e. ./data:/data/db, but no luck. Thank you.

1 Answers

I'm using Windows and I had the same issue today. I found this gist that shows a mongodb configuration for docker-compose, and it has support for named volumes. I tried using named volumes and it worked for me.

So in your case, you could try the following configuration (with named volumes):

services:
    mongodb:
        image: mongo:latest
        container_name: "mongodb"
        volumes:
            - mongodb:/data/db
            - mongodb_config:/data/configdb
        ports:
            - 27017:27017
volumes:
    mongodb:
    mongodb_config:
Related