Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create Docker Volumes for Persistent Storage

    Mark ShustMark Shust

    Docker containers are stateless by default. In order to persist filesystem changes, you must use docker volumes. In this lesson, we will go over how to copy files over to Docker containers, how to create volumes and copy data to them, and also how to mount remote folders for persisting updates.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Docker containers are typically stateless, but you can add a volume onto containers for persistent storage. Let's start a new Docker container mapping port 80 to the host with the name of web and a --rm so it's removed on termination, followed by the name of the image we want to run, NGINX.

    If we check the URL on our web browser, we can see that the NGINX container is running. Let's modify the default file served, open another terminal tab, and create an index.html file with the contents of foo. Then copy the file over to the Docker container.

    If we reload the website URL, we can see foo. Now stop the container and restart it. We can see that the container is stateless, as the foo file is not persisting. Let's stop the container and start it up again, but this time we'll attach a volume to it.

    We do this by using the -v flag, followed by the name of our volume, a colon, and the directory we want to be persistent. In this case it will be the default home directory that NGINX uses, user/share/NGINX.html. We can see the default NGINX page again.

    Now let's copy our foo file over to it again, and we can verify it as copy by refreshing the browser window. Let's kill the container and start it up again. If we reload our browser window, we can see that the data is now persisting for our mounted volume.

    Another way to mount a volume is from your host machine. This follows a similar format, but instead of specifying the name of the volume, we specify the directory we want to mount from. Let's use $pwd to specify the current directory. We can see that refreshing the browser window shows our foo file.

    Let's modify this file on our host to bar, then refresh our browser window. We can see that host file modifications are in fact remotely mounting into our Docker container, and the container doesn't need to be restarted for updates to take effect.