简体   繁体   中英

Docker volume mount path

I'm trying to get started with Docker volumes. I have a simple Python Flask app that stores data in an sqlite3 data base. Running the app in a container without a volume works, but of course, every time I restart the container, all DB data is lost.

I've tried to read the available documentation on how to use volumes and I created a new, named volume:

docker volume create mydb

But I don't get what path I have to specify when starting the container with the volume. If I just do

docker run -p 5000:5000 -v mydb:/db my-app

it still loses all data when restarting. What do path do I need to specify instead of /db ? What does this depend on?

You can use bind mounts or docker volumes .

Assuming you selected /<path-to-db> as the location of the database inside the container, and ./data is the folder on your host filesystem you'd like to use to persist the database, or mydb is the volume you use:

docker run -p 5000:5000 -v ./data:/<path-to-db> my-app
docker run -p 5000:5000 -v mydb:/<path-to-db> my-app

To find out which path inside the container you use to store the files (if you are not sure), look for sqlite3.connect code: the argument is the path you need.

Named Volumes should not lose the data, as explained in the docs :

Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.

What you actually need is to ensure that you are saving the database to the correct directory that the named volume will use. I suggest creating a specific directory inside your flask app in order to save the sqlite3 file, then mount that directory to your named volume. So for example your sqlite3 file path is: /home/myflaskapp/db then the mount will be as following otherwise you will lose the data because you have not mounted the correct path that you want to keep:

docker run -p 5000:5000 -v mydb:/home/myflaskapp/db my-app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM