3

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.

Ntwobike
  • 2,406
  • 1
  • 21
  • 27
shrap7
  • 79
  • 1
  • 5
  • Hey, welcome to SO! Can you run `docker inspect mongodb` both for the `docker` and `docker-compose` versions and compare the output? Take a look in particular at the `Mounts` section. – Max Dec 24 '18 at 02:18
  • 1
    Hi Max, thank you for responding. I did what you suggested. The mounts are identical for both except that the Mode is different between the two. The mode value when used direct commands is empty, that is, "Mode": "", but when used via docker-compose, it says "Mode": "rw". Does it mean anything? There is no other difference between the two mounts. – shrap7 Dec 26 '18 at 01:15

1 Answers1

5

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:
Paulo Moreno
  • 141
  • 2
  • 4