Skip to main content

Set up persistent storage for a stateful app

10 min tutorial

What you'll build​

A Volume attached to a running Compute Instance, mounted and holding real data — then you'll detach it, reattach it, and confirm the data was there the whole time, independent of any single instance.

Prerequisites​

Show me!

Open Volumes

Click Volumes in the sidebar.

Create a new volume

Click + Create Volume.

Set the volume's capacity

Fill in the fields, then click Create Volume:

  • Name — pick something you'll recognize, like data-01.
  • Capacity — how much storage to provision. Use 20Gi for this tutorial.

Open Compute Instances

Click Compute Instances in the sidebar.

Select the instance

Check the row for the instance you want to attach the volume to — it needs to be in the same region as data-01.

Attach the volume

Click Attach Volume in the selection bar.

Choose the volume

Pick the volume to attach, then click Confirm:

  • Add Volume — the volume to attach. Pick data-01.

Format and mount the filesystem

SSH into the instance, format the new device, and mount it:

sudo mkfs.ext4 /dev/sdb
sudo mkdir -p /mnt/data
sudo mount /dev/sdb /mnt/data

Add it to /etc/fstab so it remounts automatically after a reboot:

echo '/dev/sdb /mnt/data ext4 defaults 0 2' | sudo tee -a /etc/fstab

Confirm it's mounted and writable:

df -h /mnt/data
Filesystem Size Used Avail Use% Mounted on
/dev/sdb 20G 45M 19G 1% /mnt/data

Write something to it

Prove the data lives on the volume, not the instance's root disk:

echo "hello from $(hostname), $(date)" | sudo tee /mnt/data/hello.txt
cat /mnt/data/hello.txt

Select the instance again

Check the same instance's row — this time to detach the volume.

Detach the volume

Click Detach Volume in the selection bar.

Confirm the detach

Click Confirm. The instance keeps running — data-01 and everything on it just stop being reachable from /mnt/data on that instance:

  • Detach Volume — already set to data-01.

Select an instance

Check a row to reattach the volume — the same instance again works for this tutorial, but the same steps apply just as well to a different instance, or to a fresh one you've since created from Deploy your first compute instance. data-01 doesn't know or care which instance it's plugged into.

Attach it again

Click Attach Volume in the selection bar.

Confirm the reattach

Pick data-01 again and click Confirm:

  • Add Volume — pick data-01.

Confirm the data survived

SSH into whichever instance you just attached it to, mount it the same way as before, and read the file back:

sudo mount /dev/sdb /mnt/data
cat /mnt/data/hello.txt

It prints the same line you wrote earlier. The volume carried its data across the detach/attach cycle — its lifecycle is independent of any one instance, including one that's been rebuilt from scratch.

Next steps​