docker clone volume
If you are developing a website and you are running your local environment in docker then, when it comes to testing, you can use this little trick to come up with some useful patterns.
The basic idea is:
- Get your local database into a known state
- Make a copy
- Bring up your docker stack on the copy
- Do your tests
- Throw away the altered copy
- Repeat
For reference I'm going to use my public Magento 2 docker stack which is available here:
https://github.com/willwright/docker-magento2
Looking at the db service and the volumes specifically
db:
image: wwright/magento2-db
volumes:
- mysqldb:/var/lib/mysql:delegated
ports:
- "3306:3306"
environment:
- MYSQL_ROOT_PASSWORD=password123
- MYSQL_DATABASE=magento
volumes:
mysqldb:
esdata1:
Notice the MySQL DB is using the named volume mysqldb
.
First step is to make a new named volume that we can copy the data into.
docker volume create mysqldb4testing
If you are using a Mac or you are on Linux go to the following link, download the scripts and run docker_clone_volume.sh
.
https://github.com/gdiepen/docker-convenience-scripts
Swap out the volumes
db:
image: wwright/magento2-db
volumes:
- mysqldb4testing:/var/lib/mysql:delegated
ports:
- "3306:3306"
environment:
- MYSQL_ROOT_PASSWORD=password123
- MYSQL_DATABASE=magento
volumes:
mysqldb:
mysqldb4testing:
esdata1:
docker-compose down
docker-compose up
and you should be all set.
If you're on Windows then it's likely that the bash script won't work for you so you'll need to go old school and run the straight docker command shown below.
docker run --rm -i -t -v mysqldb:/from -v mysqldb4testing:/to alpine ash -c "cd /from ; cp -av . /to"
Note that you might need to replace mysqldb
and mysqldb4testing
with whatever volume names you chose.
Now you can run your integration test or load test or whatever it is you need to do over and over and over starting with the exact same state.