簡體   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