Persistence
  • While containers can create, update, and delete files, those changes are lost when the container is removed
  • Stopped container still keep the changes and can be restored by restarting the container
  • Store files in the host machine, so that the files are persisted even after the container is removed
  • Volumes
  • Volumes are stored in a part of the host filesystem and managed by Docker
  • Non-Docker processes should not modify this part of the filesystem
  • A given volume can be mounted into multiple containers simultaneousl
  • Docker for Mac runs a virtual machine behind, and the volume's path is the path on the virtual machine
  • docker volume create [name] # create a volume
    docker volume ls # list volumes
    docker volume rm [volumeName] # remove one or more volumes
    docker volume inspect [volumeName] # show volume information
            
    docker volume create sandbox-home # create a named volume "sandbox-home"
    docker run -v sandbox-home:/home -it busybox sh # run the sandbox linux
    
    # create a readme file under /home and exit the sanbox
    cd /home
    touch readme
    exit
    
    # remove the container
    docker rm [containerName]
    
    docker run -v sandbox-home:/home -it busybox sh # run the sandbox linux again
    
    # check the /home directory, readme file is still there
    cd /home
    ls
    		
    docker run -v sandbox-home:/home -it lchenlangley/hello sh # mount the volumn to a container running another image
    
    # check the /home directory, readme file is there
    cd /
    ls
            
    # two containers share one volumn
    # changes in the mounted directory on one container will appear in the mounted directory on another container
    docker run -v sandbox-home:/home -it lchenlangley/hello sh
    docker run -v sandbox-home:/home -it busybox sh
    
    # on the container with busybox
    cd /home
    touch hello2.py # create a file
    
    # on the container of lchenlangley/hello
    # check the /home directory, hello2.py file is there
    cd /home
    ls
            
    Bind Mounts
  • Bind a host directory to a container directory
  • The files created on host or container do not appear in the container directory. Instead, they exist in the host directory
  • Both host and container can access the created files
  • # docker run -it -v [hostDirectory]:[containerDirectory] busybox sh, need absolute path
    docker run -it -v $PWD/temp:/home busybox sh
    
    # on container
    cd /home
    touch hello.py
    ls # no file is there
    
    # on host
    cd $PWD/temp
    ls # hello.py file is here
    echo "print('Hello')" > hello.py
    
    # on container
    cat hello.py # can access hello.py, though hello.py does not appear in /home on container
            
    Reference
  • Storage