The volume flag mounts a Docker volume at a specified path inside a container. Use the same syntax whether or not the image declares a Dockerfile VOLUME instruction. section 6.2
Use the flag to control container storage:
- Specify a named volume and target path with -v volume-name:/data on Linux or -v volume-name:c:\data on Windows. section 6.2
- Override an image's declared volume by mounting an existing volume at the same target path. section 6.2
- Prefer named volumes instead of relying on automatically created volumes with random IDs. section 6.2
Keep to-do data across an application update
Create a volume with docker volume create todo-list, then run version 1 using -v todo-list:/data. Remove that container and run version 2 with the same -v todo-list:/data mount; the application keeps its stored data. section 6.2
# save the target file path in a variable: target='/data' # for Linux containers $target='c:\data' # for Windows containers # create a volume to store the data: docker volume create todo-list # run the v1 app, using the volume for app storage: docker container run -d -p 8011:8080 -v todo-list:$target ` --name todo-v1 diamol/ch06-todo-list:2e # add some data using the web app at http:/./localhost:8011 # remove the v1 app container: docker container rm -f todo-v1 # and run a v2 container using the same volume for storage: docker container run -d -p 8011:8080 -v todo-list:$target ` --name todo-v2 diamol/ch06-todo-list:2e-v2
Shows the complete named-volume workflow, including Linux and Windows target paths, application replacement, and reuse of stored data. section 6.2
