コンテナ最適化デプロイメントを作成する

この例では、コンテナ用に最適化されたイメージを使用する仮想マシンを含むデプロイの作成方法を説明します。Compute Engine でのコンテナの使用について、詳しくはコンテナ用に最適化された Compute Engine イメージをご覧ください。

このチュートリアルでは、以下の手順について説明します。

  1. 単純なコンテナのマニフェストを作成します。
  2. コンテナ イメージを使用する設定とテンプレートを作成します。
  3. リソースをデプロイし、デプロイが成功したことを確認します。

コンテナのマニフェストを作成する

コンテナを使用するには、コンテナのマニフェストを定義する必要があります。マニフェストは、コンテナ イメージ、起動するコンテナ、ブート時に実行するコマンド、有効にするポートなどのプロパティを定義します。

次の内容のファイルを container_manifest.yaml という名前で作成します。

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This is a container manifest, as described here:
#   https://cloud.google.com/compute/docs/containers/container_vms
apiVersion: v1
kind: Pod
metadata:
  name: simple-echo
spec:
  containers:
    - name: simple-echo
      image: gcr.io/google-samples/hello-app:2.0
      imagePullPolicy: Always
      ports:
        - containerPort: 8080
          hostPort: 8080

このマニフェストは hello アプリケーション コンテナ イメージを使用する simple-echo という名前のコンテナを作成し、8080 でリッスンする netcat サーバーを起動します。

テンプレートと構成を作成する

次に、コンテナに最適化されたイメージを使用して仮想マシン インスタンスを起動するテンプレートを作成します。次の内容のファイルを container_vm.[jinja|py] という名前で作成します。

Jinja



