Replacing a container can discard data written to its writable layer. That is fine for a disposable cache, but not for a database. A Docker volume is storage with a lifecycle separate from the container’s: attach it at a directory, and the application reads and writes there as usual. Attach the same volume to a replacement container to make the stored data available again. section 6.1 section 6.2
Choose how to attach the volume:
- Declare `VOLUME /data` in a Dockerfile. Docker creates and attaches a volume when a container starts from the image. Use `C:\data` as the application path for Windows containers. section 6.2
- Create a named volume with `docker volume create todo-list`, then attach it with `-v todo-list:/data` on Linux. For Windows containers, use `-v todo-list:c:\data`. Reuse the name when starting the replacement container. section 6.2
- Check an attachment with `docker container inspect --format '{{json .Mounts}}' todo1`; list volumes with `docker volume ls`. section 6.2
Keep a to-do list through an update
Create `todo-list` and run the to-do application with that volume mounted at its data directory. Add items in the web app, remove the container, then start the updated image with the same named volume. The updated app can read the existing items. Simply starting a second container from an image that declares `VOLUME` gives it its own volume instead; sharing storage requires attaching the existing one. 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
Commands for creating the named volume and attaching it to both versions, with Linux and Windows target paths. section 6.2
A bind mount is a different choice: it exposes a specific host directory inside the container, so host and container can access the same files. A volume keeps the storage lifecycle separate while Docker manages the resource. Plan mount targets carefully: mounting a directory over one populated by the image hides the image’s files rather than merging them. section 6.3 section 6.4







