0
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Red Hat OpenShift Study - (2)OpenShift CLI(oc)を使ってみる

Last updated at Posted at 2020-08-20

はじめに

OpenShiftお勉強のログです。
前回Windows10上にOpenShift CodeReady Containersを構築しようとしましたが、Hiper-V環境に切り替えるのも鬱陶しいしマシンスペックも厳しいし挙動も不安定なので、IBM Cloud上のOpenShiftクラスター(マネージドサービス)を使ってみることにします。これは無償の範囲で使えるプランがないので環境準備がなかなかしんどいのですが。
ここでは、IBM Cloud上のOpenShift環境に対して、Windowsから主にOpenShift CLI(oc)を使った簡単な操作を試してみます。具体的にはKubernetes(kubectl)と同じイメージでPod関連の単純な操作、および、OpenShift特有のリソースである"アプリケーション"についての操作、といった辺りを試してみます。

関連記事

Red Hat OpenShift Study - (1)CodeReady Containers on Windows10
Red Hat OpenShift Study - (2)Windows10上でOpenShift CLI(oc)を使ってみる

参考情報

公式ドキュメント
https://docs.openshift.com/container-platform/4.3/welcome/index.html
https://access.redhat.com/documentation/ja-jp/openshift_container_platform/4.3/

環境

OpenShift V4.3.28_1532(IBM Cloud上のマネージドサービス)
Windows10, OpenShift CLI V4.3.23

image.png

OpenShift CLI(oc)のインストール

回り道のログ...

参考: CLIのインストール

以下にアクセスしてRedHatのアカウントでログインし、Run on BareMetalを選択
https://cloud.redhat.com/openshift/install
image.png

Command line interface以下からWindowsを選択してDownload command-line toolsをクリック
image.png

openshift-client-windows.zipがダウンロードされるので、適当な場所に解凍します。oc.exeが展開されるので、PATHを通しておきます。

c:\>oc version
Client Version: 4.5.3
Unable to connect to the server: dial tcp: lookup api.crc.testing: no such host

ん???最新版を入手しちゃったっぽい。今回管理対象のOpenShiftは4.3なんだが。

そもそもCLIのバージョンとOpenShift本体(サーバー)のバージョンってどの程度気にする必要あんのかしら。
ということでマニュアル漁ると以下の記述がありました。
OpenShift Container Platform Versioning Policy
image.png
これによると、サーバー側のバージョンが高い場合(②)アクセスできない場合があるらしい。クライアント側のバージョンが高い場合(③)はサーバーで互換性のないオプションが提供される可能性があると。

ま、クライアント側が高い分には良さそうですが、合わせておくのが無難なので、4.3のクライアントの入手方法を探します。以下に各バージョンのocダウンロードサイトのリンクありました。というかIBM Cloud環境のOpenShift使うならはじめからこっちを見ろということか。
Red Hat OpenShift on IBM Cloud - Installing the OpenShift CLI
V4系はこちら
https://mirror.openshift.com/pub/openshift-v4/clients/oc/

V4.3だと4.3.23というのが一番新しいようなのでそこからWindows版のoc.zipをダウンロードして展開しPATHを修正。

c:\>oc version
Client Version: 4.3.23-202005230952-4fb2d4d
Unable to connect to the server: dial tcp: lookup api.crc.testing: no such host

ocコマンドが実行できるようになりました。

ocコマンドの利用

ocコマンドはkubectlの拡張のような位置づけのようです。kubectlで実行できる操作に加えてOpenShift特有のリソースの操作などができるようになっています。

