tjun月1日記

なんでもいいので毎月書きたい

独自imageのdocker-machineをGCEで利用する

独自のdocker imageを作ってGoogleCloudPlatform(以下GCP)上のContainer Registryに登録して、GCE(Google Compute Engine)で動かすやり方です。

Dockerfileを元にimageを作ってContainer Registryにpushするまで

以下の例ではcontainer registryのサーバはアジアにしてます。

NAME=myapp
VERSION=1
APPID=<gcpのprojectID>

docker build -t ${NAME}:${VERSION} .
docker tag ${NAME}:${VERSION} asia.gcr.io/$(APPID)/${NAME}:${VERSION}
docker tag asia.gcr.io/$(APPID)/${NAME}:${VERSION} asia.gcr.io/$(APPID)/${NAME}:latest

gcloud --project=$(APPID) docker --server=asia.gcr.io -- push asia.gcr.io/$(APPID)/${NAME}

GCEをdocker-machineとして起動する

以下のように、docker-machineを作る際にdriverとしてgoogleを指定します。 その他のoptionは Google Compute Engine | Docker Documentation を参考に設定します。

docker-machine create \
    --driver google \
    --google-project $(APPID) \
    --google-preemptible \
    --google-zone asia-northeast1-a \
    --google-machine-type n1-highcpu-8 \
    --google-disk-size 300 \
    --google-disk-type pd-ssd \
    --google-machine-image https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/ubuntu-1604-xenial-v20170815a \
    --google-scopes https://www.googleapis.com/auth/devstorage.read_write \
    ${NAME} 

作ったdocker-machineを確認する

$ docker-machine ls
NAME             ACTIVE   DRIVER   STATE     URL   SWARM   DOCKER    ERRORS
myapp                 -        google   Stopped                 Unknown

activeなdocker-machineを切り替える

eval $$(docker-machine env ${NAME}) 

docker-machine上で、登録したimageを実行する

gcloud docker -- run -it -e PROJECT_ID=$(APPID) --name ${NAME} asia.gcr.io/$(APPID)/${NAME}:latest /bin/bash