docker 容器完成后如何自动关闭 GCE VM?

How to automatically shutdown a GCE VM after the docker container finishes?

我有一个批处理过程(打包在 docker 图像中)需要每天 运行 在云端某处执行一次。 Google Compute Engine (GCE) 似乎是一个简单易用的选项,它的容器优化 OS VM。这非常有效,除了我 找不到在 docker 容器完成 后自动关闭 VM 的简单方法。您可以指定一个启动脚本,但 GCE 似乎在容器启动之前执行它,所以在那里做 docker wait 是行不通的。我不在乎它是 docker 优化的 VM。其他基本的 Linux OSs(如 Debian)之一很好,只要它可以很容易地用 docker.

设置

是否有一种简单的方法可以在 docker 容器完成后自动关闭 Linux 虚拟机?

根据问题评论中的要求,Python 用于关闭 Compute Engine 实例的代码。

注意:Google Compute Engine Metadata 服务器可以在脚本中提供 REPLACE 变量。此外,您无需等待结果被 STOPPED,只需验证脚本没有失败即可。您也可以在本地测试此程序。

有关 COS 容器凭据的提示,请参阅此 。下面的程序使用 ADC(应用程序默认凭据)。

from pprint import pprint
import time

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()

service = discovery.build('compute', 'v1', credentials=credentials)

# Project ID for this request.
project = 'REPLACE_WITH_PROJECT_ID'

# The name of the zone for this request.
zone = 'REPLACE_WITH_COMPUTE_ENGINE_ZONE'

# Name of the instance resource to start.
instance = 'REPLACE_WITH_COMPUTE_ENGINE_INSTANCE_NAME'

request = service.instances().stop(project=project, zone=zone, instance=instance)
response = request.execute()

pprint(response)

print('Waiting for operation to finish...')
print('Name:', response['name'])

while True:
    result = service.zoneOperations().get(
        project=project,
        zone=zone,
        operation=response['name']).execute()

    print('status:', result['status'])

    if result['status'] == 'DONE':
        print("done.")
        break;

    if 'error' in result:
        raise Exception(result['error'])

    time.sleep(1)

我可以通过简单地在 Compute Engine 上部署一个常规的 Debian VM 来避免从 docker 容器中关闭 VM。步骤:

首先,在 Compute Engine 上创建一个 Debian VM 并传递安装 docker 的启动脚本。启动脚本:

#!/bin/bash
# Install docker. Taken from the docker documentation.
# Passed into the gcloud command that creates the VM instance.
apt-get -y remove docker docker-engine docker.io containerd runc
apt-get update
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian \
  $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io
echo Done installing docker.

其次,将启动脚本替换为拉取 运行 图像 docker 的脚本:

#!/bin/bash
...
# Get authorization to pull from artifact registry
gcloud -q auth configure-docker us-east1-docker.pkg.dev
# Pull the image and run it, then shutdown.
docker pull $image
docker rm $container
docker run -v $vol_ini:$app_ini -v $vol_log:$app_log --name $container $image
shutdown now

现在可以安排此 VM 每天 运行 docker 映像并自动关闭。