Formatar e ativar um disco que não é de inicialização em uma VM do Linux
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Linux
Se você anexou um disco novo e em branco à VM, antes de poder usá-lo, formate-o e ative-o. Se você anexou um disco que já contém dados, ative-o antes de usá-lo.
Antes de começar
Configure a autenticação, caso ainda não tenha feito isso.
A autenticação verifica sua identidade para acesso a serviços e APIs do Google Cloud . Para executar
códigos ou amostras de um ambiente de desenvolvimento local, autentique-se no
Compute Engine selecionando uma das seguintes opções:
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and
APIs, you don't need to set up authentication.
gcloud
Instale a CLI do Google Cloud.
Após a instalação,
inicialize a CLI do Google Cloud executando o seguinte comando:
Clique no botão SSH ao lado da instância que tem o novo disco
anexado. O navegador abrirá uma conexão de terminal com a VM.
Formatar um disco que não é de inicialização em uma VM Linux
Permissões exigidas para a tarefa
Para executar esta tarefa, é necessário ter as seguintes
permissões:
compute.instances.setMetadata na instância, para que você possa se conectar usando SSH.
Se você estiver se conectando a uma instância da VM que possa ser executada como uma conta de serviço, conceda também o papel roles/iam.serviceAccountUser.
No terminal, use o link simbólico criado para o disco anexado e determine qual dispositivo formatar.
ls-l/dev/disk/by-id/google-*
Os discos não formatados não têm outros links simbólicos com
-partN no nome.
Neste exemplo, o novo Persistent Disk foi criado com o nome extra-scsi-disk. O nome do dispositivo do novo disco é sdb.
Formate o dispositivo de disco usando a ferramenta mkfs.
Este comando exclui todos os dados do disco especificado. Portanto, verifique
se você especificou o dispositivo de disco corretamente.
É possível usar qualquer formato de arquivo necessário, mas recomendamos um único
sistema de arquivos ext4 sem uma tabela particionada. Você pode aumentar o tamanho
do disco
mais tarde sem precisar modificar as partições do disco.
Para aumentar o desempenho
do disco, use as opções de formatação recomendadas
na sinalização -E. Não é necessário reservar espaço para a raiz
neste disco secundário. Portanto, especifique -m 0 para usar todo o
espaço disponível no disco. O comando a seguir formata todo o disco sem a tabela de partições.
FILE_SYSTEM_TYPE: o tipo de sistema de arquivos. Por exemplo, ext2,
ext3, ext4 ou xfs.
DEVICE_NAME: o nome do dispositivo do
disco que você está formatando. Por exemplo, considerando o exemplo de saída da primeira etapa, use sdb para o nome do dispositivo.
Montar o disco
Crie um diretório que sirva como ponto de montagem para o novo disco na VM.
Use qualquer diretório. No exemplo a seguir, criamos um diretório em
/mnt/disks/.
$ sudo mkdir -p /mnt/disks/MOUNT_DIR
Substitua MOUNT_DIR pelo diretório em que você quer
montar o disco.
Use a ferramenta mount
para montar o disco na instância e ative a opção discard:
$ sudo mount -o discard,defaults /dev/DEVICE_NAME /mnt/disks/MOUNT_DIR
Substitua:
DEVICE_NAME: o nome do dispositivo do disco a
ser montado.
MOUNT_DIR: o diretório em que o disco
será montado.
Configure as permissões de leitura e gravação no disco. Neste exemplo,
conceda acesso de gravação no dispositivo a todos os usuários:
$ sudo chmod a+w /mnt/disks/MOUNT_DIR
Substitua MOUNT_DIR pelo diretório em que você
montou o disco.
Configurar a montagem automática na reinicialização da VM
Adicione o disco ao arquivo /etc/fstab para que ele seja montado de novo
automaticamente quando a VM for reiniciada. Em sistemas operacionais Linux, o
nome do dispositivo pode mudar a cada reinicialização, mas o UUID do dispositivo sempre indica
o mesmo volume, mesmo quando você move discos entre sistemas. Por isso,
recomendamos usar o UUID do dispositivo em vez do nome do dispositivo para configurar
a montagem automática na reinicialização da VM.
DEVICE_NAME: o nome do dispositivo do disco que
você quer montar automaticamente. Se você criou uma tabela particionada no
disco, especifique a partição que quer montar adicionando o sufixo
anexado ao nome do dispositivo. Por exemplo, se sdb for o nome do dispositivo
para o disco, sdb1 poderá ser o nome da partição.
Abra o arquivo /etc/fstab em um editor de texto e crie uma entrada que inclua o UUID. Exemplo:
UUID_VALUE: o UUID do disco, listado na
saída da etapa anterior.
MOUNT_DIR: o diretório em que você montou
o disco.
FILE_SYSTEM_TYPE: o tipo de sistema de arquivos.
Por exemplo, ext2, ext3, ext4 ou xfs.
MOUNT_OPTION: especifica o que o sistema operacional faz se não for possível ativar o disco permanente zonal no momento da inicialização.
Para valores válidos, consulte O quarto campo na documentação do fstab do Linux.
Para permitir que o sistema seja inicializado mesmo se o
disco estiver indisponível, use a opção nofail.
Use o comando cat para verificar se as entradas /etc/fstab estão corretas:
Sempre mantenha o arquivo /etc/fstab sincronizado com os dispositivos anexados a
uma VM. Se você quiser remover um disco ou criar um snapshot do disco de inicialização de uma VM, edite o arquivo /etc/fstab e remova a entrada do disco. Mesmo que você defina MOUNT_OPTION como nofail ou nobootwait, remova a entrada antes de criar o snapshot do disco de inicialização ou removê-lo.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[[["\u003cp\u003eNew or pre-existing disks attached to a Linux VM must be formatted and/or mounted before they can be used.\u003c/p\u003e\n"],["\u003cp\u003eFormatting a disk with the \u003ccode\u003emkfs\u003c/code\u003e tool deletes all data, requiring correct disk device specification, and \u003ccode\u003eext4\u003c/code\u003e is recommended for maximizing disk performance.\u003c/p\u003e\n"],["\u003cp\u003eMounting a disk involves creating a mount point directory and using the \u003ccode\u003emount\u003c/code\u003e tool, and you can set permissions such as universal write access using \u003ccode\u003echmod\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eTo ensure disks automatically mount on VM restart, you should add an entry to the \u003ccode\u003e/etc/fstab\u003c/code\u003e file using the disk's UUID instead of its device name.\u003c/p\u003e\n"],["\u003cp\u003eIt is crucial to keep the \u003ccode\u003e/etc/fstab\u003c/code\u003e file updated to match the current disk configuration and remove disk entries before detaching or snapshotting.\u003c/p\u003e\n"]]],[],null,["# Format and mount a non-boot disk on a Linux VM\n\nLinux\n\n*** ** * ** ***\n\nIf you attached a new, blank disk to your VM, before you can use it you must\nformat and mount the disk. If you attached a disk that already contains data,\nthen you must mount the disk before you can use it.\n\nBefore you begin\n----------------\n\n- If you haven't already, set up [authentication](/compute/docs/authentication). Authentication verifies your identity for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:\n\n Select the tab for how you plan to use the samples on this page: \n\n ### Console\n\n\n When you use the Google Cloud console to access Google Cloud services and\n APIs, you don't need to set up authentication.\n\n ### gcloud\n\n 1.\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n After installation,\n [initialize](/sdk/docs/initializing) the Google Cloud CLI by running the following command:\n\n ```bash\n gcloud init\n ```\n\n\n If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n | **Note:** If you installed the gcloud CLI previously, make sure you have the latest version by running `gcloud components update`.\n 2. [Set a default region and zone](/compute/docs/gcloud-compute#set_default_zone_and_region_in_your_local_client).\n\n ### REST\n\n\n To use the REST API samples on this page in a local development environment, you use the\n credentials you provide to the gcloud CLI.\n 1. [Install](/sdk/docs/install) the Google Cloud CLI. After installation, [initialize](/sdk/docs/initializing) the Google Cloud CLI by running the following command: \n\n ```bash\n gcloud init\n ```\n 2. If you're using an external identity provider (IdP), you must first [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n\n For more information, see\n [Authenticate for using REST](/docs/authentication/rest)\n in the Google Cloud authentication documentation.\n\nConnect to the VM\n-----------------\n\n1. Go to the **VM instances** page.\n\n [Go to the VM instances page](https://console.cloud.google.com/compute/instances)\n2. Click the **SSH** button next to the instance that has the new attached\n disk. The browser opens a terminal connection to the VM.\n\nFormat a non-boot disk on a Linux VM\n------------------------------------\n\n#### Permissions required for this task\n\nTo perform this task, you must have the following\n[permissions](/iam/docs/overview#permissions):\n\n\n- `compute.instances.setMetadata` on the instance, so that you can connect using SSH\n\n\u003cbr /\u003e\n\nIf you are connecting to a VM instance that can run as a service account,\nyou must also grant the `roles/iam.serviceAccountUser` role.\n\n1. In the terminal, use the [symlink](/compute/docs/disks/disk-symlinks)\n created for your attached disk to determine which device to format.\n\n ls -l /dev/disk/by-id/google-*\n\n Unformatted disks don't have additional symlinks with\n `-part`\u003cvar translate=\"no\"\u003eN\u003c/var\u003e in the name. \n\n google-extra-scsi-disk -\u003e ../../sdb\n google-instance-2 -\u003e ../../sda\n google-instance-2-part1 -\u003e ../../sda1\n google-instance-2-part14 -\u003e ../../sda14\n google-instance-2-part15 -\u003e ../../sda15\n google-local-nvme-ssd-0 -\u003e ../../nvme0n1\n google-local-nvme-ssd-1 -\u003e ../../nvme0n2\n\n In this example, the new Persistent Disk was created with the name\n `extra-scsi-disk`. The device name for the new disk is `sdb`.\n2. Format the disk device using the\n [`mkfs` tool](http://manpages.ubuntu.com/manpages/xenial/man8/mkfs.8.html).\n This command **deletes** all data from the specified disk, so make sure\n that you specify the disk device correctly.\n\n You can use any file format that you need, but we recommend a single\n `ext4` file system without a partition table. You can\n [increase the size of your disk](/compute/docs/disks/resize-persistent-disk)\n later without having to modify disk partitions.\n\n To maximize disk performance, use the [recommended formatting options](/compute/docs/disks/optimizing-pd-performance#formatting_parameters)\n with the `-E` flag. It is not necessary to reserve space for the root\n volume on this secondary disk, so specify `-m 0` to use all of the\n available disk space. The following command formats the entire disk with no\n partition table.\n\n \u003cbr /\u003e\n\n ```\n $ sudo mkfs.FILE_SYSTEM_TYPE -m 0 -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/DEVICE_NAME\n \n ```\n\n \u003cbr /\u003e\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eFILE_SYSTEM_TYPE\u003c/var\u003e: the file system type. For example, `ext2`, `ext3`, `ext4`, or `xfs`.\n - \u003cvar translate=\"no\"\u003eDEVICE_NAME\u003c/var\u003e: the device name of the disk that you are formatting. For example, using the example output from the first step, you would use `sdb` for the device name.\n\nMount the disk\n--------------\n\n1. Create a directory that serves as the mount point for the new disk on the VM.\n You can use any directory. The following example creates a directory under\n `/mnt/disks/`.\n\n ```\n $ sudo mkdir -p /mnt/disks/MOUNT_DIR\n ```\n\n Replace \u003cvar translate=\"no\"\u003eMOUNT_DIR\u003c/var\u003e with the directory at which to\n mount disk.\n2. Use the [mount tool](http://manpages.ubuntu.com/manpages/xenial/man8/mount.8.html)\n to mount the disk to the instance, and enable the `discard` option:\n\n ```\n $ sudo mount -o discard,defaults /dev/DEVICE_NAME /mnt/disks/MOUNT_DIR\n ```\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eDEVICE_NAME\u003c/var\u003e: the device name of the disk to mount.\n - \u003cvar translate=\"no\"\u003eMOUNT_DIR\u003c/var\u003e: the directory in which to mount your disk.\n3. Configure read and write permissions on the disk. For this example,\n grant write access to the disk for all users.\n\n ```\n $ sudo chmod a+w /mnt/disks/MOUNT_DIR\n ```\n\n Replace \u003cvar translate=\"no\"\u003eMOUNT_DIR\u003c/var\u003e with the directory where you\n mounted your disk.\n\n### Configure automatic mounting on VM restart\n\nAdd the disk to your `/etc/fstab` file, so that the disk automatically\nmounts again when the VM restarts. On Linux operating systems, the\n*device name* can change with each reboot, but the *device UUID* always points\nto the same volume, even when you move disks between systems. Because of this,\nwe recommend using the device UUID instead of the device name to configure\nautomatic mounting on VM restart.\n| **Note:** If you use Container-Optimized OS, modifications to `/etc/fstab` don't persist across system reboots. To ensure the device is checked and mounted during boot, run the `fsck` and `mount` operations on the disk from your cloud-config's `bootcmd` section. See [Mounting and formatting\n| disks](/container-optimized-os/docs/concepts/disks-and-filesystem#mounting_and_formatting_disks) in the Container-Optimized OS documentation.\n\n1. Create a backup of your current `/etc/fstab` file.\n\n ```\n $ sudo cp /etc/fstab /etc/fstab.backup\n ```\n2. Use the `blkid` command to list the UUID for the disk.\n\n ```\n $ sudo blkid /dev/DEVICE_NAME\n ``` \n\n ```\n /dev/DEVICE_NAME: UUID=\"a9e1c14b-f06a-47eb-adb7-622226fee060\" BLOCK_SIZE=\"4096\"\n TYPE=\"ext4\" PARTUUID=\"593b3b75-108f-bd41-823d-b7e87d2a04d1\"\n ```\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eDEVICE_NAME\u003c/var\u003e: the device name of the disk that you want to automatically mount. If you created a partition table on the disk, specify the partition that you want to mount by adding the suffix appended to the device name. For example, if `sdb` is the device name for the disk, `sdb1` might be the name for the partition.\n3. Open the `/etc/fstab` file in a text editor and create an entry that\n includes the UUID. For example:\n\n ```\n UUID=UUID_VALUE /mnt/disks/MOUNT_DIR FILE_SYSTEM_TYPE discard,defaults,MOUNT_OPTION 0 2\n ```\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eUUID_VALUE\u003c/var\u003e: the UUID of the disk, listed in the output of the previous step\n - \u003cvar translate=\"no\"\u003eMOUNT_DIR\u003c/var\u003e: the directory where you mounted your disk\n - \u003cvar translate=\"no\"\u003eFILE_SYSTEM_TYPE\u003c/var\u003e: the file system type. For example, `ext2`, `ext3`, `ext4`, or `xfs`.\n - \u003cvar translate=\"no\"\u003eMOUNT_OPTION\u003c/var\u003e: specifies what the operating system does if it cannot mount the zonal persistent disk at boot time. For valid values, see **The fourth field** in the [Linux `fstab`\n documentation](https://man7.org/linux/man-pages/man5/fstab.5.html). To let the system boot even if the disk is unavailable, use the `nofail` mount option.\n4. Use the `cat` command to verify that your `/etc/fstab` entries are correct:\n\n ```\n $ cat /etc/fstab\n\n UUID=6B33-A686 /boot/efi vfat defaults 0 0\n UUID=\u003cvar translate=\"no\"\u003eUUID_VALUE\u003c/var\u003e /mnt/disks/\u003cvar translate=\"no\"\u003eMOUNT_DIR\u003c/var\u003e \u003cvar translate=\"no\"\u003eFILE_SYSTEM_TYPE\u003c/var\u003e discard,defaults,\u003cvar translate=\"no\"\u003eMOUNT_OPTION\u003c/var\u003e 0 2\n\n ```\n\nAlways keep the `/etc/fstab` file in sync with the devices that are attached to\na VM. If you want to detach a disk or create a snapshot from the boot disk\nfor a VM, edit the `/etc/fstab` file and remove the entry for the disk. Even\nif you set \u003cvar translate=\"no\"\u003eMOUNT_OPTION\u003c/var\u003e to `nofail` or `nobootwait`,\nremove the entry before you create your boot disk snapshot or detach the disk.\n\nWhat's next\n-----------\n\n- [Configure persistent device names](/compute/docs/disks/set-persistent-device-name-in-linux-vm) for your added disks.\n- Learn how to [resize your persistent disks](/compute/docs/disks/resize-persistent-disk).\n- Learn how to regularly [back up your disks using snapshots](/compute/docs/disks/create-snapshots) to prevent unintended data loss."]]