By Wilson Karl
I’m getting started with Docker and I noticed that every time I stop and remove a container, all the data inside it is lost. How can I set up my Docker containers to persist data even after the container is removed?
Is there a simple way to do this for databases or web applications that need to store data permanently?
Not sure if it matters but I am using the 1-Click Droplet from the Marketplace?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Accepted Answer
Hey there 👋,
By default, Docker containers are ephemeral, meaning that any data created inside the container is lost when the container is stopped or removed. But don’t worry, there’s a simple way to persist data in Docker by using volumes or bind mounts.
Here’s a quick breakdown of the two:
Docker Volumes Docker manages volumes and stores them outside the container’s file system. This is the recommended way to persist data in Docker because volumes are easier to manage and are independent of the container lifecycle. You can create a volume using this command:
docker volume create my_data_volume
Then, when you run your container, you can attach the volume like this:
docker run -d -v my_data_volume:/path/inside/container my_container
This way, any data in /path/inside/container
will persist even if the container is stopped or removed!
Bind Mounts With bind mounts, you link a directory on your host system to a directory inside your container. This is useful if you want to access specific files on your host machine directly. Here’s how you can set it up:
docker run -d -v /host/path:/container/path my_container
In this case, the files in /host/path
on your machine will be available inside the container at /container/path
.
So, if you’re running something like a MySQL or a web application that needs persistent storage, volumes are the way to go!
If you want to dive deeper into Docker and learn all about managing containers and volumes, check out this free Docker ebook: Introduction to Docker.
Let me know if you need any more help!
\— Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.