Using preexisting Persistent Disks as PersistentVolumes

This page explains how to create a PersistentVolume using an existing Compute Engine persistent disk populated with data, and how to use the PersistentVolume in a Pod.

Creating the PersistentVolume and PersistentVolumeClaim

If you already have a 500-GB persistent disk named pd-name, the following manifest file (named existing-pd.yaml) describes a corresponding PersistentVolume and PersistentVolumeClaim.

This example uses a claimRef. By referencing a PersistentVolumeClaim in the PersistentVolume, you can ensure that the PersistentVolume can only be bound with the PersistentVolumeClaim that you specify.

A StorageClass object with a name matching storageClassName is only necessary if you require functionality configured by the StorageClass, for example allowVolumeExpansion for volume resizing.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-demo
spec:
  storageClassName: "example-storageclass"
  capacity:
    storage: 500G
  accessModes:
    - ReadWriteOnce
  claimRef:
    namespace: default
    name: pv-claim-demo
  gcePersistentDisk:
    pdName: pd-name
    fsType: ext4
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pv-claim-demo
spec:
  storageClassName: "example-storageclass"
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 500G

To create the PersistentVolume and PersistentVolumeClaim use kubectl apply -f existing-pd.yaml.

Using the PersistentVolume in a Pod

After the PersistentVolume and PersistentVolumeClaim exist in the cluster, you can give a Pod's containers access to the volume by specifying values in the volumeMounts field. In this example, these fields specify that the volume named task-pv-storage is mounted at the file path /usr/share/nginx/html.

kind: Pod
apiVersion: v1
metadata:
  name: task-pv-pod
spec:
  volumes:
    - name: task-pv-storage
      persistentVolumeClaim:
       claimName: pv-claim-demo
  containers:
    - name: task-pv-container
      image: nginx
      ports:
        - containerPort: 80
          name: "http-server"
      volumeMounts:
        - mountPath: "/usr/share/nginx/html"
          name: task-pv-storage

When you apply this manifest to a cluster, the Pod is created, and the task-pv-container container has access to the volume in its /usr/share/nginx/html/ directory.