Load data from host to docker container and write back to host on exit. Load and Persist data between host and container

My requirement is to create docker image using data in host directory. And when I run the container, the data produced in the container has to be copied back to the host directory. In simple words, data persistence.

Here is how i build and run the container (that works):

Docker build & create, starts the container with data in host location (all fine)

#!/bin/bash
sudo docker build -t myimage:latest . && > /dev/null
sudo docker create -p 8080:8080 -v host/data/location:/etc/container/data/location --name mycontainer myimage:latest && > /dev/null

Start container and copy data back to host for persistence.

#!/bin/bash
#start container
sudo docker start mycontainer && > /dev/null

#copy data on exit 
sudo docker cp mycontainer:/etc/container/data/location/. `pwd`/host/data/location/ && > /dev/null

I know that the best way is to mount volumes but it has been unsuccessful on copying data back to host from container. And i want to get rid of copy step.

It should work,

docker create -p 8080:8080 -v /host/data/location:/etc/container/data/location --name mycontainer myimage:latest 

but it isn’t! Can someone tell the reason?

Source: StackOverflow