Créer un déploiement optimisé pour les conteneurs

Cet exemple complet décrit la création d'un déploiement à l'aide d'une machine virtuelle utilisant une image optimisée pour les conteneurs. Pour en savoir plus sur l'utilisation de conteneurs avec Compute Engine, consultez la page Images Compute Engine optimisées pour les conteneurs.

Ce didacticiel vous apprend à effectuer les opérations suivantes :

  1. Créer un manifeste de conteneur simple
  2. Créer une configuration et un modèle qui utilise une image de conteneur
  3. Déployer vos ressources et vérifier que le déploiement a réussi

Créer un manifeste de conteneur

Pour utiliser des conteneurs, vous devez définir un fichier manifeste de conteneur. Le fichier manifeste décrit les propriétés telles que l'image du conteneur, les conteneurs à lancer, les commandes à exécuter au démarrage et les ports à activer.

Créez un fichier nommé container_manifest.yaml avec le contenu suivant :

# 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

Ce fichier manifeste crée un conteneur nommé simple-echo qui utilise l'image de conteneur Hello Application et lance un serveur Echo qui écoute sur le port 8080.

Créer un modèle et une configuration

Vous allez ensuite créer un modèle qui lance une instance de machine virtuelle avec une image optimisée pour les conteneurs. Créez un fichier nommé container_vm.[jinja|py] avec le contenu suivant :

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

Créez le fichier de schéma correspondant, qui applique la structure du modèle :

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

Notez qu'il existe un certain nombre de paramètres définis dans ce modèle, dont :

  • Les variables d'environnement deployment, name et project. Deployment Manager renseigne automatiquement ces variables sans que vous ayez besoin d'intervenir.
  • Les propriétés zone, containerImage et containerManifest, qui seront définies dans la configuration.

Créez un fichier de configuration nommé container_vm.yaml qui se présente comme suit :

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

Veillez à remplacer ZONE_TO_RUN par la zone souhaitée pour votre machine virtuelle. Notez que le fichier a également défini l'image de conteneur à utiliser et le fichier manifeste de conteneur que vous avez créé précédemment.

Déployer votre instance de machine virtuelle

Enfin, déployez votre instance de machine virtuelle à l'aide de la Google Cloud CLI:

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

Une fois le déploiement créé, vous pouvez en afficher les détails. Exemple :

$ 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     -

Vérifier que votre instance est en cours d'exécution

Pour tester le démarrage de votre instance de conteneur, accédez à l'adresse IP externe de la machine virtuelle dans votre navigateur, dans lequel hello world doit s'afficher :

  1. Ajoutez une règle de pare-feu Compute Engine pour pouvoir interroger le trafic de la machine virtuelle via le port 8080 :

    gcloud compute firewall-rules create allow-8080 --allow tcp:8080
    
  2. Récupérez l'adresse IP externe de votre instance :

    $ 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
    ...

    Dans ce cas, l'adresse IP externe est 104.197.8.138.

  3. Dans une fenêtre de navigateur, saisissez l'adresse IP externe et le port 8080 dans la barre de navigation. Par exemple, 104.197.8.138:8080.

    Si l'opération réussit, le message hello world s'affiche.

Supprimer votre déploiement (Facultatif)

Si vous souhaitez réaliser des économies et n'avez plus besoin de votre déploiement, supprimez-le.

gcloud deployment-manager deployments delete my-container-deployment

Étapes suivantes

Pour en savoir plus sur Deployment Manager, consultez les guides de l'utilisateur complets ou la API.

Essayez d'autres didacticiels :