Volume Management: Taming the Beast
Volumes are persistent, which means they don't disappear when you delete containers. If you aren't careful, your disk will fill up with orphan volumes containing gigabytes of stale data. You need to master the lifecycle.
1. The Lifecycle of a Volume
- Creation: Explicit (
docker volume create) or Implicit (viaVOLUMEinstruction in Dockerfile). - Attachment: Mounted into a running container.
- Detachment: Container stops or is removed. The volume remains.
- Pruning: Deleting volumes that are no longer attached to any container.
Named vs Anonymous Volumes
- Named:
docker run -v my-db:/data .... Easy to find and manage. - Anonymous:
docker run -v /data .... Docker generates a random hash name (e.g.,2d3f4a...). These are the primary cause of “disk leak”.
2. Interactive: Lifecycle Simulator
Visualize the state of a volume as you perform operations.
1. Created
→
2. Attached
→
3. Detached
→
4. Pruned
Volume: my-vol
Status: Free
System Ready.
3. Code Example: Cleaning Up
How to programmatically find and remove unused volumes.
package main
import (
"context"
"fmt"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
)
func main() {
ctx := context.Background()
cli, _ := client.NewClientWithOpts(client.FromEnv)
// Prune Volumes
// Equivalent to: docker volume prune -f
report, err := cli.VolumesPrune(ctx, filters.Args{})
if err != nil {
panic(err)
}
fmt.Printf("Deleted Volumes:\n")
for _, v := range report.VolumesDeleted {
fmt.Println(v)
}
fmt.Printf("Space Reclaimed: %d bytes\n", report.SpaceReclaimed)
}
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.api.model.PruneResponse;
public class VolumeCleaner {
public static void main(String[] args) {
DockerClient dockerClient = DockerClientBuilder.getInstance().build();
// Prune unused volumes
PruneResponse response = dockerClient.pruneCmd(PruneType.VOLUMES).exec();
System.out.println("Space Reclaimed: " + response.getSpaceReclaimed());
}
}