我想创建一个带有 Wordpress 图像的实例容器。
我可以使用以下方法创建容器:
gcloud compute instances create-with-container test-container --container-image=registry.hub.docker.com/library/wordpress --tags=http-server --zone=europe-west1-b --machine-type=n1-standard-1
我还如何传递图像的环境变量?
-e WORDPRESS_DB_HOST=10.0.0.0
-e WORDPRESS_DB_USER="test"
-e WORDPRESS_DB_PASSWORD="test"
-e WORDPRESS_DB_NAME="test"
-e WORDPRESS_TABLE_PREFIX="wp_"
我可以使用 create-with-container 语句中的标志来执行此操作吗?如何执行?
答案1
docker run
与允许传递环境变量的命令类似:
$ docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
--env , -e Set environment variables
--env-file Read in a file of environment variables
gcloud compute instances create-with-container
支持类似的功能和命令行参数:
$ gcloud compute instances create-with-container INSTANCE_NAMES [INSTANCE_NAMES …]
--container-env=[KEY=VALUE, …,…]
Declare environment variables KEY with value VALUE passed to container.
Only the last value of KEY is taken when KEY is repeated more than once.
Values, declared with --container-env flag override those with the same KEY from file, provided in --container-env-file.
--container-env-file=CONTAINER_ENV_FILE
Declare environment variables in a file.
Values, declared with --container-env flag override those with the same KEY from file.
File with environment variables in format used by docker (almost). This means:
• Lines are in format KEY=VALUE.
• Values must contain equality signs.
• Variables without values are not supported (this is different from docker format).
• If # is first non-whitespace character in a line the line is ignored as a comment.
• Lines with nothing but whitespace are ignored.
例如
CloudShell:$ gcloud compute instances create-with-container nginx-container --container-image gcr.io/cloud-marketplace/google/nginx1:1.14 --zone=europe-west3-c --tags=nginx --container-env=MYVAR1=myval1,MYVAR2=myval2
或者,你可以创建如下的 shell 脚本create-vm.sh
:
#!/bin/bash
set -x
gcloud compute instances create-with-container nginx-container --container-image gcr.io/cloud-marketplace/google/nginx1:1.14 --zone=europe-west3-c --tags=nginx --container-env=MYVAR1=$1,MYVAR2=$2
使用命令行传递的变量启动它:
CloudShell:$ chmod +x create-vm.sh
CloudShell:$ ./create-vm.sh myval1 myval2
然后通过 SSH 连接到新创建的 VM 实例nginx-container
并检查 Docker 容器内的变量:
nginx-container:$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS NAMES
8637cbacf2e1 gcr.io/cloud-marketplace/google/nginx1:1.14 "/usr/local/bin/dock…" 4 minutes ago Up 4 minutes klt-nginx-container-ikrz
nginx-container:$ sudo docker exec 8637cbacf2e1 printenv MYVAR1 MYVAR2
myval1
myval2
Docker 文档 > 命令行参考 > Docker CLI (docker) > docker run
开发者工具 > Cloud SDK:命令行界面 > 文档 > 参考 > gcloud compute instance create-with-container