[Yandex Cloud documentation](../../../index.md) > [Tutorials](../../index.md) > [Basic infrastructure](../../infrastructure/index.md) > Tools > [Running a Docker image on a VM](index.md) > Terraform

# Running a Docker image on a VM using Terraform

To run a [Docker image on a VM](index.md) using a [Yandex Container Registry](../../../container-registry/index.md) registry via Terraform:

1. [Get your cloud ready](#before-begin).
1. [Create your infrastructure](#deploy).
1. [Build and push the Docker image to Container Registry](#create-image).
1. [Push the Docker image to the VM](#run).
1. [Check the result](#check-result).

If you no longer need the resources you created, [delete them](#clear-out).


## Get your cloud ready {#before-begin}

Sign up for Yandex Cloud and create a [billing account](../../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../../billing/quickstart/index.md) and [link](../../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../../resource-manager/concepts/resources-hierarchy.md).


### Required paid resources {#paid-resources}

The infrastructure support cost includes:
* Fee for a continuously running VM (see [Yandex Compute Cloud pricing](../../../compute/pricing.md)).
* Fee for a dynamic or static [public IP address](../../../vpc/concepts/address.md#public-addresses) (see [Yandex Virtual Private Cloud pricing](../../../vpc/pricing.md)).
* Fee for storing a Docker image in the registry and outgoing traffic (see [Yandex Container Registry pricing](../../../container-registry/pricing.md)).


### Create an SSH key pair {#create-ssh}

Prepare an SSH key for [VM access](../../../compute/operations/vm-connect/ssh.md).

{% list tabs group=operating_system %}

- Linux/macOS {#linux-macos}

  1. Open the terminal.
  1. Use the `ssh-keygen` command to create a new key:
  
      ```bash
      ssh-keygen -t ed25519 -C "<optional_comment>"
      ```
  
      You can specify an empty string in the `-C` parameter to avoid adding a comment, or you may not specify the `-C` parameter at all: in this case, a default comment will be added.
  
      After running this command, you will be prompted to specify the name and path to the key files, as well as enter the password for the private key. If you only specify the name, the key pair will be created in the current directory. The public key will be saved in a file with the `.pub` extension, while the private key, in a file without extension.
  
      By default, the command prompts you to save the key under the `id_ed25519` name in the following directory: `/home/<username>/.ssh`. If there is already an SSH key named `id_ed25519` in this directory, you may accidentally overwrite it and lose access to the resources it is used in. Therefore, you may want to use unique names for all SSH keys.

- Windows 10/11 {#windows}

  If you do not have [OpenSSH](https://en.wikipedia.org/wiki/OpenSSH) installed yet, follow this [guide](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse?tabs=gui) to install it.
  
  1. Run `cmd.exe` or `powershell.exe` (make sure to update PowerShell before doing so).
  1. Use the `ssh-keygen` command to create a new key:
  
      ```shell
      ssh-keygen -t ed25519 -C "<optional_comment>"
      ```
  
      You can specify an empty string in the `-C` parameter to avoid adding a comment, or you may not specify the `-C` parameter at all: in this case, a default comment will be added.
  
      After running this command, you will be prompted to specify the name and path to the key files, as well as enter the password for the private key. If you only specify the name, the key pair will be created in the current directory. The public key will be saved in a file with the `.pub` extension, while the private key, in a file without extension.
  
      By default, the command prompts you to save the key under the `id_ed25519` name in the following folder: `C:\Users\<username>/.ssh`. If there is already an SSH key named `id_ed25519` in this directory, you may accidentally overwrite it and lose access to the resources it is used in. Therefore, you may want to use unique names for all SSH keys.

- Windows 7/8 {#windows7-8}

  Create keys using the PuTTY app:
  
  1. [Download](https://www.putty.org) and install PuTTY.
  1. Add the folder with PuTTY to the `PATH` variable:
  
      1. Click **Start** and type **Change system environment variables** in the Windows search bar.
      1. Click **Environment Variables...** at the bottom right.
      1. In the window that opens, find the `PATH` parameter and click **Edit**.
      1. Add your folder path to the list.
      1. Click **OK**.
  
  1. Launch the PuTTYgen app.
  1. Select **EdDSA** as the pair type to generate. Click **Generate** and move the cursor in the field above it until key creation is complete.
  
      ![ssh_generate_key](../../../_assets/compute/ssh-putty/ssh_generate_key.png)
  
  1. In **Key passphrase**, enter a strong password. Enter it again in the field below.
  1. Click **Save private key** and save the private key. Do not share its key phrase with anyone.
  1. Click **Save public key** and save the public key to a file named `<key_name>.pub`.

{% endlist %}

{% note warning %}

Store your private key securely, as you will not be able to connect to the VM without it.

{% endnote %}


### Install and configure Docker {#configure-docker}

{% list tabs group=operating_system %}

- Linux {#linux}

    1. Install Docker Engine. Use [this guide](https://docs.docker.com/engine/install/#supported-platforms) to install and run Docker for your operating system.

    1. After the installation is complete, add the current user to the `docker` group:

        ```bash
        sudo groupadd docker
        sudo usermod -aG docker $USER
        newgrp docker
        ```

    For groups to update successfully, you may need to log back into the OS or reboot the computer.

    For information on additional Docker settings in Linux, see [this developer guide](https://docs.docker.com/engine/install/linux-postinstall/).

    If you are working on a device with a GUI, you can also [install](https://docs.docker.com/desktop/install/linux-install/) Docker Desktop for Linux.

- macOS {#macos}

  [Download](https://docs.docker.com/get-docker/) and install the Docker Desktop distribution for macOS. For more information, see [this developer guide](https://docs.docker.com/desktop/install/mac-install/).

- Windows {#windows}

    1. [Download](https://docs.docker.com/get-docker/) and install the Docker Desktop distribution for Windows.

    1. After the installation is complete, add the current user to the `docker-users` group:

        1. Run **Computer Management** as administrator:

            ```powershell
            compmgmt.msc
            ```
        
        1. Expand the **(Local) Computer Management** menu, then go **Utilities** → **Local Users and Groups** → **Groups** and open the `docker-users` group.
        1. Click **Add** and add the required user to the group.
        1. Click **OK**.
    1. Run Docker Desktop and make sure the app's status is `running`.

    For information on additional Docker settings in Windows, see [this developer guide](https://docs.docker.com/desktop/install/windows-install/).

{% endlist %}


## Create your infrastructure {#deploy}

With [Terraform](https://www.terraform.io/), you can quickly create a cloud infrastructure in Yandex Cloud and manage it using configuration files. These files store the infrastructure description written in HashiCorp Configuration Language (HCL). If you change the configuration files, Terraform automatically detects which part of your configuration is already deployed, and what should be added or removed.

Terraform is distributed under the [Business Source License](https://github.com/hashicorp/terraform/blob/main/LICENSE). The [Yandex Cloud provider for Terraform](https://github.com/yandex-cloud/terraform-provider-yandex) is distributed under the [MPL-2.0](https://www.mozilla.org/en-US/MPL/2.0/) license.

For more information about the provider resources, see the guides on the [Terraform](https://www.terraform.io/docs/providers/yandex/index.html) website or [its mirror](../../../terraform/index.md).

To create an infrastructure using Terraform:
1. [Install Terraform](../terraform-quickstart.md#install-terraform), [get the authentication credentials](../terraform-quickstart.md#get-credentials), and specify the Yandex Cloud provider source (see [Configure your provider](../terraform-quickstart.md#configure-provider), Step 1).
1. Prepare your infrastructure description files:

    {% list tabs group=infrastructure_description %}

    - Ready-made configuration {#ready}

      1. Clone the [repository](https://github.com/yandex-cloud-examples/yc-run-docker-on-vm) with configuration files:

          ```bash
          git clone https://github.com/yandex-cloud-examples/yc-run-docker-on-vm.git
          ```

      1. Navigate to the repository directory. Make sure it contains the `run-docker-on-vm-config.tf` file with the new infrastructure configuration.

    - Manually {#manual}

      1. Create a folder for the infrastructure description file.
      1. In the folder, create a configuration file named `run-docker-on-vm.tf`:

          {% cut "Contents of the run-docker-on-vm.tf file" %}

          ```hcl
          # Declaring variables for confidential parameters
          
          locals {
            zone             = "<default_availability_zone>"
            username         = "<VM_user_name>"
            ssh_key_path     = "<path_to_public_SSH_key>"
            target_folder_id = "<ID_of_folder_to_place_VM_in>"
            registry_name    = "<registry_name>"
            sa_name          = "<service_account_name>"
            network_name     = "<cloud_network_name>"
            subnet_name      = "<subnet_name>"
            vm_name          = "<VM_name>"
            image_id         = "<image_ID>"
          }
          
          # Configuring a provider
          
          terraform {
            required_providers {
              yandex    = {
                source  = "yandex-cloud/yandex"
                version = ">= 0.47.0"
              }
            }
          }
          
          provider "yandex" {
            zone = local.zone
          }
          
          # Creating a Container Registry repository
          
          resource "yandex_container_registry" "my-registry" {
            name       = local.registry_name
            folder_id  = local.target_folder_id
          }
          
          # Creating a service account
          
          resource "yandex_iam_service_account" "registry-sa" {
            name      = local.sa_name
            folder_id = local.target_folder_id
          }
          
          # Assigning roles to a service account
          
          resource "yandex_resourcemanager_folder_iam_member" "registry-sa-role-images-puller" {
            folder_id = local.target_folder_id
            role      = "container-registry.images.puller"
            member    = "serviceAccount:${yandex_iam_service_account.registry-sa.id}"
          }
          
          # Creating a cloud network
          
          resource "yandex_vpc_network" "docker-vm-network" {
            name = local.network_name
          }
          
          # Creating a subnet
          
          resource "yandex_vpc_subnet" "docker-vm-network-subnet-a" {
            name           = local.subnet_name
            zone           = local.zone
            v4_cidr_blocks = ["192.168.1.0/24"]
            network_id     = yandex_vpc_network.docker-vm-network.id
          }
          
          # Creating a boot disk
          
          resource "yandex_compute_disk" "boot-disk" {
            name     = "bootvmdisk"
            type     = "network-hdd"
            zone     = local.zone
            size     = "10"
            image_id = local.image_id
          }
          
          # Creating a VM instance
          
          resource "yandex_compute_instance" "docker-vm" {
            name               = local.vm_name
            platform_id        = "standard-v3"
            zone               = local.zone
            service_account_id = "${yandex_iam_service_account.registry-sa.id}"
          
            resources {
              cores  = 2
              memory = 2
            }
          
            boot_disk {
              disk_id = yandex_compute_disk.boot-disk.id
            }
          
            network_interface {
              subnet_id = "${yandex_vpc_subnet.docker-vm-network-subnet-a.id}"
              nat       = true
            }
          
            metadata = {
              user-data = "#cloud-config\nusers:\n  - name: ${local.username}\n    groups: sudo\n    shell: /bin/bash\n    sudo: 'ALL=(ALL) NOPASSWD:ALL'\n    ssh_authorized_keys:\n      - ${file("${local.ssh_key_path}")}"
            }
          }
          ```

          {% endcut %}

    {% endlist %}

    Learn more about the properties of Terraform resources in the relevant Terraform guides:

    * [Registry](../../../container-registry/concepts/registry.md): [yandex_container_registry](../../../terraform/resources/container_registry.md)
    * [Service account](../../../iam/concepts/users/service-accounts.md): [yandex_iam_service_account](../../../terraform/resources/iam_service_account.md)
    * [Folder access binding](../../../iam/concepts/access-control/index.md#access-bindings): [yandex_resourcemanager_folder_iam_member](../../../terraform/resources/resourcemanager_folder_iam_member.md)
    * [Network](../../../vpc/concepts/network.md#network): [yandex_vpc_network](../../../terraform/resources/vpc_network.md)
    * [Subnets](../../../vpc/concepts/network.md#subnet): [yandex_vpc_subnet](../../../terraform/resources/vpc_subnet.md)
    * [Disk](../../../compute/concepts/disk.md): [yandex_compute_disk](../../../terraform/resources/compute_disk.md)
    * [VM instance](../../../compute/concepts/vm.md): [yandex_compute_instance](../../../terraform/resources/compute_instance.md)

1. Under `locals`, set the following parameters for the new resources:
    * `zone`: [Availability zone](../../../overview/concepts/geo-scope.md) the VM will reside in.
    * `username`: VM user name.
    * `ssh_key_path`: Path to the public SSH key to authenticate the user on the VM. For more information, see [Creating an SSH key pair](../../../compute/operations/vm-connect/ssh.md#creating-ssh-keys).
    * `target_folder_id`: [ID of the folder](../../../resource-manager/operations/folder/get-id.md) to host the VM.
    * `registry_name`: Name of the registry in Container Registry.
    * `sa_name`: Service account name.
    * `network_name`: Name of the cloud network.
    * `subnet_name`: Subnet name.
    * `vm_name`: VM name.
    * `image_id`: ID of the image to create the VM from. For more information, see [Getting a list of public images](../../../compute/operations/images-with-pre-installed-software/get-list.md).

1. Create the resources:

    1. In the terminal, navigate to the configuration file directory.
    1. Make sure the configuration is correct using this command:
    
       ```bash
       terraform validate
       ```
    
       If the configuration is valid, you will get this message:
    
       ```bash
       Success! The configuration is valid.
       ```
    
    1. Run this command:
    
       ```bash
       terraform plan
       ```
    
       You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.
    1. Apply the configuration changes:
    
       ```bash
       terraform apply
       ```
    
    1. Type `yes` and press **Enter** to confirm the changes.

After creating the infrastructure, [build and push the Docker image to Container Registry](#create-image).


## Build and push the Docker image to Container Registry {#create-image}

The example below is for MacOS and Linux. To run it on Windows, [check the details on working with Bash in Microsoft Windows](../../../overview/concepts/console-syntax-guide.md).

1. Open the terminal.
1. To make command execution easier, add the following variables:

    * Username and your VM's public IP to the `${PUBLIC_IP}` variable:

        ```bash
        export PUBLIC_IP=<username>@<VM_public_IP_address>
        ```

    * ID of the previously created registry in `crpc9qeoft23********` format to the `${REGISTRY_ID}` variable:

        ```bash
        export REGISTRY_ID=<registry_ID>
        ```

1. Authenticate as yourself:

    {% list tabs group=registry_auth %}

    - OAuth token {#oauth-token}

      {% note info "OAuth token authentication is deprecated" %}
      
      This authentication method will no longer be supported. Consider using [IAM tokens](../../../iam/concepts/authorization/iam-token.md) or [API keys](../../../iam/concepts/authorization/api-key.md).
      
      {% endnote %}

      1. If you do not have an OAuth token yet, get one by following [this link](https://oauth.yandex.com/authorize?response_type=token&client_id=1a6990aa636648e9b2ef855fa7bec2fb).
      1. Run this command:

          ```bash
          echo <OAuth_token> | docker login --username oauth --password-stdin cr.yandex
          ```

          Result:

          ```text
          Login Succeeded
          ```

    - IAM token {#iam-token}

      {% note info %}

      The IAM token has a short [lifetime](../../../iam/concepts/authorization/iam-token.md#lifetime) of up to 12 hours. This makes it a good method for applications that automatically request an IAM token.

      {% endnote %}

      1. [Get](../../../iam/operations/iam-token/create.md) an IAM token.
      1. Run this command:

          ```bash
          yc iam create-token | docker login --username iam --password-stdin cr.yandex
          ```

          Result:

          ```text
          ...
          Login Succeeded
          ```

    - Docker credential helper {#docker}

      1. If you do not have a CLI profile yet, [create one](../../../cli/quickstart.md#initialize).
      1. Configure Docker to use `docker-credential-yc`:

          ```bash
          yc container registry configure-docker
          ```

          Result:

          ```text
          Credential helper is configured in '/home/<user>/.docker/config.json'
          ```

          The current user’s profile stores the settings.

          {% note warning %}

          The credential helper only works if you use Docker without `sudo`. To learn how to configure Docker to run under the current user without `sudo`, see the [official documentation](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user).

          {% endnote %}

      1. Make sure that Docker is configured.

          The following line must appear in the `/home/<user>/.docker/config.json` configuration file:

          ```json
          "cr.yandex": "yc"
          ```

      1. You can now use Docker, for example, to [push Docker images](../../../container-registry/operations/docker-image/docker-image-push.md). You do not need to run the `docker login` command for that.

    {% endlist %}

1. Create a file called Dockerfile:

    ```bash
    touch .dockerfile
    ```

1. Open Dockerfile in a text editor, e.g.:

    ```bash
    nano .dockerfile
    ```

1. Add the lines below to the file:

    ```text
    FROM ubuntu:latest
    CMD echo "Hi, I'm inside"
    ```

1. Build the Docker image:

    ```bash
    docker build . -t cr.yandex/${REGISTRY_ID}/ubuntu:hello -f .dockerfile
    ```

    Result:

    ```text
    ...
    Successfully built b68ee9b6b1af
    Successfully tagged cr.yandex/crpmnjr98tm5********/ubuntu:hello
    ```

1. Push the built Docker image to Container Registry:

    ```bash
    docker push cr.yandex/${REGISTRY_ID}/ubuntu:hello
    ```

    Result:

    ```text
    The push refers to repository [cr.yandex/crpc9qeoft23********/ubuntu]
    cc9d18e90faa: Pushed
    0c2689e3f920: Pushed
    47dde53750b4: Pushed
    hello: digest: sha256:42068479274f1d4c7ea095482430dcba24dcfe8c23ebdf6d32305928******** size: 943
    ```


## Push the Docker image to the VM {#run}

1. [Use SSH to connect](../../../compute/operations/vm-connect/ssh.md#vm-connect) to the VM.
1. On the VM, [install and configure](../../../container-registry/operations/configure-docker.md) Docker.
1. [Authenticate](../../../compute/operations/vm-connect/auth-inside-vm.md#auth-inside-vm) under the service account tied to the machine:

    ```bash
    curl --header Metadata-Flavor:Google 169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token | \
    cut -f1 -d',' | \
    cut -f2 -d':' | \
    tr -d '"' | \
    docker login --username iam --password-stdin cr.yandex
    ```

    Result:

    ```text
    Login Succeeded
    ```

1. To make it easier to run commands, add the ID of the registry you created earlier to the `${REGISTRY_ID}` variable:

    ```bash
    export REGISTRY_ID=<registry_ID>
    ```

1. Download the Docker image to the VM:

    ```bash
    docker pull cr.yandex/${REGISTRY_ID}/ubuntu:hello
    ```

    Result:

    ```text
    hello: Pulling from crpc9qeoft23********/ubuntu
    6a5697faee43: Pulling fs layer
    ba13d3bc422b: Pulling fs layer
    ...
    Digest: sha256:42068479274f1d4c7ea095482430dcba24dcfe8c23ebdf6d32305928********
    Status: Downloaded newer image for cr.yandex/crpc9qeoft23********/ubuntu:hello
    cr.yandex/crpc9qeoft23********/ubuntu:hello
    ```


## Check the result {#check-out}

Run the Docker image on the VM:

```bash
docker run cr.yandex/${REGISTRY_ID}/ubuntu:hello
```

Result:

```text
Hi, I'm inside
```


## How to delete the resources you created {#clear-out}

To delete the infrastructure and stop paying for the resources you created:

1. Open the `run-docker-on-vm-config.tf` file and delete your infrastructure description from it.
1. Apply the changes:

    1. In the terminal, navigate to the configuration file directory.
    1. Make sure the configuration is correct using this command:
    
       ```bash
       terraform validate
       ```
    
       If the configuration is valid, you will get this message:
    
       ```bash
       Success! The configuration is valid.
       ```
    
    1. Run this command:
    
       ```bash
       terraform plan
       ```
    
       You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.
    1. Apply the configuration changes:
    
       ```bash
       terraform apply
       ```
    
    1. Type `yes` and press **Enter** to confirm the changes.

## See also {#see-also}

* [Running a Docker image on a VM using the management console, CLI, and API](console.md)