简体   繁体   English

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

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

I have a batch process (packaged in a docker image) that needs to run once a day somewhere in the cloud.我有一个批处理过程(打包在 docker 图像中)需要每天在云端某处运行一次。 Google Compute Engine (GCE) seems like a simple and easy to use option for this with it's container-optimized OS VM.谷歌计算引擎 (GCE) 似乎是一个简单易用的选项,它具有容器优化的操作系统虚拟机。 This works really well, except that I cannot find an easy way to automatically shutdown the VM after the docker container finishes .这工作得很好,除了我找不到在 docker 容器完成后自动关闭 VM 的简单方法 You can specify a startup script but GCE seems to execute it before the container is started, so doing docker wait there does not work.您可以指定一个启动脚本,但 GCE 似乎在容器启动之前执行它,所以docker wait在那里不起作用。 I don't care that it's a docker-optimized VM.我不在乎它是一个 docker 优化的虚拟机。 One of the other basic Linux OSs (like Debian) is fine as long as it can easily be setup with docker.其他基本 Linux 操作系统之一(如 Debian)也可以,只要它可以轻松地使用 docker 进行设置即可。

Is there an easy way of automatically shutting a Linux VM down after the docker container finishes?在 docker 容器完成后,是否有一种简单的方法可以自动关闭 Linux 虚拟机?

As requested in the question comments, Python code to shutdown a Compute Engine instance.根据问题评论中的要求,Python 代码用于关闭计算引擎实例。

Note: The Google Compute Engine Metadata server can provide the REPLACE variables in the script.注意:Google Compute Engine元数据服务器可以在脚本中提供REPLACE变量。 Also, you do not need to wait for the results to be STOPPED, just verify that the script did not fail.此外,您无需等待结果被 STOPPED,只需验证脚本没有失败即可。 You can test this program locally as well.您也可以在本地测试该程序。

See this answer for tips on COS container credentials.有关 COS 容器凭证的提示,请参阅此答案 The program below uses ADC (Application Default Credentials).下面的程序使用 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)

I was able to avoid shutting down the VM from within the docker container by simply deploying a regular Debian VM on Compute Engine.通过简单地在 Compute Engine 上部署常规 Debian VM,我能够避免从 docker 容器中关闭 VM。 Steps:脚步:

First, create a Debian VM on Compute Engine and pass a startup script that installs docker. Startup script:首先,在 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.

Second, replace that startup script with one that pulls and runs the docker image:其次,将启动脚本替换为拉取并运行 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

Now this VM can be scheduled to run the docker image on a daily basis and automatically shut itself down.现在可以安排此 VM 每天运行 docker 映像并自动关闭。

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

相关问题 如何暂停/恢复 GCE VM - How to suspend/resume GCE VM Cloud Run Docker 容器 - 如何访问 VM 上的数据库? - Cloud Run Docker container - How to access DB on VM? 如何将数据从 GCS 传输到 Colab GCE VM? - How to transfer data from GCS to Colab GCE VM? GCE抢占式实例如何自动重启? - How do I automatically restart a GCE preemptible instance? 如何为自定义 docker 运行命令设置 Google VM 容器配置? - How do I setup Google VM container configuration for a custom docker run command? azure 应用程序服务,一段时间后没有暴露端口的容器关闭 - azure app service, container without exposed port shutdown after a while GCE - 我们无法连接到端口 22 上的虚拟机 - GCE - We are unable to connect to the VM on port 22 如何将文件从 GCE VM 上的 R Studio 服务器保存到 Google Cloud Bucket? 可能的设置问题 - How to save files from R Studio-server on GCE VM to a Google Cloud Bucket? Possible settings issue 如何从 GCE 实例中的 Container-optimized OS 获取启动脚本日志? - How do I get startup-script logs from Container-optimized OS in a GCE instance? 部署到 VM(docker、kube.netes)后,Nextjs 应用程序未在端口上运行 - Nextjs app not running on port after deploying to VM (docker, kubernetes)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM