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!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
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:
Then, when you run your container, you can attach the volume like this:
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:
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