Mongo db persistence in docker with volumes

Viewed 13740

I'm trying to create a mongo database container, but can't make the data to persist. Here is my docker-compose.yml

version: "3.2"
services:
  mongodb:
  image: mongo:2.4
  command: --smallfiles 
  ports:
    - 27017:27017
  volumes:
    - type: volume
      source: mongodb_data_volume
      target: /data
volumes:
  mongodb_data_volume:
    external: true

After docker-compose, and exec -it into the mongodb, I create a new empty database and then I list the contents of the mounted volume:

root@cf8330019f91:/data/db# ls
_tmp     admin.1   journal  local.ns
admin.0  admin.ns  local.0  mongod.lock

But then I do a compose down and up cycle and the same mounted volume is reset to the initial values.

root@d18bda47d0b3:/data/db# ls
_tmp  journal  local.0  local.ns  mongod.lock

I've tried to only stop the container instead compose down, and then the data persisted... which would indicate that I'm still using the internal storage. If this is the case, how do I make it to use the external volume?

I'm using a mac and docker version 18.06.1-ce-mac73.

2 Answers

I have replicated same issue in my local system and try to resolve it,I have modified the target path in the docker-compose volume from "target: /data" to "target: /data/db" as per the documentation given in https://hub.docker.com/_/mongo/ and it works. Use updated docker-compose file as given below

    version: "3.2"
    services:
      mongodb:
      image: mongo:2.4
      command: --smallfiles 
      ports:
        - 27017:27017
      volumes:
        - type: volume
          source: mongodb_data_volume
          target: /data/db
    volumes:
      mongodb_data_volume:
        external: true

Tested and works !!!

I have created a mongodb container, with persistent storage using the following docker-compose.yml file trimmed down to the basics. I am using a official mongo image version and map the database data stored in the container under /data/db to a local folder /data as below:

version: "3.2"

services:
    mongodb:
        image: mongo:4.2.2-bionic
        container_name: mongodb
        restart: unless-stopped
        ports:
            - 27017-27019:27017-27019
        volumes:
            - ./data:/data/db
Related