{% set COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/' %}
{% set BASE_NAME = env['deployment'] + '-' + env['name'] %}

{% macro GlobalComputeUrl(project, collection, name) -%}
{{ COMPUTE_URL_BASE }}projects/{{ project }}/global/{{ collection }}/{{ name }}
{%- endmacro %}

{% macro ZonalComputeUrl(project, zone, collection, name) -%}
{{ COMPUTE_URL_BASE }}projects/{{ project }}/zones/{{ zone }}/{{ collection }}/{{ name }}
{%- endmacro %}

resources:
- name: {{ BASE_NAME }}
  type: compute.v1.instance
  properties:
    zone: {{ properties['zone'] }}
    machineType: {{ ZonalComputeUrl(env['project'], properties['zone'], 'machineTypes', 'n1-standard-1') }}
    metadata:
      items:
        - key: gce-container-declaration
          value: |
            {{ imports[properties['containerManifest']]|indent(12) }}
    disks:
      - deviceName: boot
        type: PERSISTENT
        autoDelete: true
        boot: true
        initializeParams:
          diskName: {{ BASE_NAME }}-disk
          sourceImage: {{ GlobalComputeUrl('cos-cloud', 'images', properties['containerImage']) }}
    networkInterfaces:
      - accessConfigs:
          - name: external-nat
            type: ONE_TO_ONE_NAT
        network: {{ GlobalComputeUrl(env['project'],  'networks', 'default') }}
    serviceAccounts:
      - email: default
        scopes:
        - https://www.googleapis.com/auth/logging.write
        - https://www.googleapis.com/auth/monitoring.write

Python

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Creates a Container VM with the provided Container manifest."""

COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'

def GlobalComputeUrl(project, collection, name):
  return ''.join([COMPUTE_URL_BASE, 'projects/', project,
                  '/global/', collection, '/', name])

def ZonalComputeUrl(project, zone, collection, name):
  return ''.join([COMPUTE_URL_BASE, 'projects/', project,
                  '/zones/', zone, '/', collection, '/', name])

def GenerateConfig(context):
  """Generate configuration."""

  res = []
  base_name = (context.env['deployment'] + '-' +
               context.env['name'])

  # Properties for the container-based instance.
  instance = {
      'zone': context.properties['zone'],
      'machineType': ZonalComputeUrl(context.env['project'],
                                     context.properties['zone'],
                                     'machineTypes',
                                     'n1-standard-1'),
      'metadata': {
          'items': [{
              'key': 'gce-container-declaration',
              'value': context.imports[
                  context.properties['containerManifest']],
              }]
      },
      'disks': [{
          'deviceName': 'boot',
          'type': 'PERSISTENT',
          'autoDelete': True,
          'boot': True,
          'initializeParams': {
              'diskName': base_name + '-disk',
              'sourceImage': GlobalComputeUrl('cos-cloud',
                                              'images',
                                              context.properties[
                                                  'containerImage'])
              },
      }],
      'networkInterfaces': [{
          'accessConfigs': [{
              'name': 'external-nat',
              'type': 'ONE_TO_ONE_NAT'
              }],
          'network': GlobalComputeUrl(context.env['project'],
                                      'networks',
                                      'default')
      }],
      'serviceAccounts': [{
          'email': 'default',
          'scopes': [
            "https://www.googleapis.com/auth/logging.write",
            "https://www.googleapis.com/auth/monitoring.write"
          ]
      }]
  }
  res.append({
      'name': base_name,
      'type': 'compute.v1.instance',
      'properties': instance
  })
  # Resources to return.
  resources = {
      'resources': res,
  }

  return resources

対応するスキーマ ファイルを作成します。これにより、テンプレートの構造を適用します。

Jinja

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

info:
  title: Container VM
  author: Google Inc.
  description: Creates a Container VM with the provided Container manifest.

required:
  - zone
  - containerImage
  - containerManifest

properties:
  zone:
    description: Zone in which this VM will run
    type: string
  containerImage:
    description: Name of the Google Cloud Container VM Image
    type: string
  containerManifest:
    description: String containing the Container Manifest in YAML
    type: string

Python

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

info:
  title: Container VM
  author: Google Inc.
  description: Creates a Container VM with the provided Container manifest.

required:
  - zone
  - containerImage
  - containerManifest

properties:
  zone:
    description: Zone in which this VM will run
    type: string
  containerImage:
    description: Name of the Google Cloud Container VM Image
    type: string
  containerManifest:
    description: String containing the Container Manifest in YAML
    type: string

このテンプレートで定義される多数のパラメータには、次のようなものが含まれることに注意してください。

  • deploymentnameproject 環境変数。Deployment Manager が自動的に変数に値を設定します。何も操作を行う必要はありません。
  • zonecontainerImagecontainerManifest プロパティ。これらのプロパティは構成に定義します。

次のような構成ファイルを container_vm.yaml という名前で作成します。

Jinja

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

imports:
- path: ../../common/container_manifest.yaml
  name: container_manifest
- path: container_vm.jinja

resources:
  - name: my-container-vm
    type: container_vm.jinja
    properties:
      zone: ZONE_TO_RUN
      containerImage: family/cos-stable
      containerManifest: container_manifest

Python

# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

imports:
- path: ../../common/container_manifest.yaml
  name: container_manifest
- path: container_vm.py

resources:
  - name: my-container-vm
    type: container_vm.py
    properties:
      zone: ZONE_TO_RUN
      containerImage: family/cos-stable
      containerManifest: container_manifest

必ず ZONE_TO_RUN を仮想マシンに設定するゾーンで置き換えてください。このファイルは、使用するコンテナ イメージと先に作成したコンテナ マニフェストも定義していることに注意してください。

仮想マシン インスタンスをデプロイする

最後に、Google Cloud CLI を使用して、仮想マシン インスタンスをデプロイします。

gcloud deployment-manager deployments create my-container-deployment \
  --config container_vm.yaml

デプロイが作成されると、その詳細を見ることができます。次に例を示します。

$ gcloud deployment-manager deployments describe my-container-deployment
creationTimestamp: '2015-04-02T12:24:31.645-07:00'
fingerprint: ''
id: '8602410885927938432'
manifest: https://www.googleapis.com/deploymentmanager/v2/projects/myproject/global/deployments/my-container-deployment/manifests/manifest-1428002671645
name: my-container-deployment
state: DEPLOYED
resources:
NAME                                     TYPE                 ID                   UPDATE_STATE  ERRORS
my-container-deployment-my-container-vm  compute.v1.instance  3775082612632070557  COMPLETED     -

インスタンスの稼働を確認する

コンテナ インスタンスが起動したことを確認するため、ブラウザで仮想マシンの外部 IP アドレスにアクセスすると hello world と表示されます。

  1. ポート 8080 を介して仮想マシン上のトラフィックを照会できるように、Compute Engine のファイアウォール ルールを追加します。

    gcloud compute firewall-rules create allow-8080 --allow tcp:8080
    
  2. インスタンスの外部 IP アドレスを取得します。

    $ gcloud compute instances describe my-container-deployment-my-container-vm
    ...
    name: my-container-vm-my-container-deployment
    networkInterfaces:
    - accessConfigs:
      - kind: compute#accessConfig
        name: external-nat
        natIP: 104.197.8.138
        type: ONE_TO_ONE_NAT
      name: nic0
      network: https://www.googleapis.com/compute/v1/projects/myproject/global/networks/default
      networkIP: 10.240.97.220
    scheduling:
      automaticRestart: true
      onHostMaintenance: MIGRATE
    selfLink: https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/instances/my-container-deployment-my-container-vm
    status: RUNNING
    tags:
      fingerprint: 42WmSpB8rSM=
    zone: https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a
    ...

    この場合の外部 IP アドレスは 104.197.8.138 です。

  3. ブラウザ ウィンドウで、ブラウザバーに外部 IP アドレスとポート 8080 を入力します。例: 104.197.8.138:8080

    正常な場合、hello world というメッセージが表示されます。

(省略可)デプロイを削除する

作成したデプロイの必要がなくなり、費用を節約したい場合は、デプロイを削除します。

gcloud deployment-manager deployments delete my-container-deployment

次のステップ

Deployment Manager の詳細について、Complete ユーザーガイドまたは API で確認する。

他のチュートリアルを試してみます。