如何让Google Cloud VM上的RStudio已安装包重启后不丢失
Got it, let's fix this annoying issue once and for all! The problem you're facing is super common with the default R Studio VM on Google Cloud—it uses a Docker container, and every time you restart the VM, the container gets recreated from scratch. That means any packages you installed inside the container vanish because the container's filesystem is temporary.
Luckily, we can fix this by persisting the R package directory to the VM's persistent disk. Here's exactly what you need to do in the Google Cloud Console:
Core Issue Recap
The default R Studio VM template runs R Studio inside a Docker container. Containers are ephemeral by design—when the VM restarts, the container is reinitialized, wiping any changes (like installed packages) you made inside it. We need to mount the R package storage directory to the VM's persistent disk so packages stay saved between restarts.
Step-by-Step Console Actions
1. Stop Your VM Instance
Head to Compute Engine > VM Instances in the Google Cloud Console. Find your R Studio VM, click the three-dot menu next to it, and select Stop. Wait for the VM to fully stop before moving on.
2. Edit VM Startup Script
Once the VM is stopped:
- Click the name of your VM to open its details page.
- Click the Edit button at the top of the page.
- Scroll down to the Custom metadata section.
- Click Add item:
- For the Key, enter
startup-script - For the Value, paste this script (replace
your-rstudio-passwordwith your actual R Studio login password):#!/bin/bash # Create a persistent directory for R packages on the VM's disk mkdir -p /mnt/r_packages # Set correct permissions so R can read/write to this directory chmod 777 /mnt/r_packages # Clean up existing R Studio container if it exists if docker ps -a | grep -q rstudio; then docker stop rstudio docker rm rstudio fi # Launch R Studio container with the package directory mounted docker run -d -p 80:8787 \ -v /mnt/r_packages:/usr/local/lib/R/site-library \ -e USER=rstudio -e PASSWORD=your-rstudio-password \ --name rstudio rocker/rstudio:latest
- For the Key, enter
- Double-check that you replaced the password, then scroll to the bottom and click Save.
3. Restart the VM
Go back to the VM Instances page, find your VM, and click Start. Let the VM boot up completely.
Verify the Fix
Log into R Studio as usual, install a test package (e.g., install.packages("dplyr")), then stop and restart the VM again. After restarting, log back in and run library(dplyr)—if it loads without errors, your packages are now persisting!
Bonus Tip
If you have an additional persistent disk attached to your VM, you can use that instead of the root disk for R packages. Just replace /mnt/r_packages in the script with the mount path of your extra disk (e.g., /mnt/disks/my_extra_disk/r_packages).
内容的提问来源于stack exchange,提问作者Vikrant