参考:
oc および kubectl コマンドの使用
[Kubernetes と OpenShift の違いを確かめてみた] (https://qiita.com/MahoTakara/items/394bb7518d86ea0dd2c7)

ログインその1 / token指定でのログイン

ocコマンドで各種操作を行う前に操作対象のクラスターにログインします。ログインするための情報は以下の手順でOpenShift Webコンソールから確認できます。

token取得

IBM Cloud - クラスター から対象のOpenShiftクラスターを選択し、OpenShift Webコンソールをクリック
image.png

OpenShiftのWebコンソールが開きます。右上のユーザー名の所のプルダウンメニューから、Copy Login Commandを選択。
image.png

Display Tokenをクリック
image.png

以下のようにoc loginコマンドの雛形が表示されるのでそれをコピー
image.png

token指定でOpenShiftクラスターにログイン

Windowsのコマンドプロンプトでコピーしたコマンドを実行

c:\>oc login --token=Ixxxxk --server=https://xxxxx.cloud.ibm.com:nnnnnn
Logged into "https://xxxxx.cloud.ibm.com:nnnnn" as "IAM#tomxxx@xxx.com" using the token provided.

You have access to 70 projects, the list has been suppressed. You can list all projects with 'oc projects'

Using project "default".

ログインできました。

ログインその2 / apikey指定でのログイン

上の方法だと、tokenの有効期限が1日くらいしか無いようなので、expireした場合その都度tokenを確認しないといけません。
それ以外にもいくつかログインする方法はあるようです。
参考: CLI からクラスターへの接続
ここでは、以下の記述に従って、APIキーを使用したログインを試してみます。
参考: API キーを使用した OpenShift クラスターへのログイン

IBM Cloud CLI インストール

以下の手順に従ってIBM Cloud CLIをインストールします。
参考:https://cloud.ibm.com/docs/cli?topic=cli-getting-started

PowerShellから以下のコマンド実行。

PS C:\WINDOWS\system32> [Net.ServicePointManager]::SecurityProtocol = "Tls12, Tls11, Tls, Ssl3"; iex(New-Object Net.WebClient).DownloadString('https://ibm.biz/idt-win-installer')                                                              [main] --==[ IBM Cloud Developer Tools - Installer for Windows, v1.2.2 ]==--                                            [install] Starting Installation/Update...                                                                               C:\Program Files\IBM\Cloud\bin\ibmcloud.exe : 用語 'C:\Program Files\IBM\Cloud\bin\ibmcloud.exe' は、コマンドレット、関
数、スクリプト ファイル、または操作可能なプログラムの名前として認識されません。名前が正しく記述されていることを確認し、
パスが含まれている場合はそのパスが正しいことを確認してから、再試行してください。
発生場所 行:1 文字:1
+ C:\"Program Files"\IBM\Cloud\bin\ibmcloud.exe plugin list
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Program File...in\ibmcloud.exe:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

[install_deps] Checking for external dependency: git
[install_deps] Checking for external dependency: docker
[install_deps] Installing/updating external dependency: docker
[install_deps] Install/update completed for: docker
[install_deps] Checking for external dependency: kubectl
[install_deps] Installing/updating external dependency: kubectl


    ディレクトリ: C:\Program Files


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2020/08/03     17:38                kubectl
[add_to_path] Adding C:\Program Files\kubectl to PATH
[install_deps] Install/update completed for: kubectl
[install_deps] Checking for external dependency: helm
[install_deps] Installing/updating external dependency: helm
[install_deps] Helm URL : https://get.helm.sh/helm-v3.3.0-rc.2-windows-amd64.zip
[install_deps] Helm File: helm-v3.3.0-rc.2-windows-amd64.zip
d-----       2020/08/03     17:38                helm
[add_to_path] Adding C:\Program Files\helm\windows-amd64 to PATH
[install_deps] Install/update completed for: helm
[install_ibmcloud] Installing 'ibmcloud' CLI for Windows...
[install_ibmcloud] Downloading and installing 'ibmcloud' CLI from: https://clis.cloud.ibm.com/install/powershell
Current platform is Win64. Downloading corresponding IBM Cloud CLI...
Download complete. Executing installer...
Install complete. Please restart to make the modification effective.
[install_ibmcloud] IBM Cloud CLI version:
C:\Program Files\IBM\Cloud\bin\ibmcloud.exe version 1.1.0+cc908fe-2020-04-29T04:06:12+00:00
[install_plugins] Installing/updating IBM Cloud CLI plugins...
[install_plugins] Checking status of plugin: Cloud-Functions
[install_plugins] Installing plugin 'Cloud-Functions'
リポジトリー 'IBM Cloud' から 'Cloud-Functions' を検索しています...
プラグイン 'cloud-functions/wsk/functions/fn 1.0.44' がリポジトリー 'IBM Cloud' 内で見つかりました
バイナリー・ファイルをダウンロードしようとしています...
 14.14 MiB / 14.14 MiB [================================================================================] 100.00% 2m55s
14823424 バイトがダウンロードされました
バイナリーをインストールしています...
OK
プラグイン 'cloud-functions 1.0.44' は C:\Users\TomohiroTaguchi\.bluemix\plugins\cloud-functions に正常にインストールさ れました。 'C:\Program Files\IBM\Cloud\bin\ibmcloud.exe plugin show cloud-functions' を使用して詳細を表示してください。
[install_plugins] Checking status of plugin: container-registry
[install_plugins] Installing plugin 'container-registry'
リポジトリー 'IBM Cloud' から 'container-registry' を検索しています...
プラグイン 'container-registry 0.1.485' がリポジトリー 'IBM Cloud' 内で見つかりました
バイナリー・ファイルをダウンロードしようとしています...
 28.57 MiB / 28.57 MiB [================================================================================] 100.00% 4m39s
29956608 バイトがダウンロードされました
バイナリーをインストールしています...
OK
プラグイン 'container-registry 0.1.485' は C:\Users\TomohiroTaguchi\.bluemix\plugins\container-registry に正常にインストールされました。 'C:\Program Files\IBM\Cloud\bin\ibmcloud.exe plugin show container-registry' を使用して詳細を表示してください。
[install_plugins] Checking status of plugin: container-service
[install_plugins] Installing plugin 'container-service'
リポジトリー 'IBM Cloud' から 'container-service' を検索しています...
プラグイン 'container-service/kubernetes-service 1.0.118' がリポジトリー 'IBM Cloud' 内で見つかりました
バイナリー・ファイルをダウンロードしようとしています...
 21.80 MiB / 21.80 MiB [================================================================================] 100.00% 4m24s
22859264 バイトがダウンロードされました
バイナリーをインストールしています...
OK
プラグイン 'container-service 1.0.118' は C:\Users\TomohiroTaguchi\.bluemix\plugins\container-service に正常にインストールされました。 'C:\Program Files\IBM\Cloud\bin\ibmcloud.exe plugin show container-service' を使用して詳細を表示してくだ さい。
[install_plugins] Running 'ibmcloud plugin list'...
インストール済みプラグインをリストしています...

プラグイン名                           バージョン   状況
container-registry                     0.1.485
container-service/kubernetes-service   1.0.118
cloud-functions/wsk/functions/fn       1.0.44

[install_plugins] Finished installing/updating plugins
Creating 'ic' script to act as shortcut to 'ibmcloud' command...
[install] Install finished.
[quit] --==[ Finished. Total time: 00:27:08 seconds ]==--

A system restart is required. Would you like to restart now (y/N)?:

なんだか勝手にいろんなものをインストールしてくれちゃってちとうざいです。Dockerとか入れられても困るんですが。Virtual Box使ってるからHyper-V有効化したくないし。とりあえず途中で以下のようなポップアップが出てくるのでEnable Hyper-Vのチェックははずす。
image.png
以下の「Close and log out」ボタンを押しちゃうとWindowsからログアウトしようとしちゃうので注意!PowerShellのスクリプト終了するのを待ちましょう。
image.png

最終的に終わったらOS再起動が必要。

再起動後コマンドプロンプトでibmcloudコマンド打ってみます。

c:\>ibmcloud -v
ibmcloud version 1.1.0+cc908fe-2020-04-29T04:06:12+00:00

OKですね。

IBM Cloudにログイン

ibmcloudコマンドで、IBM Cloudにログインします。フェデレーテッドIDを使っているので--ssoオプション付きでログインします。

c:\>ibmcloud login --sso
API エンドポイント: https://cloud.ibm.com
地域: jp-tok

https://identity-2.ap-north.iam.cloud.ibm.com/identity/passcode からワンタイム・コードを取得して、続行します。
デフォルトのブラウザーで URL を開きますか? [Y/n] > Y
One Time Code >
認証中です...
OK

アカウントを選択:
1. Tomohiro Taguchi's Account (xxxxxxxxxxxxxxxxx)
2. XXX - XXXXXXXXXXXXXXXXXX (xxxxxxxxxxxxxxxxxxxxxxxx) <-> 1378943
3. XXX - xxxxxxxxxxxxxxxxxx (xxxxxxxxxxxxxxxxxxxxxxxx) <-> 423632
4. XXX (xxxxxxxxxxxxxxxxxxxx) <-> 1707641
数値を入力してください> 4
ターゲットのアカウント XXX (xxxxxxxxxxxxxxxxxx) <-> 1707641


API エンドポイント:      https://cloud.ibm.com
地域:                    jp-tok
ユーザー:                XXXX@xx.xx.com
アカウント:              XXX (xxxxxxxxxxxxx) <-> 1707641
リソース・グループ:      リソース・グループがターゲットになっていません。'ibmcloud target -g RESOURCE_GROUP' を使用して ください
CF API エンドポイント:
組織:
スペース:

c:\>

途中ブラウザが開いてユーザー認証するとワンタイム・パスコードが表示されるので、それをコピーして入力します。
認証が通ってアカウントを選択するとログイン完了です。アカウントはOpenShiftクラスターが構成されているアカウントを選択します。

API key作成

以下のコマンドでAPI Keyを作成します。名前は適当に付ければOK。

c:\>ibmcloud iam api-key-create taguchi_oc_key01
XXXXX@xx.xx.com として 1fc8373f538a408187ffedbe62e5796a に API キー taguchi_oc_key01 を作成しています...
OK
API キー taguchi_oc_key01 が作成されました

API キーを保存してください。 作成後に取得することはできません。

ID         ApiKey-xxxxxxxxxxxxxxxxxxxxxxxx
名前       taguchi_oc_key01
説明
作成日時   2020-08-04T07:42+0000
API キー   xxxxxxxxxxxxxxxxxx
ロック中   false

ここで生成されたAPIキーは恐らくここでしか表示されず後から確認できません。他人に見せないよう大事に保管しておいてください。
apikeyでibmcloudにログインします。

c:\>ibmcloud login --apikey xxxxxxxxxxxxxxxxxx
API エンドポイント: https://cloud.ibm.com
地域: jp-tok
認証中です...
OK

ターゲットのアカウント XXX (xxxxxxxxxxxxxxxxxx) <-> 1707641


API エンドポイント:      https://cloud.ibm.com
地域:                    jp-tok
ユーザー:                XXXXX@xx.xx.com
アカウント:              XXX (xxxxxxxxxxxxxxxxxxxxxxxxxx) <-> 1707641
リソース・グループ:      リソース・グループがターゲットになっていません。'ibmcloud target -g RESOURCE_GROUP' を使用して ください
CF API エンドポイント:
組織:
スペース:

kubeconfigファイル設定

以下のコマンドを実行します。

c:\>ibmcloud oc cluster config -c xxxxxcluster-tok04-b3c.4x16
Kubernetes removed deprecated APIs, which impacts clusters that run Kubernetes version 1.16, OpenShift version 4.4, or later. For more information, see <http://ibm.biz/k8s-1-16-apis>

If you have IBM Cloud Kubernetes Service clusters that run version 1.14 or 1.15, update them now to continue receiving important security updates and support. Version 1.15 is deprecated and will be unsupported 12 September 2020. Versions 1.14 and earlier are already unsupported. For more information and update actions, see <https://ibm.biz/iks-versions>

OK
xxxxxcluster-tok04-b3c.4x16 の構成は正常にダウンロードされました。

xxxxxcluster-tok04-b3c.4x16 のコンテキストを現在の kubeconfig ファイルに追加しました。
これで、クラスターに対して「kubectl」コマンドを実行できます。 例えば、「kubectl get nodes」を実行します。

kubectlでkubernetesクラスターにアクセスする際に使用する接続先の情報は、kubeconfigファイル(~/.kube/config)で管理されるようで、ocコマンドでもこれがそのまま使われるようです。
参考: kubectlの接続設定ファイル(kubeconfig)の概要

上のコマンドを実行すると接続先のOpenShiftクラスターの接続情報がこのファイルに追加されるようです。

API KeyでOpenShiftクラスターにログイン

ここまでの設定をしておけば、apikeyでOpenShiftクラスターにログインできるようになります。

oc loginコマンドでapikeyを指定してログイン

c:\>oc login -u apikey -p xxxxxxxxxxxxxxxxxxxxxxxxxx
Login successful.

You have access to 71 projects, the list has been suppressed. You can list all projects with 'oc projects'

Using project "default".

ログインできました!

ocコマンド実行例

help
c:\>oc --help
OpenShift Client

This client helps you develop, build, deploy, and run your applications on any
OpenShift or Kubernetes cluster. It also includes the administrative
commands for managing a cluster under the 'adm' subcommand.

Usage:
  oc [flags]

Basic Commands:
  login           Log in to a server
  new-project     Request a new project
  new-app         Create a new application
  status          Show an overview of the current project
  project         Switch to another project
  projects        Display existing projects
  explain         Documentation of resources

Build and Deploy Commands:
  rollout         Manage a Kubernetes deployment or OpenShift deployment config
  rollback        Revert part of an application back to a previous deployment
  new-build       Create a new build configuration
  start-build     Start a new build
  cancel-build    Cancel running, pending, or new builds
  import-image    Imports images from a container image registry
  tag             Tag existing images into image streams

Application Management Commands:
  create          Create a resource from a file or from stdin.
  apply           Apply a configuration to a resource by filename or stdin
  get             Display one or many resources
  describe        Show details of a specific resource or group of resources
  edit            Edit a resource on the server
  set             Commands that help set specific features on objects
  label           Update the labels on a resource
  annotate        Update the annotations on a resource
  expose          Expose a replicated application as a service or route
  delete          Delete resources by filenames, stdin, resources and names, or by resources and label selector
  scale           Change the number of pods in a deployment
  autoscale       Autoscale a deployment config, deployment, replication controller, or replica set
  secrets         Manage secrets
  serviceaccounts Manage service accounts in your project

Troubleshooting and Debugging Commands:
  logs            Print the logs for a resource
  rsh             Start a shell session in a container.
  rsync           Copy files between local filesystem and a pod
  port-forward    Forward one or more local ports to a pod
  debug           Launch a new instance of a pod for debugging
  exec            Execute a command in a container
  proxy           Run a proxy to the Kubernetes API server
  attach          Attach to a running container
  run             Run a particular image on the cluster
  cp              Copy files and directories to and from containers.
  wait            Experimental: Wait for a specific condition on one or many resources.

Advanced Commands:
  adm             Tools for managing a cluster
  replace         Replace a resource by filename or stdin
  patch           Update field(s) of a resource using strategic merge patch
  process         Process a template into list of resources
  extract         Extract secrets or config maps to disk
  observe         Observe changes to resources and react to them (experimental)
  policy          Manage authorization policy
  auth            Inspect authorization
  convert         Convert config files between different API versions
  image           Useful commands for managing images
  registry        Commands for working with the registry
  idle            Idle scalable resources
  api-versions    Print the supported API versions on the server, in the form of "group/version"
  api-resources   Print the supported API resources on the server
  cluster-info    Display cluster info
  diff            Diff live version against would-be applied version
  kustomize       Build a kustomization target from a directory or a remote url.

Settings Commands:
  logout          End the current server session
  config          Change configuration files for the client
  whoami          Return information about the current session
  completion      Output shell completion code for the specified shell (bash or zsh)

Other Commands:
  ex              Experimental commands under active development
  help            Help about any command
  plugin          Provides utilities for interacting with plugins.
  version         Print the client and server version information

Use "oc <command> --help" for more information about a given command.
Use "oc options" for a list of global command-line options (applies to all commands).
c:\>oc get clusterversion
NAME      VERSION   AVAILABLE   PROGRESSING   SINCE   STATUS
version   4.3.31    True        False         14d     Cluster version is 4.3.31
c:\>oc status
In project default on server https://xxx.containers.cloud.ibm.com:nnn

svc/openshift - kubernetes.default.svc.cluster.local
svc/openshift-apiserver - 172.21.86.216:443
svc/kubernetes - 172.21.0.1:443 -> 2040

View details with 'oc describe <resource>/<name>' or list everything with 'oc get all'.
c:\>oc describe svc/openshift
Name:              openshift
Namespace:         default
Labels:            <none>
Annotations:       <none>
Selector:          <none>
Type:              ExternalName
IP:
External Name:     kubernetes.default.svc.cluster.local
Session Affinity:  None
Events:            <none>

c:\>oc describe svc/openshift-apiserver
Name:              openshift-apiserver
Namespace:         default
Labels:            <none>
Annotations:       kubectl.kubernetes.io/last-applied-configuration:
                     {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"name":"openshift-apiserver","namespace":"default"},"spec":{"ports":[{"na...
Selector:          <none>
Type:              ClusterIP
IP:                172.21.86.216
Port:              https  443/TCP
TargetPort:        443/TCP
Endpoints:         172.19.165.135:443
Session Affinity:  None
Events:            <none>

c:\>oc describe svc/kubernetes
Name:              kubernetes
Namespace:         default
Labels:            component=apiserver
                   provider=kubernetes
Annotations:       <none>
Selector:          <none>
Type:              ClusterIP
IP:                172.21.0.1
Port:              https  443/TCP
TargetPort:        2040/TCP
Endpoints:         172.20.0.1:2040
Session Affinity:  None
Events:            <none>
c:\>oc get all
NAME                          TYPE           CLUSTER-IP      EXTERNAL-IP                            PORT(S)   AGE
service/kubernetes            ClusterIP      172.21.0.1      <none>                                 443/TCP   51d
service/openshift             ExternalName   <none>          kubernetes.default.svc.cluster.local   <none>    51d
service/openshift-apiserver   ClusterIP      172.21.86.216   <none>                                 443/TCP   51d
c:\>oc config get-contexts
CURRENT   NAME                                                                          CLUSTER                                        AUTHINFO                                                              NAMESPACE
          /api-crc-testing:6443/developer                                               api-crc-testing:6443                           developer/api-crc-testing:6443
          default/api-crc-testing:6443/kube:admin                                       api-crc-testing:6443                           kube:admin/api-crc-testing:6443                                       default
*         default/xxxxxcontainers-cloud-ibm-com:nnn/IAM#tomxxx@xxx.com                  xxxxxcontainers-cloud-ibm-com:nnnnn            IAM#tomxxx@xxx.com/c100-e-jp-tok-containers-cloud-ibm-com:30570       default
c:\>oc get node
NAME            STATUS   ROLES           AGE   VERSION
10.192.54.222   Ready    master,worker   53d   v1.16.2
10.192.54.231   Ready    master,worker   53d   v1.16.2

ocコマンドでOpenshiftコンソール接続用のURLを確認する方法

c:\>oc whoami --show-console
https://console-openshift-console.x15kcluster-tok04-xxxxx.jp-tok.containers.appdomain.cloud

プロジェクト

参考: OpenShiftとKubernetesのちがうところ

Kubernetesではnamespaceという考え方でリソースのセットを分離してプロジェクト毎やフェーズ毎に管理することができますが、OpenShiftではそれを拡張して"プロジェクト"という考え方で管理できるようです。

c:\>oc new-project taguchi02
Now using project "taguchi02" on server "https://xxxxxx.containers.cloud.ibm.com:nnnnn".

You can add applications to this project with the 'new-app' command. For example, try:

    oc new-app django-psql-example

to build a new example application in Python. Or use kubectl to deploy a simple Kubernetes application:

    kubectl create deployment hello-node --image=gcr.io/hello-minikube-zero-install/hello-node


c:\>oc project taguchi02
Already on project "taguchi02" on server "https://xxxxx.containers.cloud.ibm.com:nnnnn".

c:\>oc get all
No resources found in taguchi02 namespace.

taguchi02というプロジェクトを作ってそのプロジェクトに切替ます。プロジェクト作ったばかりでリソースは何もないので、oc get allすると何もない状態です。

ちなみに上のようにtaguchi02というプロジェクトを作成すると、taguchi02というnamespaceも勝手に作られていました。
(oc get namespace, oc get projectでnamespace, projectのリストを確認してみると、同じものがリストされていました。)

単純なPodの稼働

まずは、Kubernetesと同じ操作イメージでPodを動かしてみます。
以下のようなPod管理用のマニフェストファイルを作成します。

nginx-pod.yml
apiVersion: v1
kind: Pod
metadata:
 name: nginx
spec:
 containers:
 - name: nginx
   image: nginx:latest

適用します。

c:\y\OpenShift\pod_test01>oc apply -f nginx-pod.yml
pod/nginx created

確認してみます。

c:\y\OpenShift\pod_test01>oc get pod -o wide
NAME    READY   STATUS    RESTARTS   AGE   IP               NODE            NOMINATED NODE   READINESS GATES
nginx   1/1     Running   0          33m   172.30.125.195   10.192.54.231   <none>           <none>

OpenShiftコンソールからもこんな感じに確認できます。
image.png

ただ、このPodにアサインされているIPアドレスはクラスターネットワーク上で閉じているので、このままだとホストOSや外部からアクセスできません。外からアクセスさせるためにはいくつか方法がありますが、例えば別途Kubernetesの"サービス"というオブジェクトを使用するといったやり方があります。
ここでは、busyboxという各種コマンドを備えた軽量なコンテナを踏み台にして確認してみます。

busybox用のPodを起動してshで接続

c:\y\OpenShift\pod_test01>oc run busybox --image=busybox --restart=Never --rm -it sh
If you don't see a command prompt, try pressing enter.
/ #       

この時点で別コマンドプロンプトからPodの状況を確認してみます。

c:\>oc get pod -o wide
NAME      READY   STATUS    RESTARTS   AGE     IP               NODE            NOMINATED NODE   READINESS GATES
busybox   1/1     Running   0          3m38s   172.30.125.227   10.192.54.231   <none>           <none>
nginx     1/1     Running   0          41m     172.30.125.195   10.192.54.231   <none>           <none>

nginxが動いているPodと踏み台用のbusyboxが動いているpodの2つが稼働していることが分かります。

元のウィンドウに戻ってbusyboxのシェルから、nginxにアクセスしてみます。
busyboxにはcurlが入っていないようなのでwgetで確認します。

/ # wget -q -O - http://172.30.125.195
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

busyboxというPodからnginxにアクセスできることが確認できました。
やってることのイメージとしてはこんな感じです。
image.png

この辺はkubernetesの環境でkubectlでできる操作と同じですね。

hello-worldアプリ

OpenShiftでは"アプリケーション"というリソースがあり、例えばGitHubに置いてあるアプリのソースやDockerfileなどを元にdockerイメージを作成してPodやらサービスやら関連するリソースを動かす、というようなことがサクッと簡単にできるようになっています。
ここではその辺りを試してみます。

参考:
レッスン 3: OpenShift クラスターにアプリをデプロイする
2.3. CLI を使用したアプリケーションの作成

hello-worldのアプリをOpenShift上に動かしてみます。ソースは以下のLab 1以下のものを使います。
container-service-getting-started-wt

このLab 1には、以下のようなDockerfile(node.js実行環境をdocker imageとして使用)と、そこで動かすnode.jsのソースが提供されています。
Dockerfile

oc new-appで上のソースを元にアプリケーションを作成します。

c:\y\OpenShift>oc new-app --name hello-world https://github.com/IBM/container-service-getting-started-wt --context-dir="Lab 1"
--> Found container image b5f9499 (2 years old) from Docker Hub for "node:9.4.0-alpine"

    * An image stream tag will be created as "node:9.4.0-alpine" that will track the source image
    * A Docker build using source code from https://github.com/IBM/container-service-getting-started-wt will be created
      * The resulting image will be pushed to image stream tag "hello-world:latest"
      * Every time "node:9.4.0-alpine" changes a new build will be triggered
    * This image will be deployed in deployment config "hello-world"
    * Port 8080/tcp will be load balanced by service "hello-world"
      * Other containers can access this service through the hostname "hello-world"
    * WARNING: Image "node:9.4.0-alpine" runs as the 'root' user which may not be permitted by your cluster administrator

--> Creating resources ...
    imagestream.image.openshift.io "node" created
    imagestream.image.openshift.io "hello-world" created
    buildconfig.build.openshift.io "hello-world" created
    deploymentconfig.apps.openshift.io "hello-world" created
    service "hello-world" created
--> Success
    Build scheduled, use 'oc logs -f bc/hello-world' to track its progress.
    Application is not exposed. You can expose services to the outside world by executing one or more of the commands below:
     'oc expose svc/hello-world'
    Run 'oc status' to view your app.

ステータスを見てみます。

c:\y\OpenShift>oc status
In project taguchi02 on server https://c100-e.jp-tok.containers.cloud.ibm.com:30570

svc/hello-world - 172.21.24.242:8080
  dc/hello-world deploys istag/hello-world:latest <-
    bc/hello-world docker builds https://github.com/IBM/container-service-getting-started-wt on istag/node:9.4.0-alpine
    deployment #1 deployed 51 seconds ago - 1 pod

pod/nginx runs nginx:latest


2 infos identified, use 'oc status --suggest' to see details.

先に作成したnginxのPodとは別に、svc/hello-worldというのが出来ています。

リソースを見てみます。

c:\y\OpenShift>oc get all -o wide
NAME                       READY   STATUS      RESTARTS   AGE     IP               NODE            NOMINATED NODE   READINESS GATES
pod/hello-world-1-8h5hw    1/1     Running     0          5m27s   172.30.125.241   10.192.54.231   <none>           <none>
pod/hello-world-1-build    0/1     Completed   0          6m14s   172.30.208.187   10.192.54.222   <none>           <none>
pod/hello-world-1-deploy   0/1     Completed   0          5m28s   172.30.208.169   10.192.54.222   <none>           <none>
pod/nginx                  1/1     Running     0          82m     172.30.125.195   10.192.54.231   <none>           <none>

NAME                                  DESIRED   CURRENT   READY   AGE     CONTAINERS    IMAGES                                                                                                                                           SELECTOR
replicationcontroller/hello-world-1   1         1         1       5m29s   hello-world   image-registry.openshift-image-registry.svc:5000/taguchi02/hello-world@sha256:32cd4008d22484d48f0e0b291b0e5b7549f3c696601ae3a301b42e0a9f46093c   deployment=hello-world-1,deploymentconfig=hello-world

NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE     SELECTOR
service/hello-world   ClusterIP   172.21.24.242   <none>        8080/TCP   6m16s   deploymentconfig=hello-world

NAME                                             REVISION   DESIRED   CURRENT   TRIGGERED BY
deploymentconfig.apps.openshift.io/hello-world   1          1         1         config,image(hello-world:latest)

NAME                                         TYPE     FROM   LATEST
buildconfig.build.openshift.io/hello-world   Docker   Git    1

NAME                                     TYPE     FROM          STATUS     STARTED         DURATION
build.build.openshift.io/hello-world-1   Docker   Git@9312385   Complete   6 minutes ago   45s

NAME                                         IMAGE REPOSITORY                                                         TAGS           UPDATED
imagestream.image.openshift.io/hello-world   image-registry.openshift-image-registry.svc:5000/taguchi02/hello-world   latest         5 minutes ago
imagestream.image.openshift.io/node          image-registry.openshift-image-registry.svc:5000/taguchi02/node          9.4.0-alpine   6 minutes ago

hello-world用のPodが稼働し、外部アクセス用のサービスなどが作成されています。

さて、これを外部からアクセスするためにRouteというリソースを作成します。これもOpenShift特有のリソースのようで、KubernetesのIngressに近いイメージのもののようです。
複数のPodに対する経路設定や名前解決を行う"サービス"というリソースがありますが、これを外部向けに公会するためのもの、という位置づけのようです。

参考:
OpenShift バージョン 4 での経路を使用したアプリの公開
Kubernetes Ingress vs OpenShift Route
Kubernetes の LoadBalancer, Ingress と OpenShift の Routes の仕組み
サービスについての整理

route作成

c:\y\OpenShift>oc create route edge --service=hello-world
route.route.openshift.io/hello-world created

作成されたrouteの確認

c:\y\OpenShift>oc get route -o wide
NAME          HOST/PORT                                                                                                                 PATH   SERVICES      PORT       TERMINATION   WILDCARD
hello-world   hello-world-taguchi02.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.jp-tok.containers.appdomain.cloud          hello-world   8080-tcp   edge          None

このパスに対してcurlでアクセスしてみます。

c:\y\OpenShift>curl https://hello-world-taguchi02.xxxxxx.jp-tok.containers.appdomain.cloud
Hello world from hello-world-1-8h5hw! Your app is up and running in a cluster!

アプリにアクセスできました!経路としてはこんな感じだと思われます。(細かいところはおいおい調べていきます)
image.png

ちなみに、OpenShiftコンソールからアプリケーションを見るとこんな感じで確認できます。
image.png

0
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?