title: How to migrate a MongoDB database between Docker containers?
body: <p>Migrating databases in MongoDB is a pretty well understood problem domain and there are a range of tools available to do so on a host-level. Everything from <a href="https://docs.mongodb.com/manual/reference/program/mongodump/" rel="noreferrer"><code>mongodump</code></a> and <a href="https://docs.mongodb.com/manual/reference/program/mongoexport/" rel="noreferrer"><code>mongoexport</code></a> to <code>rsync</code> on the <a href="https://docs.mongodb.com/manual/core/backups/#back-up-by-copying-underlying-data-files" rel="noreferrer">data files</a>. If you're getting very fancy, you can use network mounts like <a href="https://en.wikipedia.org/wiki/SSHFS" rel="noreferrer">SSHFS</a> and <a href="https://en.wikipedia.org/wiki/Network_File_System" rel="noreferrer">NFS</a> to mitigate diskspace and IOPS constraint problems.</p>
  
  <p><strong>Migrating a Database on a Host</strong></p>
  
  <pre class="lang-bash prettyprint-override"><code># Using a temporary archive
  mongodump    --db my_db --gzip --archive /tmp/my_db.dump --port 27017
  mongorestore --db my_db --gzip --archive /tmp/my_db.dump --port 27018
  rm /tmp/my_db.dump
  
  # Or you can stream it...
  mongodump      --db my_db --port 27017 --archive \
  | mongorestore --db my_db --port 27018 --archive
  </code></pre>
  
  <p>Performing the same migrations in a containerized environment, however, can be somewhat more complicated and the lightweight, purpose-specific nature of containers means that you often don't have the same set of tools available to you.</p>
  
  <p>As an engineer managing containerized infrastructure, I'm interested in what approaches can be used to migrate a database from one container/cluster to another whether for backup, cluster migration or development (data sampling) purposes.</p>
  
  <p><em>For the purpose of this question, let's assume that the database is <strong>NOT</strong> a multi-TB cluster spread across multiple hosts and seeing thousands(++) of writes per second (i.e. that you can make a backup and have "enough" data for it to be valuable without needing to worry about replicating oplogs etc).</em></p>