繁体   English   中英

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

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

我有一个批处理过程(打包在 docker 图像中)需要每天在云端某处运行一次。 谷歌计算引擎 (GCE) 似乎是一个简单易用的选项,它具有容器优化的操作系统虚拟机。 这工作得很好,除了我找不到在 docker 容器完成后自动关闭 VM 的简单方法 您可以指定一个启动脚本,但 GCE 似乎在容器启动之前执行它,所以docker wait在那里不起作用。 我不在乎它是一个 docker 优化的虚拟机。 其他基本 Linux 操作系统之一(如 Debian)也可以,只要它可以轻松地使用 docker 进行设置即可。

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

根据问题评论中的要求,Python 代码用于关闭计算引擎实例。

注意:Google Compute Engine元数据服务器可以在脚本中提供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 映像并自动关闭。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM