Cozy
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Docker/Kubanetes 実践コンテナ開発入門 第5章 Kubernates入門 # 自己紹介 ささきこうじ 2019/11 から Pythonでデータ分析(需要予測)の仕事をしています。 以前はJavaでインターネット損保の申込/契約者サイトを作ったり、保険契約者向けのAndroidアプリを作ったりしてました。 @coozy_corner https://github.com ![](https://i.imgur.com/yNl8ClF.jpg) ### Docker/Kubernetes に興味を持ったきっかけ 仕事の勉強用に、MacにPythonの機械学習環境(Anaconda)を入れたところ、趣味のRailsで使っていた npm (Node.jsのパッケージ管理)がバージョンアップできなくなった! (Anacondaは Python3系に依存、npmはPython2系に依存。) クリーンな環境で快適に開発したい! ↓ いろんな言語、アプリの開発環境を独立させたい ↓ dockerを使うとできるらしい ### 業務での Docker/Kubernates の活用 普段、Azure上の機械学習環境で作業している。時々、レスポンスが重くなるのでローカルの Windows/Docker上で開発している。 kubernetesは触ったことなし。 # 5.1 Kubernetesとは Google が作ったコンテナの運用を自動化するためのコンテナオーケストレーションシステム![](https://i.imgur.com/0Oc3BZy.png) 以下、クベと呼びます。 ## オーケストレーションて何? https://ja.wikipedia.org/wiki/オーケストレーション_(コンピュータ) オーケストレーション(英: orchestration)は、複雑なコンピュータシステム/ミドルウェア/サービスの配備/設定/管理の自動化を指す用語。 ## dockerdって何? docker daemon のこと 仮想環境全体を制御する管理機能的役割を果たすコンポーネント。 縁の下の力持ち。OSで言うところのカーネル。 ![](https://i.imgur.com/8DXpRTD.jpg) ## クベで何ができるの? こんなことができるようになる。 * 複数のDockerホストの管理 * コンテナのスケジューリング ![](https://i.imgur.com/KfBMxhr.jpg) * ローリングアップデート * スケーリング / オートスケーリング ![](https://i.imgur.com/FpywOfy.jpg) * コンテナの死活監視 * 障害時のセルフヒーリング![](https://i.imgur.com/XaYcVCA.jpg) * サービスディスカバリ * ロードバランシング * データの管理 * ワークロードの管理 * ログの管理 * Infrastructure as Code * その他エコシステムとの連携や拡張 https://thinkit.co.jp/article/13289 ## Docker Swarm と何が違うの? どちらも役割は同じ。 KubernetesはCompose/Stack/Swarmの機能を統合しつつ、より高度に管理できるもの。詳しくはこの後。 5.4 のノードのところでも少し触れます。 * Compose マルチコンテナ運用 * Stack サービスをグルーピングした単位。アプリケーション全体の構成。 * Swarm Docker Hostのクラスタリング ※ 知り合いの話では、Swarm を本番環境で使うことはあまりないらしい。 # 5.2 ローカル環境でKubernetesを実行する !Macで書籍の通りにインストールを行ったところ、kubectl でエラーが出た。 mac 10.14.6(Mojave) bash 3.2.57 kubernates ``` kubectl apply -f /usr/local/bin/kubectl: line 1: syntax error near unexpected token `<' /usr/local/bin/kubectl: line 1: `<?xml version='1.0' encoding='UTF-8'?><Error><Code>NoSuchBucket</Code><Message>The specified bucket does not exist.</Message></Error>' ``` 以下の通り homebrew でインストールしたら上手くいった。 https://scble.net/2019/03/27/kubectl-syntax-error-near-unexpected-token/ ※ !ダッシュボードにサインインする方法がよくわからない (書籍ではサインインの方法に関する記述なし。自己証明書を作ってhttpsでアクセスしないといけなくなったらしい) http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/#!/overview?namespace=default Dashboardのサービスアカウントに管理者権限を付与する こちらを参考に サインインをSKIPしました。 (開発で使う人はちゃんと設定してください。) https://www.it-swarm.net/ja/kubernetes/kubernetes%E3%83%80%E3%83%83%E3%82%B7%E3%83%A5%E3%83%9C%E3%83%BC%E3%83%89%E3%81%AB%E3%82%B5%E3%82%A4%E3%83%B3%E3%82%A4%E3%83%B3%E3%81%99%E3%82%8B%E3%81%AB%E3%81%AF%E3%81%A9%E3%81%86%E3%81%99%E3%82%8C%E3%81%B0%E3%81%84%E3%81%84%E3%81%A7%E3%81%99%E3%81%8B%EF%BC%9F/833861828/ ![](https://i.imgur.com/RZ3dyff.png) # 5.3 Kubernetes の概念 # 5.4 KubernetesクラスタとNode ## Nodeとは クラスタの管理下のDockerホストのこと クラスタにはMasterが最低1つ含まれる GCPではGCE, AWSではEC2のインスタンスがNodeに当たる。パブリッククラウドではマスターノードはマネージドサービスで提供されており、あまり意識することはないとのこと。 ![](https://i.imgur.com/tYYW6ep.png) ※参考 Swarm Swarmではマネージャーは管理人だけだなくワーカー(アプリケーション)の役割を持てる。 KubeではマスターNodeは管理しかしない。(選手兼監督はダメ) ![](https://i.imgur.com/8ZJwbtP.png) # 5.5 Namespace クラスタの中の入れ子となる仮想的なクラスタのこと チーム開発で有用。 全てのオブジェクトはネームスペースに属しているとは限らない。 https://kubernetes.io/ja/docs/concepts/overview/working-with-objects/namespaces/ # 5.6 Pod Dockerコンテナの集合体のこと。(1つのコンテナの場合もある) Podは Nodeに配置される。 ![](https://i.imgur.com/U26hMij.png) ## 5.6.1 Podを作成してデプロイする ``` apiVersion: v1 kind: Pod # リソースの種類 metadata: name: simple-echo spec: # リソースを定義 containers: # Podを構成するコンテナ - name: nginx image: gihyodocker/nginx:latest env: - name: BACKEND_HOST value: localhost:8080 ports: # ローカルがEXPOSEするport - containerPort: 80 - name: echo image: gihyodocker/echo:latest ports: - containerPort: 8080 ``` ## 5.6.2 Podを操作する ### Podの一覧 ``` kubectl get pod ``` ### Pod内の標準出力 `kubectl logs -f simple-echo -c echo` ### Podの削除 `kubectl delete pod simple-echo` マニュフェストファイルベースでPod削除もできる。 ``` apiVersion: v1 kind: Pod # リソースの種類 metadata: name: simple-echo spec: # リソースを定義 containers: # Podを構成するコンテナ - name: nginx image: gihyodocker/nginx:latest env: - name: BACKEND_HOST value: localhost:8080 ports: # ローカルがEXPOSEするport - containerPort: 80 - name: echo image: gihyodocker/echo:latest ports: - containerPort: 8080 ``` # 5.7 ReplicaSet 同一のPodを複数実行する仕組み ``` apiVersion: apps/v1 kind: ReplicaSet metadata: name: echo labels: app: echo spec: replicas: 3 # 作成するPod数 selector: matchLabels: app: echo template: # template以下はPodリソースにおけるspec定義と同じ metadata: labels: ~ ``` ``` kubectl get pod NAME READY STATUS RESTARTS AGE echo-hwxd5 0/2 ContainerCreating 0 13s echo-jks9g 0/2 ContainerCreating 0 13s echo-thfnt 0/2 ContainerCreating 0 13s ``` WebアプリケーションのようなステートレスなPodに向いている。 ## ReplicaSetの削除 ``` delete -f simple-replicaset.yaml ``` # 5.8 Deployment Replicasetを管理するためのリソース。 ステートレスなアプリケーションを管理するのに向いている。 (ステートフルなアプリケーションは次節のStatefulSet) ![](https://i.imgur.com/w81LL0p.png) DeploymentはReplicasetの世代管理(リビジョン付け)ができる。 ## 5.8.1 ReplicaSetライフサイクル Deploymentのマニュフェストファイルで管理する * 指定されたPod数の確保 * 新しいバージョンのPodへの入れ替え * 以前のバージョンのPodへのロールバック **Pod数を変更してもリビジョンは変わらない。** そのほかのコンテナ定義を更新するとリビジョンが変わる。 ## 5.8.2 ロールバック 特定のリビジョンの確認 ``` kubectl rollout history deployment echo --revision=1 ``` ロールバック やらかしてしまった時も安心 ``` kubectl rollout undo deployment echo ``` # 5.9 Service クラスタで Podの集合(特にReplicaSet)に対する経路やサービスディスカバリ(名前解決)を提供するためのリソース ### 特定のラベルを持つPodのみトラフィックのターゲットとする例 ``` apiVersion: v1 kind: Service metadata: name: echo spec: selector: # ターゲットとするPodを指定する app: echo release: summer ports: - name: http port: 80 ``` ![](https://i.imgur.com/whhFwP7.png) ## 5.9.1 ClusterIP Service クラスタ上の内部IPアドレスにServiceを公開できる。Podから別のPodへアクセスできる。(外からは見えない) https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0 ## 5.9.2 NodePort Service クラスタ外からアクセスできるサービス。ClusterIP Serviceにグローバルなportを開けたもの。 クラスタ上にDBサーバーを構築し、外部から参照したりする。 ## 5.9.3 LoadBalancer Service GCP, AWSなどのみ利用できるサービス。 詳しくは次節で。 ## 5.9.4 ExternalName Service クラスタ内から外部のホストを解決するためのエイリアスを提供する # 5.10 Ingress NodePort Service では L4層(TCPとか)までしか扱えない。 L7層(HTTPとか)の制御をするための仕組み。 ![](https://i.imgur.com/95iuWU0.png) ## Ingressを利用する準備 nginx_ingress_controller が必要。 書籍のURLは404 以下を参考にデプロイできました。 https://kubernetes.github.io/ingress-nginx/deploy/#docker-for-mac ## 5.10.1 Ingressを通じたアクセス ``` apiVersion: extensions/v1beta1 kind: Ingress metadata: name: echo spec: rules: - host: ch05.gihyo.local # ルーティングさせたいホスト http: paths: - path: / backend: serviceName: echo servicePort: 80 ``` アクセスを確認しようとしたら、503エラーになった。 Ingressの目的のルーティングはできているので深追いせず。 ``` curl http://localhost -H 'Host: ch05.gihyo.local' <html> <head><title>503 Service Temporarily Unavailable</title></head> <body> <center><h1>503 Service Temporarily Unavailable</h1></center> <hr><center>openresty/1.15.8.2</center> </body> </html> ``` ※ -H はhttpヘッダの指定。Hostヘッダは ドメインの特定のサーバ上のWebサーバへの疎通する時に使う。 その他にもリダイレクト,SSLなどのHTTP制御ができる。 # 感想 今のところKubernatesを業務で使う予定はないが、 コンテナの考え方の概要がわかったので、ECSなどを使う時にも役に立ちそう。 5章だけだと概念的な内容が多くて理解しにくいので、5章は軽く流して6章に入って復習しながらがいいかもしれない。 HackMDを初めて使ってみたが、なかなか使い勝手が良かった。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully