How to use docker volume

When you're working with Docker, you often need a way to store data that persists even after your containers stop or get deleted. That's where Docker volumes come in. Think of them as special folders that keep your data safe and accessible, no matter what happens to your containers.
First off, Docker volumes are a type of storage that Docker manages for you. They're separate from the container's writable layer, which means the data in a volume doesn't get affected by the container's lifecycle. This is super helpful for databases, file uploads, or any data you want to keep around.
To create a Docker volume, you use a simple command:
docker volume create my_volume
This creates a volume named my_volume
. You can then attach this volume to a container when you start it:
docker run -v my_volume:/app/data my_image
In this example, my_volume
is mounted to the /app/data
directory inside the container. Any data written to /app/data
in the container will be stored in the volume.
Now, let's say you're running a web app that lets users upload images. You'd want those images to stick around, even if you update or restart your app. Here's how you could set that up:
- Create a volume for your images:
docker volume create image_uploads
- Start your web app container with the volume attached:
docker run -d -p 8080:80 -v image_uploads:/app/uploads my_web_app
In this command,-d
runs the container in detached mode,-p 8080:80
maps port 8080 on your host to port 80 in the container, and-v image_uploads:/app/uploads
mounts theimage_uploads
volume to the/app/uploads
directory in the container. - Your web app can now write user-uploaded images to
/app/uploads
, and they'll be safely stored in theimage_uploads
volume.
If you ever need to see where a volume is storing its data on your host machine, you can use:
docker volume inspect image_uploads
This command will show you the mountpoint of the volume, which is the actual directory on your host where the data is stored.
Docker volumes also make it easy to share data between multiple containers. For example, if you have a separate container for processing the uploaded images, you can mount the same volume to that container:
docker run -d -v image_uploads:/app/input image_processor
Now both your web app and image processor containers can access the same set of images.
In summary, Docker volumes are a simple yet powerful way to manage persistent data in your Docker environment. They help keep your data safe and make it easy to share between containers. Whether you're dealing with user uploads, databases, or any other persistent data, Docker volumes are an essential tool in your Docker toolkit.