Moving Docker container data

      No Comments on Moving Docker container data

If you have created a container without specifying a volume, Docker will create one for you. If you later decide you’d rather have the container’s data somewhere else, you can move it. Docker does not provide a command for this, but you can do it as described below.

Let’s imagine you have a directory “move-test” containing the following docker-compose file:

version: '2'
 
services:
 database:
  container_name: move_test_db
  image: postgres
  restart: always

If we now start this container with “docker-compose up -d”, Docker will create a volume somewhere for the postgres data. In order to find out where, we can do a “docker inspect move_test_db”. This will display a json structure containing a “Mounts” section like the following:

        "Mounts": [
            {
                "Type": "volume",
                "Name": "23e8a6e5f36ee8121a05b926259424ab30",
                "Source": "/var/lib/docker/volumes/23e8a6e5f36ee8121a05b926259424ab30/_data",
                "Destination": "/var/lib/postgresql/data",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
 

So our data is stored in /var/lib/docker/volumes/23e8a6e5f36ee8121a05b926259424ab30/_data.

If we now create a sub-directory called “data” and want to move the container’s data there, we can do the following:

docker-compose down
sudo rsync -a /var/lib/docker/volumes/23e8a6e5f36ee8121a05b926259424ab30/_data/ ./data

We then just need to update the docker-compose file as follows:

version: '2'
 
services:
 database:
  container_name: move_test_db
  image: postgres
  restart: always
  volumes:
   - ~/data:/var/lib/postgresql/data

and then we can restart the container with “docker-compose up -d”.

Note: we didn’t remove the old data – this can be done by purging dangling volumes as follows:

docker volume rm `docker volume ls -q -f dangling=true`

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.