Skip to content

Instantly share code, notes, and snippets.

@nojaja
Last active January 29, 2021 07:15
Show Gist options
  • Save nojaja/887b486cad04f08a60da8ec901bd3a60 to your computer and use it in GitHub Desktop.
Save nojaja/887b486cad04f08a60da8ec901bd3a60 to your computer and use it in GitHub Desktop.
minikube develop env setup for win7

管理ネットワーク内でKubernetesを使うための開発環境のセットアップ(win7)

出先のオフィスや学校、公共施設など制限が厳しいエリアで開発したい場合の覚書 PKS/AKS/Kubernetesを利用した開発を行うのに必要なローカル環境の構築を行います。

前提条件

事前作業

  • Admin権限がある状態で実施する事
  • 制限付きネットワーク
  • BIOSにてVirtualization Technology(VT-X / AMD-v)が[Enabled]になっている事

要求スペック

検証で利用したマシンスペックは下記になります。

項目 内容
ホストOS Windows 7 Pro SP1
CPU Intel Core i5-6200U@2.30GHz
MEM 8GB
BIOS VT-x technologyもしくはAMD-V technologyが有効

※上記は最低限のスペックではありません。

この作業で導入されるもの

項目 内容 バージョン
Chocolatey パッケージマネージャ v0.10.15
hypervisor VirtualBox 6.0.8
Minikube Kubernetesの簡易版 v1.1.1 (on Docker v18.09.6)
kubectl Kubernetes CLI v1.14.3
docker-cli Docker CLI v18.09.6
skaffold 継続デプロイTool v0.31.0

※ バージョン指定がない場合、手順が実施された時点の最新バージョンを利用してください

環境設定

管理者権限でpowershell起動

Winキー+Rもしくはファイル名を指定して実行にて
CMDを入力、Shift+Ctrl+Enterで管理者権限で起動
下記のコマンドを実行する

"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass

Proxyの設定

社内の場合はpowershellにて下記のコマンドを実行してproxyを設定する。

$PROXYOVERRIDE = '172.*;192.168.*;<local>';
$HTTP_PROXY ='myproxy:8080';
$NO_PROXY = '127.0.0.1,192.168.XX.ZZ,・・・';

(Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings' -name 'ProxyEnable' -value '1');
(Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings' -name 'ProxyServer' -value $HTTP_PROXY);
(Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings' -name 'ProxyOverride' -value $PROXYOVERRIDE);

(Get-Item -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings').GetValue('ProxyEnable');
(Get-Item -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings').GetValue('ProxyServer');
(Get-Item -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings').GetValue('ProxyOverride');

$HTTP_PROXY = (Get-Item -Path 'Registry::HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings').GetValue('ProxyServer');
[Environment]::SetEnvironmentVariable('HTTP_PROXY', $HTTP_PROXY, 'User');
[Environment]::SetEnvironmentVariable('HTTPS_PROXY', $HTTP_PROXY, 'User');
[Environment]::SetEnvironmentVariable('NO_PROXY', $NO_PROXY, 'User');

インストール

パッケージマネージャインストール

Winキー+Rもしくはファイル名を指定して実行にて
CMDを入力、Shift+Ctrl+Enterで管理者権限で起動
下記のコマンドを実行する

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

関連ツールインストール

Winキー+Rもしくはファイル名を指定して実行にて
CMDを入力、Shift+Ctrl+Enterで管理者権限で起動
下記のコマンドを実行する

rem 下記は必須ツール(既に導入済であればスキップ)
choco install git jdk8 maven azure-cli -y
choco install nodist -y --install-args="'/D=c:\nodist'"
rem mavenもインストール先が微妙なので別の方法を検討したい

rem 下記は必要に応じて導入
choco install 7zip -y
rem choco install sourcetree -y
rem choco install winmerge-jp -y →DL先が404なので  https://winmergejp.bitbucket.io/からDL
choco install tortoisegit
choco install vscode
choco install eclipse
choco install winscp
choco install putty
choco install googlejapaneseinput -y
nodist 10.16.0
nodist npm match
refreshenv
実行NG ログに下記の文言が含まれる場合は`refreshenv`を実行してください
see the changes (or in powershell/cmd.exe just type `refreshenv`).
項目 内容 バージョン
maven タスクランナー 3.6.1
git バージョン管理 v2.22.0
JDK8 Java v8.0.211
nodist nodist v0.9.1

mavenの環境設定

社内リポジトリの設定と接続する際にproxyを利用しないように設定

C:\ProgramData\chocolatey\lib\maven\apache-maven-3.6.1\conf 配下を書き換え

gitの環境設定

社内リポジトリに接続する際にproxyを利用しないように設定

Winキー+Rもしくはファイル名を指定して実行にて
CMDを入力、Shift+Ctrl+Enterで管理者権限で起動
下記のコマンドを実行する

git config --global http.http://{社内リポジトリ}/.proxy ""

npmの環境設定

※外部に接続する場合のみ設定

rem 社外にnpmするよう設定
npm config set proxy http://myproxy:8080
npm config set https-proxy http://myproxy:8080
npm config set strict-ssl false
rem npm config set registry http://local/artifactory/api/npm/npm-virtual/
npm config list

Minikubeとkubernetes-cliのインストール

Winキー+Rもしくはファイル名を指定して実行にて
CMDを入力、Shift+Ctrl+Enterで管理者権限で起動
下記のコマンドを実行する

choco install virtualbox minikube kubernetes-cli docker-cli skaffold -y

VirtualBox Host-Only Ethernet Adapterの設定からIPv6を無効化
アダプターを再起動

Kubernetesにproxyのルート証明書を登録する

社内の場合は専用のルート証明書が必要になる場合がある

証明書の配置場所を作成

mkdir %USERPROFILE%\.minikube\files\etc\ssl\certs

形式はpemで拡張子は.crt

Kubernetesクラスタの起動

minikube startで起動(初回はVM作成)が行われます。 ハイパーバイザを明示的に指定するには--vm-driverオプションでvirtualboxなどを指定する。

Winキー+Rもしくはファイル名を指定して実行にて
CMDを入力、Shift+Ctrl+Enterで管理者権限で起動
下記のコマンドを実行する

minikube start --vm-driver virtualbox
実行結果:成功 下記の様に表示されればOK
>minikube start
* minikube v1.1.0 on windows (amd64)
* Downloading Minikube ISO ...
 131.28 MB / 131.28 MB [============================================] 100.00% 0s
* Creating virtualbox VM (CPUs=2, Memory=2048MB, Disk=20000MB) ...
* Found network options:
  - HTTP_PROXY=myproxy:8080
  - HTTPS_PROXY=myproxy:8080
  - NO_PROXY=127.0.0.1,192.168.99.100,192.168.99.102,192.168.99.103
* Configuring environment for Kubernetes v1.14.2 on Docker 18.09.6
  - env HTTP_PROXY=myproxy:8080
  - env HTTPS_PROXY=myproxy:8080
  - env NO_PROXY=127.0.0.1,192.168.99.100,192.168.99.102,192.168.99.103
* Downloading kubelet v1.14.2
* Downloading kubeadm v1.14.2
* Pulling images ...
* Launching Kubernetes ...
* Verifying: apiserver proxy etcd scheduler controller dns
* Done! kubectl is now configured to use "minikube"
実行結果:VTが無効で失敗 下記の場合、VTが無効になってます。 BIOS設定でVTをEnabledにしてください
>minikube start
E0619 16:11:43.180199   10144 start.go:529] StartHost: create: creating: Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm minikube --type headless
failed:
VBoxManage.exe: error: The native API dll was not found (C:\Windows\system32\WinHvPlatform.dll) (VERR_NEM_NOT_AVAILABLE).
VBoxManage.exe: error: VT-x is disabled in the BIOS for all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole

Details: 00:00:02.382753 Power up failed (vrc=VERR_VMX_MSR_ALL_VMX_DISABLED, rc=E_FAIL (0X80004005))

X Unable to start VM: create: creating: Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm minikube --type headless failed:
VBoxManage.exe: error: The native API dll was not found (C:\Windows\system32\WinHvPlatform.dll) (VERR_NEM_NOT_AVAILABLE).
VBoxManage.exe: error: VT-x is disabled in the BIOS for all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole

Details: 00:00:02.382753 Power up failed (vrc=VERR_VMX_MSR_ALL_VMX_DISABLED, rc=E_FAIL (0X80004005))

* Sorry that minikube crashed. If this was unexpected, we would love to hear from you:
  - https://github.com/kubernetes/minikube/issues/new

実行確認

Winキー+Rもしくはファイル名を指定して実行にて
CMDを入力、ユーザー権限で起動
下記のコマンドを実行する

minikube version
kubectl version
@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
docker version
docker info
skaffold version

それぞれこの作業で導入されるもののバージョンより新しいことを確認する

実行NG:docker version `docker daemon is not running.`と出る場合はminikubeが起動してない可能性があります [Kubernetesクラスタの起動](#Kubernetesクラスタの起動)を再実施してください
エラー
Client:
 Version:           18.09.6
 API version:       1.39
 Go version:        go1.10.8
 Git commit:        c89750f8
 Built:             06/09/2019 17:10:42
 OS/Arch:           windows/amd64
 Experimental:      false
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.39/version: o
pen //./pipe/docker_engine: The system cannot find the file specified. In the de
fault daemon configuration on Windows, the docker client must be run elevated to
 connect. This error may also indicate that the docker daemon is not running.

クラスタの状況確認

kubectl cluster-info
実行結果 下記の様に表示されればOK
>kubectl cluster-info
Kubernetes master is running at https://192.168.99.102:8443
KubeDNS is running at https://192.168.99.102:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

クラスタのノード情報確認

kubectl get nodes
実行結果 下記の様に表示されればOK
>kubectl get node
NAME       STATUS   ROLES    AGE    VERSION
minikube   Ready    master   178m   v1.14.2

次のステップ

ここまで完了したら クイックスタート に進んでください。


補足

BIOS設定方法

ThinkPad L450(Windows7)の場合

Security  
→Virtualization  
 →Intel(R) Virtualization Technology  
 →Intel(R) VT-d Feature   

#######

01_setup\step01作業履歴

パッケージマネージャインストール

chocoはFW関連の問題でアクセスできないが 下記を直接実行した場合は回避できたため、この方法を利用する

Kubernetesクラスタの起動にて

ネットワーク関連のエラーが出た

///virtualbox 立ち上げてホストネットワークアダプタ削除

VirtualBox Host-Only Ethernet Adapterの設定からIPv6を無効化

>minikube start
* minikube v1.1.0 on windows (amd64)
* Downloading Minikube ISO ...
 131.28 MB / 131.28 MB [============================================] 100.00% 0s
* Creating virtualbox VM (CPUs=2, Memory=2048MB, Disk=20000MB) ...
* Found network options:
  - HTTP_PROXY=myproxy:8080
  - HTTPS_PROXY=myproxy:8080
  - NO_PROXY=127.0.0.1,192.168.99.100,192.168.99.102,192.168.99.103
* Configuring environment for Kubernetes v1.14.2 on Docker 18.09.6
  - env HTTP_PROXY=myproxy:8080
  - env HTTPS_PROXY=myproxy:8080
  - env NO_PROXY=127.0.0.1,192.168.99.100,192.168.99.102,192.168.99.103
* Downloading kubelet v1.14.2
* Downloading kubeadm v1.14.2
* Pulling images ...
* Launching Kubernetes ...
* Verifying: apiserver proxy etcd scheduler controller dns
* Done! kubectl is now configured to use "minikube"

dockerの残骸などを削除していてVMのminikubeを消したら動かなくなった

minikube環境のリフレッシュ

minikube delete
minikube start

で復旧

実行確認

C:\WINDOWS\system32>minikube version
minikube version: v1.1.1

C:\WINDOWS\system32>kubectl version
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.3", GitCommit:"5e53fd6bc17c0dec8434817e69b04a25d8ae0ff0", GitTreeState:"clean", BuildDate:"2019-06-06T01:44:30Z", GoVersion:"go1.12.5", Compiler:"gc", Platform:"windows/amd64"}
Server Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.3", GitCommit:"5e53fd6bc17c0dec8434817e69b04a25d8ae0ff0", GitTreeState:"clean", BuildDate:"2019-06-06T01:36:19Z", GoVersion:"go1.12.5", Compiler:"gc", Platform:"linux/amd64"}

C:\WINDOWS\system32>@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i

C:\WINDOWS\system32>docker version
Client:
 Version:           18.09.6
 API version:       1.39
 Go version:        go1.10.8
 Git commit:        c89750f8
 Built:             06/09/2019 17:10:42
 OS/Arch:           windows/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.6
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.8
  Git commit:       481bc77
  Built:            Sat May  4 02:41:08 2019
  OS/Arch:          linux/amd64
  Experimental:     false

クラスタの状況確認

>kubectl cluster-info
Kubernetes master is running at https://192.168.99.102:8443
KubeDNS is running at https://192.168.99.102:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

IPが100ではなくて102になってるのが、気になるがOKとする

クラスタのノード情報確認

>kubectl get node
NAME       STATUS   ROLES    AGE    VERSION
minikube   Ready    master   178m   v1.14.2

Kubernetesクイックスタート(minikube 使用版)

PKS/AKS/Kubernetesを利用するためのクイックスタートです。
この手順を実施する事で上記を利用するのに必要な作業内容を把握する事が出来ます。

前提条件

  • 開発環境のセットアップが完了している事(Minikube startが正常実行出来ている事)

この作業で学習するもの

項目 内容
Hello Kubernetes 最も簡単なKubernetesサンプルの実行
Hello Docker 最も簡単なDockerサンプルの実行
Docker Build DockerイメージのBuildと、それを使ったKubernetesデプロイ
マニフェストサンプル Kubernetesマニフェストを利用したKubernetesデプロイ
Hello skaffold skaffoldを利用した継続的なKubernetesデプロイ
javaサンプル JavaプロジェクトをビルドしてKubernetesデプロイ
ダッシュボード起動 minikube管理画面の起動と動作の確認

事前準備

クラスタのノード情報確認

minikubeが起動しているか確認します

kubectl get nodes
実行結果 下記の様に表示されればOK
>kubectl get nodes
NAME       STATUS   ROLES    AGE    VERSION
minikube   Ready    master   178m   v1.14.3

Dockerコマンドの有効化

@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%iによって、minikubeのdockerを操作できるようになります。
コンソール起動毎に実施してください

実行結果 文言なし、もしくは下記のような文言であればOK
>@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
There is a newer version of minikube available (v1.2.0).  Download it here:
https://github.com/kubernetes/minikube/releases/tag/v1.2.0

To disable this notification, run the following:
minikube config set WantUpdateNotification false

作業フォルダ

[任意ディレクトリ]/workspace_k8s/nginxpageを作業場所と想定しますので、 カレントディレクトリで下記で作業ディレクトリを作成ます。 ※既に存在するならスキップしてください

.\workspace_k8s\nginxpageにて
作業するものとします。

mkdir -p .\workspace_k8s\nginxpage
cd .\workspace_k8s\nginxpage

echoserver

最も簡単なKubernetesサンプルの実行

echoserverを構築してみる

kubectl create deployment hello-minikube --image=k8s.gcr.io/echoserver:1.10
kubectl expose deployment hello-minikube --type=NodePort --port=8080
minikube service hello-minikube
minikube service list
kubectl get deploy hello-minikube -o yaml
kubectl get service
kubectl get pods

削除

kubectl delete service hello-minikube
kubectl delete deployment hello-minikube
kubectl get service
kubectl get pods

Hello Kubernetes

最も簡単なKubernetesサンプルの実行

https://kubernetes.io/ja/docs/tutorials/hello-minikube/
の手順を実施します
外部のリポジトリよりgcr.io/hello-minikube-zero-install/hello-nodeのDockerImageを取得して、 デプロイ、公開を行います

構築

Deploymentの作成

kubectl create コマンドを使用してPodを管理するDeploymentを作成してください。

Podは提供されたDockerイメージを元にコンテナを実行します

kubectl create deployment hello-kubernetes --image=gcr.io/hello-minikube-zero-install/hello-node
実行結果 下記の様に表示されればOK
deployment.apps/hello-kubernetes created
deploymentの稼働状況一覧取得:
kubectl get deployments
実行結果 下記の様に表示されればOK
>kubectl get deployments
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
hello-kubernetes   1/1     1            1           42s
podの稼働状況一覧取得
kubectl get pods
実行OK
``` >kubectl get pods NAME READY STATUS RESTARTS AGE hello-kubernetes-69b545884f-fzdnr 1/1 Running 0 2m7s ```
実行NG:ImagePullBackOff Docker Imageが取得できない場合に発生します proxy設定を見直してください、イメージを自分で作成している場合は対象のDockerImageが正しくビルド出来ているか`docker image ls`で確認してください
``` >kubectl get pods NAME READY STATUS RESTARTS AGE hello-kubernetes-69b545884f-fzdnr 0/1 ImagePullBackOff 0 103s ```
デプロイなどのイベントログ確認(うまく動作してない場合はここで確認する)
kubectl get events
実行OK
>kubectl get events
LAST SEEN   TYPE     REASON              OBJECT                                   MESSAGE
4m14s       Normal   Scheduled           pod/hello-kubernetes-69b545884f-fzdnr    Successfully assigned default/hello-kubernetes-69b545884f-fzdnr to minikube
4m12s       Normal   Pulling             pod/hello-kubernetes-69b545884f-fzdnr    Pulling image "gcr.io/hello-minikube-zero-install/hello-node"
4m10s       Normal   Pulled              pod/hello-kubernetes-69b545884f-fzdnr    Successfully pulled image "gcr.io/hello-minikube-zero-install/hello-node"
4m10s       Normal   Created             pod/hello-kubernetes-69b545884f-fzdnr    Created container hello-node
4m9s        Normal   Started             pod/hello-kubernetes-69b545884f-fzdnr    Started container hello-node
4m14s       Normal   SuccessfulCreate    replicaset/hello-kubernetes-69b545884f   Created pod: hello-kubernetes-69b545884f-fzdnr
4m14s       Normal   ScalingReplicaSet   deployment/hello-kubernetes              Scaled up replica set hello-kubernetes-69b545884f to 1

podの詳細状況確認
kubectl describe pod {POD NAME}
実行OK例 例`kubectl describe pod hello-kubernetes-b89fcc69b-cnwj2`
``` Name: hello-kubernetes-b89fcc69b-cnwj2 Namespace: default Node: docker-for-desktop/192.168.65.3 Start Time: Thu, 27 Jun 2019 10:45:51 +0900 Labels: app=hello-kubernetes pod-template-hash=645977256 Annotations: Status: Running IP: 10.1.0.56 Controlled By: ReplicaSet/hello-kubernetes-b89fcc69b ```
設定の確認
kubectl config view
実行OK例
>kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority: C:\Users\{ユーザホーム}\.minikube\ca.crt
    server: https://192.168.99.100:8443
  name: minikube
contexts:
- context:
    cluster: minikube
    user: minikube
  name: minikube
current-context: minikube
kind: Config
preferences: {}
users:
- name: minikube
  user:
    client-certificate: C:\Users\{ユーザホーム}\.minikube\client.crt
    client-key: C:\Users\{ユーザホーム}\.minikube\client.key

Serviceの作成

kubectl expose コマンドを使用してPodを外部に公開します:
kubectl expose deployment hello-kubernetes --type=LoadBalancer --port=8080
実行結果 下記の様に表示されればOK
service/hello-kubernetes exposed
作成したServiceを確認します:
kubectl get service
実行結果 下記の様に表示されればOK
>kubectl get service
NAME                TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
hello-kubernetes    LoadBalancer   10.106.90.5     <pending>     8080:32374/TCP   45s
kubernetes          ClusterIP      10.96.0.1       <none>        443/TCP          19d

「NAME」列の値がhello-kubernetesの行があることを確認します

確認

モジュールの動作確認

minikube service hello-kubernetes
実行結果 下記の様に表示されればOK
>minikube service hello-kubernetes
* Opening kubernetes service default/hello-kubernetes in default browser...

Browerが立ち上がって、Hello World!が表示されます。

もしくはkubectl get serviceのhello-kubernetesの行から、
http://{起動時に表示されるIP}/[PORT(左)] でアクセスします 例http://192.168.99.100:32374/

Serviceとして動作している一覧取得

minikube service list

実行結果 下記の様に表示されればOK
>minikube service list
|-------------|----------------------|-----------------------------|
|  NAMESPACE  |         NAME         |             URL             |
|-------------|----------------------|-----------------------------|
| default     | hello-kubernetes     | http://192.168.99.100:32374 |
| default     | kubernetes           | No node port                |
| kube-system | kube-dns             | No node port                |
| kube-system | kubernetes-dashboard | No node port                |
|-------------|----------------------|-----------------------------|

Serviceの稼働状況一覧取得

kubectl get service

実行結果 下記の様に表示されればOK
>kubectl get service
NAME                TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
hello-kubernetes    LoadBalancer   10.106.90.5     <pending>     8080:32374/TCP   7m16s
kubernetes          ClusterIP      10.96.0.1       <none>        443/TCP          20d

特定のdeploymentのマニフェストyamlを取得

kubectl get deploy hello-kubernetes -o yaml

実行結果 下記の様に表示されればOK
>kubectl get deploy hello-kubernetes -o yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2019-07-04T09:36:20Z"
  generation: 1
  labels:
    app: hello-kubernetes
  name: hello-kubernetes
  namespace: default
  resourceVersion: "338851"
  selfLink: /apis/extensions/v1beta1/namespaces/default/deployments/hello-kubernetes
  uid: 2e0da13e-9e3f-11e9-abdc-08002793bbf5
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: hello-kubernetes
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: hello-kubernetes
    spec:
      containers:
      - image: gcr.io/hello-minikube-zero-install/hello-node
        imagePullPolicy: Always
        name: hello-node
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 1
  conditions:
  - lastTransitionTime: "2019-07-04T09:36:25Z"
    lastUpdateTime: "2019-07-04T09:36:25Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2019-07-04T09:36:20Z"
    lastUpdateTime: "2019-07-04T09:36:25Z"
    message: ReplicaSet "hello-kubernetes-69b545884f" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  observedGeneration: 1
  readyReplicas: 1
  replicas: 1
  updatedReplicas: 1

削除

デプロイしたServiceを削除します。

kubectl delete service hello-kubernetes
実行結果 下記の様に表示されればOK
>kubectl delete service hello-kubernetes
service "hello-kubernetes" deleted

デプロイメントを削除します。

kubectl delete deployment hello-kubernetes
実行結果 下記の様に表示されればOK
>kubectl delete deployment hello-kubernetes
deployment.extensions "hello-kubernetes" deleted

サービスが削除されたことを確認します。

kubectl get service hello-kubernetes

Podを削除されたことを確認します。

kubectl get pods

Hello Docker

最も簡単なDockerサンプルの実行
外部のリポジトリより'hello-world'のDockerImageを取得して実行します。

docker run -it --rm hello-world
docker image ls
実行結果 下記の様に表示されればOK
>docker run -it --rm hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

>docker image ls
REPOSITORY     TAG     IMAGE ID            CREATED             SIZE
hello-world    latest  fce289e99eb9        6 months ago        1.84kB


Docker Build

外部のリポジトリよりnginx:1.11のDockerImageを取得して
page.htmlの追加を行い、新たなDockerImageのlocal/example/nginxpage:0.1.0を作成します。

更にそのイメージを利用してKubernetesクラスタを構築します。
場所は.\workspace_k8s\nginxpageとします

Dockerfileファイル作成

Dockerfileを作成します、拡張子は無しです。

FROM nginx:1.11

COPY page.html /usr/share/nginx/html/page.html

page.htmlファイル作成

<html>
  <head><title>this is page</title></head>
  <body>original page</body>
</html>

imageを作る

タグはlatestだと動かないので、適当にバージョンつけます。

cd .\workspace_k8s\nginxpage
docker build --rm -t local/example/nginxpage:0.1.0 .
実行結果 下記の様に表示されればOK
Sending build context to Docker daemon  13.31kB
Step 1/2 : FROM nginx:1.11
 ---> 5766334bdaa0
Step 2/2 : COPY page.html /usr/share/nginx/html/page.html
 ---> Using cache
 ---> 436dd667181f
Successfully built 436dd667181f
Successfully tagged local/example/nginxpage:0.1.0

SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

Image一覧を確認します。

docker image ls

成功するとローカルのREPOSITORYに local/example/nginxpageが登録されます。

実行結果 下記の様に表示されればOK
>docker image ls
REPOSITORY                   TAG     IMAGE ID            CREATED             SIZE
hello-world                  latest  fce289e99eb9        6 months ago        1.84kB
local/example/nginxpage      0.0.1   425b5b583a28        2 weeks ago         183MB
nginx                        1.11    5766334bdaa0        2 years ago         183MB

構築

kubectl create deployment nginxpage --image=local/example/nginxpage:0.1.0
rem PCからアクセスできるように
kubectl expose deployment nginxpage --name=nginxpage-service --type="NodePort" --port=80
rem ブラウザで確認
minikube service nginxpage-service
実行結果 下記の様に表示されればOK
>kubectl create deployment nginxpage --image=local/example/nginxpage:0.1.0
deployment.apps/nginxpage created

>kubectl expose deployment nginxpage --name=nginxpage-service --type="NodePort" --port=80
service/nginxpage-service exposed

>minikube service nginxpage-service
* Opening kubernetes service default/nginxpage-service in default browser...

Browserwでトップページが表示されたら dockerimageで追加した./page.htmlが見れるか確認してください。
'http://{ip}:[port]/page.html'
(本例の場合 http://localhost:31760/page.htmlとなります)

削除

kubectl delete service nginxpage-service
kubectl delete deployment nginxpage 
kubectl get service
kubectl get pods

Imageを削除する場合は下記を実施、イメージは次の手順で利用するので通常は削除不要

docker image ls
docker rmi {IMAGE ID} -f

マニフェストサンプル

Kubernetesマニフェスト(yaml)を利用したKubernetesデプロイ

上記のnginxpageの構築を定義ファイルに記載して自動化します

場所は.\workspace_k8s\nginxpageとします

cd .\workspace_k8s\nginxpage

マニフェストファイル作成

nginxpage.yamlを作成を作成します

apiVersion: v1
kind: Pod
metadata:
  name: nginxpage
  labels: 
    app: nginxpage
spec:
  containers:
  - name: nginxpage
    image: local/example/nginxpage:0.1.0
    ports:
    - containerPort: 80 
---
apiVersion: v1
kind: Service
metadata:
  name: nginxpage-service
spec:
  type: NodePort
  ports:
    - port: 80
  selector:
    app: nginxpage

create実行

kubectl create -f nginxpage.yaml
minikube service nginxpage-service
実行OK
>kubectl create -f nginxpage.yaml
pod/nginxpage created
service/nginxpage-service created

>minikube service nginxpage-service
* Opening kubernetes service default/nginxpage-service in default browser...

実行NG:exist 既にpodもしくはserviceが存在している下記の様なエラーが発生する、 `kubectl delete`を利用して対象を削除してから再実施してください
>kubectl create -f nginxpage.yaml

service/nginxpage-service created
Error from server (AlreadyExists): error when creating "nginxpage.yaml": pods "nginxpage" already exist

確認

Browserで下記実行結果が表示されるか確認
'http://{ip}:[port]'
(本例の場合 http://localhost:31760となります)

実行OK
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

削除

kubectl delete -f nginxpage.yaml 
kubectl get service
kubectl get pods
実行OK
>kubectl create -f nginxpage.yaml
pod/nginxpage created
service/nginxpage-service created

>minikube service nginxpage-service
* Opening kubernetes service default/nginxpage-service in default browser...

>kubectl delete -f nginxpage.yaml
pod "nginxpage" deleted
service "nginxpage-service" deleted

>kubectl get service
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   20d

>kubectl get pods
No resources found.

Hello skaffold

skaffoldを利用して、
上記のDockerBuildkubectl createまでの一連の作業を自動化します
また、devオプションをつけることでコードが変更されるたびに一連動作を自動適用します

場所は.\workspace_k8s\nginxpageとします

サンプルアプリのダウンロード

git clone https://github.com/GoogleContainerTools/skaffold

マニフェストファイル作成

k8s-nginxpage.yamlを作成します(nginxpage.yamlをコピー)
※ nginxpage.yamlにあるimageのnginxpageバージョンを消したこと以外は同じ内容。

apiVersion: v1
kind: Pod
metadata:
  name: nginxpage
  labels: 
    app: nginxpage
spec:
  containers:
  - name: nginxpage
    image: local/example/nginxpage
    ports:
    - containerPort: 80 
---
apiVersion: v1
kind: Service
metadata:
  name: nginxpage-service
spec:
  type: NodePort
  ports:
    - port: 80
  selector:
    app: nginxpage

skaffoldマニフェストファイル作成

skaffold.yamlを作成します

apiVersion: skaffold/v1beta11
kind: Config
build:
  artifacts:
  - image: local/example/nginxpage
deploy:
  kubectl:
    manifests:
      - k8s-*

build:artifacts:imageは作成するdockerイメージ名=マニフェストに記載するimage名にあわせます
deploy:kubectl:manifests:はkubectl createに渡すマニフェストファイル名を設定します

skaffold dev:コードが変更されるたびにアプリをビルドおよびデプロイする

アプリを継続的にビルドおよびデプロイするために実行します。 この--default-repo機能により、デフォルトのリポジトリではなく独自のリポジトリ(local)にimageをプッシュできます

rem skaffold dev --default-repo <myrepo>
start skaffold dev --default-repo local
minikube service nginxpage-service
実行OK
�[34mGenerating tags...�[0m
�[34m - local/local_example_nginxpage -> �[0mtime="2019-07-04T19:23:38+09:00" level=warning msg="Unable to find git commit: Running [git describe --tags --always]: stdout , stderr: fatal: not a git repository (or any of the parent directories): .git\n, err: exit status 128: exit status 128"
local/local_example_nginxpage:dirty
�[34mTags generated in 962ms�[0m
�[34mStarting build...�[0m
�[34mFound [minikube] context, using local docker daemon.
�[0m�[34mBuilding [local/local_example_nginxpage]...
�[0mSending build context to Docker daemon  3.072kB
Step 1/2 : FROM nginx:1.11
 ---> 5766334bdaa0
Step 2/2 : COPY page.html /usr/share/nginx/html/page.html
 ---> Using cache
 ---> 57d97e81bc1d
Successfully built 57d97e81bc1d
Successfully tagged local/local_example_nginxpage:dirty
�[34mBuild complete in 72ms�[0m
�[34mStarting test...�[0m
�[34mTest complete in 0s�[0m
�[34mStarting deploy...�[0m
�[34mkubectl client version: 1.14�[0m
pod/nginxpage unchanged
service/nginxpage-service unchanged
�[34mDeploy complete in 16.651s�[0m
�[33mWatching for changes every 1s...
�[0m

確認

http://{IP}:{port}/page.html にアクセス

original page

となっていることを確認

page.htmlファイルを修正

<html>
  <head><title>this is page</title></head>
  <body>update page</body>
</html>

確認

http://{IP}:{port}/page.html にアクセス

update page

に更新されたことを確認

skaffold -v debug dev

time="2019-06-21T00:30:25+09:00" level=fatal msg="watching files for artifact local/exsample/tomcat-app: listing files: listing files: file pattern [target/classes] must match at least one file"

docker info
docker build --tag local/exsample/tomcat-app:0.0.1 .
docker image ls
rem docker export --output="latest.tar" local/exsample/tomcat-app
docker save --output="latest.tar" local/exsample/tomcat-app

https://yoshinorin.net/2017/07/04/docker-save-load-export-import/

skaffold.yamlは変数が使えるかも

 template: "{{.DOCKER_REGISTRY}}/jstrachan/demo102:{{.VERSION}}"
export VERSION="1.2.3"
skaffold run -f skaffold.yaml

削除

skaffoldをCtrl+Cで停止

kubectl delete -f nginxpage.yaml
kubectl get service
kubectl get pods

動作確認2-2

https://kubernetes.io/ja/docs/tutorials/hello-minikube/ の手順
自分でdockerイメージ作る

imageを作る

タグはlatestだと動かないので、適当にバージョンつけます。
タグはlatest以外にする必要があることに注意。でないと、k8sはregistryからイメージをpullしてこようとしてしまいます。

cd /d D:\devs\workspace_k8s\hello-node
@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
docker build --rm -t example/hello-node:0.1.0 .
docker tag example/hello-node 192.168.99.101:30470/hello-node
docker push 192.168.99.101:30470/hello-node
>docker push 192.168.99.101:30470/hello-node
The push refers to repository [192.168.99.101:30470/hello-node]
Get https://192.168.99.101:30470/v2/: EOF

構築

kubectl create deployment hello-node --image=192.168.99.101:30470/hello-node
rem kubectl run hello-node --image=example/hello-node --image-pull-policy=IfNotPresent
kubectl expose deployment hello-node --type=LoadBalancer --port=8080
minikube service hello-node

動かない

削除

kubectl delete service hello-node
kubectl delete deployment hello-node
kubectl get service
kubectl get pods
kubectl get events

nginxロードバランサ 作成

作成

@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
kubectl create deployment nginx --image=nginx:1.15.8
kubectl get pods
kubectl get deployment
kubectl expose deployment nginx --port 80 --type LoadBalancer
kubectl get service
minikube service nginx 

削除

kubectl delete service nginx 
kubectl delete deployment nginx 
kubectl get service
kubectl get pods


Javaサンプル

JavaプロジェクトをビルドしてKubernetesデプロイします。

JavaプロジェクトはTomcatで動作するアプリとし、 War形式で動作していたものを、Tomcatを組み込んでJar形式に書き換え、単体動作するようにします。

場所は.\workspace_k8s\tomcat-app1とします

ソース取得

Source

マニフェストファイル作成

k8s-tomcatapp1.yamlを作成する

apiVersion: v1
kind: Pod
metadata:
  name: tomcatapp1
  labels: 
    app: tomcatapp1
spec:
  containers:
  - name: tomcatapp1
    image: local/example/tomcatapp1
    ports:
    - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: tomcatapp1-service
spec:
  type: NodePort
  ports:
    - port: 8080
  selector:
    app: tomcatapp1

skaffoldマニフェストファイル作成します

*** 下記別の方法に変更予定 *** skaffold.yamlを作成する

apiVersion: skaffold/v1beta11
kind: Config
build:
  artifacts:
  - image: local/example/tomcatapp1
deploy:
  kubectl:
    manifests:
      - k8s-*

Java Build

mvn -DoutputDirectory=target/lib -Dcompile=compile clean dependency:copy-dependencies compile

skaffold dev

skaffold dev --default-repo local

動作確認

minikube service tomcatapp1-service

削除

kubectl delete service myapp-nodeport
kubectl delete deployment myapp 
kubectl get service
kubectl get pods

ダッシュボード起動

minikube管理画面の起動と動作の確認

start kubectl proxy
minikube dashboard

ブラウザが立ち上がり、Kubernetesの稼働状況が確認できるようになります。



Javaサンプル

JavaプロジェクトをビルドしてKubernetesデプロイします。

JavaプロジェクトはTomcatで動作するアプリとし、 War形式で動作していたものを、Tomcatを組み込んでJar形式に書き換え、単体動作するようにします。

場所は.\workspace_k8s\tomcat-app1とします

改修

TODO

#######

02_Testing\step01作業履歴

choco install は管理者権限必須

#検証メモ

choco install docker-cli
choco install maven
mvn -DoutputDirectory=target/lib -Dcompile=compile clean dependency:copy-dependencies compile

docker build --tag myapp:1.0 .
docker build -t example/nginxpage:0.1.0 .

NG

minikube mount %HOME%:/var/lib/host_home

失敗する場合
VirtualBox Host-Only Networkを
VirtualBox Host-Only Ethernet Adapter
に変更する

minikube mount D:\devs\workspace_k8s:/var/lib/host_home

NG

やっぱdockerは必須?

choco install docker-toolbox
@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i

minikube のvmで動作してそうなのでdocker-cliだけで動くかも
docker-cliだけで動いた

ダッシュボード起動させる

>minikube dashboard
* Enabling dashboard ...
* Verifying dashboard health ...
* Launching proxy ...
* Verifying proxy health ...
X http:///api/v1/namespaces/kube-system/services/http:kubernetes-dashboard:/proxy/ is not responding properly: checkURL: Get http:///api/v1/namespaces/kube-system/services/http:kubernetes-dashboard:/proxy/: http: no Host in request URL

起動に失敗 https://github.com/kubernetes/dashboard/wiki/Accessing-Dashboard---1.7.X-and-above のサイトによるとproxyの起動が必要らしい

FROM java:8-jre-alpine
RUN mkdir /app
WORKDIR /app
COPY target/lib /app/target/lib
COPY target/classes /app/target/classes
COPY src/main/webapp /app/src/main/webapp
ENV CLASSPATH /app/target/classes:/app/target/lib/*
ENV JAVA_TOOL_OPTIONS -Djava.security.egd=file:/dev/./urandom
EXPOSE 8080 8009
CMD java $JAVA_OPTS Main
FROM node:6.14.2
EXPOSE 8080
COPY server.js .
CMD node server.js
minikube/server.js
var http = require('http');
var handleRequest = function(request, response) {
console.log('Received request for URL: ' + request.url);
response.writeHead(200);
response.end('Hello World!');
};
var www = http.createServer(handleRequest);
www.listen(8080);
apiVersion: v1
kind: Service
metadata:
name: httpd-service
spec:
type: LoadBalancer
ports:
- port: 80
selector:
app: pod-httpd
apiVersion: v1
kind: Pod
metadata:
name: pod-httpd
labels:
app: pod-httpd
spec:
containers:
- name: httpd
image: httpd
ports:
- containerPort: 80
FROM nginx:1.11
COPY page.html /usr/share/nginx/html/page.html
<html>
<head><title>this is page</title></head>
<body>original page</body>
</html>

EclipseをインストールしたDockerイメージを作ってみた

下記、イメージの作成をもう少し考える必要がある

→Docker内のEclipseだとmvn実行時にDockerイメージ作成ができない(アンチパターンDocker in Docker)

参考

https://qiita.com/0ashina0/items/f56f35b59c98800b801f

https://hub.docker.com/r/visv/eclipse/dockerfile

「MobaXterm」をインストール

choco install mobaxterm

X11 remote accessをFullにする。

Settings->Configurationメニューを選択 X11 remote accessをFullに設定

1.「Dockerfile」を作成

2.「Dockerイメージ」devの作成(Eclipseインストール直前のイメージ)

@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
rem docker build ./ -t dev
docker pull visv/eclipse

3.「Dockerコンテナ」の作成&起動

ipconfig
docker run -it -e DISPLAY=<ホストのIPアドレス>:0.0 dev

docker run -it -e DISPLAY=192.168.0.1:0.0 dev

docker run -it --rm -v eclipseRepo:/root/repo -v eclipseWorkspace:/root/eclipse-workspace -e DISPLAY=192.168.0.1:0.0 visv/eclipse

4.Eclipseのインストール

/usr/bin/eclipse-installer/eclipse-inst

5.日本語プラグインの追加

# cp -r /plugins/* /root/eclipse/cpp-oxygen/eclipse/plugins/
# cp -r /features/* /root/eclipse/cpp-oxygen/eclipse/features/

5.「Dockerイメージ」dev_eclipseの作成(Eclipseインストール後のイメージ)

docker commit -m "Eclipse Installed"  275f75a472cb dev_eclipse
FROM centosjp
#キャッシュクリア
RUN yum clean all
#"Development and Creative Workstation"グループのインストール
RUN yum -y install deltarpm
RUN yum -y groupinstall "Development and Creative Workstation"
#Eclipseダウンロード
RUN wget -q -O /tmp/eclipse-inst-linux64.tar.gz "https://www.eclipse.org/downloads/download.php?file=/oomph/epp/oxygen/R/eclipse-inst-linux64.tar.gz&mirror_id=1"
RUN tar xavf /tmp/eclipse-* -C /opt/
RUN ln -s /opt/eclipse-installer /usr/bin
# 日本語プラグインをダウンロード
ADD http://ftp.jaist.ac.jp/pub/mergedoc/pleiades/build/stable/pleiades.zip /tmp
RUN unzip /tmp/pleiades.zip -d /tmp

社内用Docker Registryを立てる

https://blog.shibayu36.org/entry/2013/12/24/194134 https://qiita.com/RyotaIshii/items/915f0cb09155a6cae170 https://qiita.com/rsakao/items/617f54579278173d3c20

https://qiita.com/khkh/items/c4bf26d771f5a4a78ae6 https://qiita.com/ktateish/items/f094433e92310ad737a8

Docker Registryを立ち上げる

@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
docker run -p 5000:5000 -d stackbrew/registry
rem docker run -d -p 5000:5000 --restart=always --name registry registry:2

push/pull

pushやpullをしたい場合は、host名を含めたtagを付ける必要があります。例えばこのhostの名前が host だったとすると

docker build -t host:5000/sample-app .
docker push host:5000/sample-app

データのディレクトリをマウントする

Dockerコンテナをstopしたらデータが消えてしまいます。そこでhostのディレクトリを、Docker Registryのデータディレクトリにmountして、データを永続化できるようにします。

 これも立ちあげ方を変えるだけです。これでDockerを立ちあげているhostの/var/registryが、Dockerコンテナ内の/tmp/registryにmountされ、Dockerコンテナがstopしても/var/registryに残り続けてくれます。

docker run -d -p 5000:5000 -v /var/registry:/tmp/registry stackbrew/registry

停止

docker ps
docker stop nervous_yonath

kubaで作成

作成

@FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
kubectl create deployment registry --image=stackbrew/registry
kubectl get pods
kubectl get deployment
kubectl expose deployment registry --port=5000 --type="NodePort"
kubectl get service
minikube service registry 

削除

kubectl delete service registry 
kubectl delete deployment registry 
kubectl get service
kubectl get pods

rem kubectl run nginxpage --image=example/nginxpage:0.1.0 --port=80 kubectl create deployment nginxpage --image=example/nginxpage:0.1.0

2m33s Warning Failed pod/hello-node-5f97f4df7d-rfqmk Failed to pull image "example/hello-node": rpc error: code = Unknown desc = Error response from daemon: pull access denied for example/hello-node, repository does not exist or may require 'docker login'

## 参考サイト
minikube startのプロキシ越え
http://n-agetsuma.hatenablog.com/entry/2018/04/27/163553
Tomcatを使ったWebアプリをDocker化する方法を検討
https://qiita.com/namutaka/items/36f4055bd32e718890de
https://reiki4040.hatenablog.com/entry/2017/04/12/203156
https://knowledge.sakura.ad.jp/15321/
https://qiita.com/tomoyamachi/items/660bd7bb3afff8340307
Windowsで構成情報をDockerfileに定義してイメージを作成してみる
https://qiita.com/fkooo/items/53b2ea865e8c2c7fec27
MinikubeでオールインワンK8sクラスタ環境の構築
https://qiita.com/zaki-lknr/items/9eaf16ca8d4a7aacc8b0
kubernetes 学習 nginx pod 作成
http://tjtjtj.hatenablog.com/entry/2019/01/30/230000
minikubeでローカルのdocker imageを使う
https://qiita.com/ocadaruma/items/efe720e46ae7ecb9ec25

削除手順

minikube stop
minikube detele

choco uninstall minikube kubernetes-cli docker-cli skaffold -y
choco uninstall virtualbox  -y

rd /s /q %USERPROFILE%\.docker\
rd /s /q %USERPROFILE%\.kube\
rd /s /q %USERPROFILE%\.minikube\
rd /s /q %USERPROFILE%\.VirtualBox\

@nojaja
Copy link
Author

nojaja commented Jan 29, 2021

$NO_PROXY がもっとサンプルだとわかりやすい値に変更

@nojaja
Copy link
Author

nojaja commented Jan 29, 2021

表現変えとく

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment