MongoDB: Migrating Container to a Different Server

We have a very simple service called Learning Locker that we have built into one of our sites, it’s a PHP Front End with no Volumes, backed by MongoDB with a single volume (that contains information). Here’s how we originally created it:

docker run -d --name db -p 27017:27017 -p 28017:28017 mongo:3.2.21-jessie
docker run -d --name learninglocker --restart always --link db:mongo -p 8080:80 sproutlabs/learninglocker:latest

Nice and simple. So I need to move the mongo docker container to a different server. I was reading through the official docs that details this, but it’s not working as expected.

So first I attempted to just copy the files outright with tar:

docker run --rm --volumes-from db -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /data/db/

And then import it:

docker run --rm --volumes-from db -v $(pwd):/backup ubuntu bash -c "cd /data/db && tar xvf /backup/backup.tar --strip 1"

But that obviously didn’t work, because MongoDB isn’t aware of the database itself. So then I considered running mongodump in the source container with:

docker exec -it db cd /data/db/ && mongodump --database=learninglocker

And then migrating the entire directory over just as above. Except weird result the dump folder that is present in the source container and tar file aren’t in the destination. So how should I go about this final step of getting the /data/db/dumps folder over to the new container and run mongorestore with it?

I appreciate the help, thanks.

I can’t believe that there wasn’t an elegant solution for taking my mounted volume over to another machine. Anyways I ended up using mongodump to create a folder, bring that over to my new host, and then just use mongorestore.

1 Like

Have you found better solution for this?

After moving your data/db directory you need to manually set mongo.lock content from 1 to 0. After that if you start your mongodb container bound to data/db directory you should be able to see your dbs and data.

docker run --rm --volumes-from db -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /data/db/

you tar here /data/db

docker run --rm --volumes-from db -v $(pwd):/backup ubuntu bash -c "cd /data/db && tar xvf /backup/backup.tar --strip 1"

but you unzip here with -strip 1 which will upzip the zip as db folder, so you just need to cd /data

docker run --rm --volumes-from db -v $(pwd):/backup ubuntu bash -c "cd /data && tar xvf /backup/backup.tar --strip 1"

I’ve met the same problem, but found the tar --strip 1 trap. And resolved this just unzip the tar file to the right path

Uhm, I guess what you guys try to do is this.

Backup the volume (as gzip compressed tar with context):

docker run --rm --volumes-from db -v $(pwd):/backup alpine tar cvzf /backup/backup.tar.gz -C /data/db/ .

Restore the volume (from gzip compressed tar with context):

docker run --rm --volumes-from db -v $(pwd):/backup alpine tar xvzf /backup/backup.tar.gz -C /data/db/