Use Case: Run an Nginx container that serves content from a volume so that data persists even if the container is removed.
// persistent volume with nginx
git clone https://github.com/atulkamble/docker-nginx-persistence-volume.git
cd docker-nginx-persistence-volume
sudo docker run -d -p 80:80 nginx
sudo docker volume create nginx_volume_test
docker volume ls
docker container ls
or
docker ps -a
docker cp ./data/index.html 4b97ab275607:/usr/share/nginx/html/index.html
docker system prune -a
docker compose up --build
docker compose down
docker-volume-project/
├── data/
│ └── index.html
├── docker-compose.yml
└── Dockerfile
<!DOCTYPE html>
<html>
<head>
<title>Docker Volume Test</title>
</head>
<body>
<h1>Hello from Docker Volume!</h1>
<p>This page is served using a Docker Volume.</p>
</body>
</html>
(Here we use the official Nginx image, no need for custom build in this case, but for practice let's create one.)
# Use official Nginx image as base
FROM nginx:latest
# Expose port 80
EXPOSE 80
(Defines service, volume, and volume binding)
services:
webserver:
build: .
ports:
- "80:80"
volumes:
- ./data:/usr/share/nginx/html
container_name: nginx_volume_test
After defining the Docker Compose setup, you need to copy the index.html
file into the volume. Since volumes are managed by Docker, one way is:
Run container:
docker compose up -d --build
Find volume name:
docker volume ls
Find mount path:
docker volume inspect docker-nginx-persistence-volume_web_data
Copy file:
docker compose up -d --build
docker cp ./data/index.html nginx_volume_test:/usr/share/nginx/html/index.html
Visit: http://localhost:8080
You should see your index.html
page.
Stop & remove the container:
docker-compose down
Check if the volume still exists:
docker volume ls
You’ll notice dockervolumeproject_web_data
still exists — confirming data persists independently of the container.
docker volume rm dockervolumeproject_web_data
✅ Created a volume ✅ Mapped it to Nginx’s content directory ✅ Verified content persists even after container removal