Move Data From Container to Host
I found when I was just getting started (although I’m still somewhat of a N00b), I would create containers from docker-compose files where I didn’t really know how to define the volume location (localhost or within container). Alot of the templates I had were just hosting the application data within the container itself, which kind of cuts the usefulness of using containers in half…. or maybe by 30%??
So, I decided to revisit these old containers that had app data in the container itself so I can eventually do upgrades without having to manually back up the data from within a container or depend on the software to have a backup feature.
First line of business is to make a backup of the data in case I accidentally delete something and lose all my configs/data. So, let’s create a backup folder on my host where I will eventually move the data to. I use portainer, so my volume path would be as follows:
mkdir /var/lib/docker/volumes/backup_dir
Now we can log interactively log into the container (using shell or bash depending) and make sure I validate ‘where’ the data exists and maybe even look at the data (if human readable) and see if it’s what I want/expect.
docker exec -it <docker id> /bin/bash
In this case, I would look around for a “data” folder or look at the documentation to see where they store the data. When I find the folder, I will then copy the directory to the host (outside the container).
docker cp 262603b1c24c:/app/data /var/lib/docker/volumes/backup_dir/
The way I did it next may still be wrong, but it seemed to work with alot less guessing.
I edited the docker-compose file and changed the configuration to define the new location of the volume where I want the data to reside.
volumes:
- appdata:/appdata
- metadata:/metadata
- config:/config
volumes:
appdata:
metadata:
config:
I will then start my container and see what the default directory structure looks like. I would then copy my data from the ‘backed up’ directory (backup_dir) to the new location the was created from docker.
cp -R /var/lib/docker/volumes/backup_dir /newcontainerfolder/_data/
(this is only an example and could differ from container to container)
I would then restart my container and see if all my data was restored and working.