Repository: IBM/Scalable-WordPress-deployment-on-Kubernetes Branch: master Commit: 6ef71f6db686 Files: 28 Total size: 79.4 KB Directory structure: gitextract_b5klc_t9/ ├── .bluemix/ │ ├── deploy.json │ ├── pipeline.yml │ └── toolchain.yml ├── .gitignore ├── .travis.yml ├── .yamllint.yml ├── CONTRIBUTING.md ├── LICENSE ├── MAINTAINERS.md ├── README-jp.md ├── README-ko.md ├── README-pt.md ├── README.md ├── docs/ │ ├── deploy-with-docker-on-linuxone.md │ └── ubuntu.md ├── kustomization.yaml ├── local-volumes-compose.yaml ├── local-volumes.yaml ├── mysql-deployment.yaml ├── scripts/ │ ├── bx_auth.sh │ ├── install.sh │ ├── quickstart.sh │ └── resources.sh ├── test-requirements.txt ├── tests/ │ ├── deploy-minikube.sh │ └── test-kubernetes.sh ├── wordpress-deployment-compose.yaml └── wordpress-deployment.yaml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .bluemix/deploy.json ================================================ { "$schema": "http://json-schema.org/draft-04/schema#", "title": "Sample Deploy Stage", "description": "sample toolchain", "longDescription": "The Delivery Pipeline automates continuous deployment.", "type": "object", "properties": { "prod-region": { "description": "The bluemix region", "type": "string" }, "prod-organization": { "description": "The bluemix org", "type": "string" }, "prod-space": { "description": "The bluemix space", "type": "string" }, "prod-app-name": { "description": "The name of your WordPress app", "type": "string" }, "bluemix-user": { "description": "Your Bluemix user ID", "type": "string" }, "bluemix-password": { "description": "Your Bluemix Password", "type": "string" }, "bluemix-api-key": { "description": "Required for **Federated ID** since Federated ID can't login with Bluemix user and password via Bluemix CLI. You can obtain your API_KEY via https://console.ng.bluemix.net/iam/#/apikeys by clicking **Create API key** (Each API key only can be viewed once).", "type": "string" }, "bluemix-cluster-account": { "description": "The GUID of the Bluemix account where you created the cluster. Retrieve it with [bx iam accounts].", "type": "string" }, "bluemix-cluster-name": { "description": "Your cluster name. Retrieve it with [bx cs clusters].", "type": "string" } }, "required": ["prod-region", "prod-organization", "prod-space", "bluemix-cluster-name"], "anyOf": [ { "required": ["bluemix-user", "bluemix-password", "bluemix-cluster-account"] }, { "required": ["bluemix-api-key"] } ], "form": [ { "type": "validator", "url": "/devops/setup/bm-helper/helper.html" }, { "type": "text", "readonly": false, "title": "Bluemix User ID", "key": "bluemix-user" },{ "type": "password", "readonly": false, "title": "Bluemix Password", "key": "bluemix-password" },{ "type": "password", "readonly": false, "title": "Bluemix API Key (Optional)", "key": "bluemix-api-key" },{ "type": "password", "readonly": false, "title": "Bluemix Cluster Account ID", "key": "bluemix-cluster-account" },{ "type": "text", "readonly": false, "title": "Bluemix Cluster Name", "key": "bluemix-cluster-name" }, { "type": "table", "columnCount": 4, "widths": ["15%", "28%", "28%", "28%"], "items": [ { "type": "label", "title": "" }, { "type": "label", "title": "Region" }, { "type": "label", "title": "Organization" }, { "type": "label", "title": "Space" }, { "type": "label", "title": "Production stage" }, { "type": "select", "key": "prod-region" }, { "type": "select", "key": "prod-organization" }, { "type": "select", "key": "prod-space", "readonly": false } ] } ] } ================================================ FILE: .bluemix/pipeline.yml ================================================ --- stages: - name: BUILD inputs: - type: git branch: master service: ${SAMPLE_REPO} triggers: - type: commit jobs: - name: Build type: builder artifact_dir: '' build_type: shell script: |- #!/bin/bash bash -n *.sh - name: DEPLOY inputs: - type: job stage: BUILD job: Build dir_name: null triggers: - type: stage properties: - name: BLUEMIX_USER type: text value: ${BLUEMIX_USER} - name: BLUEMIX_PASSWORD type: secure value: ${BLUEMIX_PASSWORD} - name: BLUEMIX_ACCOUNT type: secure value: ${BLUEMIX_ACCOUNT} - name: CLUSTER_NAME type: text value: ${CLUSTER_NAME} - name: API_KEY type: secure value: ${API_KEY} jobs: - name: Deploy type: deployer target: region_id: ${PROD_REGION_ID} organization: ${PROD_ORG_NAME} space: ${PROD_SPACE_NAME} application: Pipeline script: | #!/bin/bash . ./scripts/deploy-to-bluemix/install_bx.sh ./scripts/deploy-to-bluemix/bx_login.sh ./scripts/deploy-to-bluemix/deploy.sh hooks: - enabled: true label: null ssl_enabled: false url: >- https://devops-api-integration.stage1.ng.bluemix.net/v1/messaging/webhook/publish ================================================ FILE: .bluemix/toolchain.yml ================================================ --- name: "Deploy Kubernetes WordPress sample to Bluemix" description: "Toolchain to deploy Kubernetes WordPress sample to Bluemix" version: 0.1 image: data:image/svg+xml;base64,$file(toolchain.svg,base64) icon: data:image/svg+xml;base64,$file(icon.svg,base64) required: - deploy - sample-repo # Github repos sample-repo: service_id: githubpublic parameters: repo_name: "{{name}}" repo_url: https://github.com/IBM/scalable-wordpress-deployment-on-kubernetes type: clone has_issues: false # Pipelines sample-build: service_id: pipeline parameters: name: "{{name}}" ui-pipeline: true configuration: content: $file(pipeline.yml) env: SAMPLE_REPO: "sample-repo" CF_APP_NAME: "{{deploy.parameters.prod-app-name}}" PROD_SPACE_NAME: "{{deploy.parameters.prod-space}}" PROD_ORG_NAME: "{{deploy.parameters.prod-organization}}" PROD_REGION_ID: "{{deploy.parameters.prod-region}}" BLUEMIX_USER: "{{deploy.parameters.bluemix-user}}" BLUEMIX_PASSWORD: "{{deploy.parameters.bluemix-password}}" API_KEY: "{{deploy.parameters.bluemix-api-key}}" BLUEMIX_ACCOUNT: "{{deploy.parameters.bluemix-cluster-account}}" CLUSTER_NAME: "{{deploy.parameters.bluemix-cluster-name}}" execute: true services: ["sample-repo"] hidden: [form, description] # Deployment deploy: schema: $ref: deploy.json service-category: pipeline parameters: prod-app-name: "{{sample-repo.parameters.repo_name}}" ================================================ FILE: .gitignore ================================================ # Ignore Vim files [._]*.s[a-w][a-z] [._]s[a-w][a-z] Session.vim .netrwhist *~ tags # Ignore macOS files *.DS_Store .AppleDouble .LSOverride ._* .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk # Ignore CI files dind-cluster-v1.7.sh* password.txt ================================================ FILE: .travis.yml ================================================ --- language: python python: 2.7 cache: pip notifications: slack: rooms: secure: "qb8F4QsJ6O6ygzZLDnp0ifmG6x8AX0Ne2KvuNOEjLwFeh45uYCMm4Ni1uiqryItyea3vZ7VOWdiR6hbBpVdXo0B3cOLDgQixQa8L89z9gQWocq7M0wo7RI9p3tGfBQ4xfNTPPLp9wzQ077h+8rXzSp6dbkWrUpUX3GEtcTz5B9rHasASGo4+azmvbdUa3CCv2MRVTEaftwBaf/F6CvMnxJdOFwd2tcFGs6sxQnWPbKEKWKqGyBqI347VcMYTmy9xmSQh8hMMxnzvYIyWFj2uTH6vYqBsMfAaI2nwBFKFVE9LzdKicoGdtzvC8hfEOC5gzORhBL3aQk4q7uhT39Cm7KcV+1/c391EuamyUAqtjPOCR3DS2CThaIEjYwi5xRMkWxqv9kZegb9vnd5BAjD6bYprZmuX6hkiaiKWPdiL3oxS8dyQG0h+rpBy1AUsDP4U7frK6QSaRHCtfx9eHncJvRxgX40D3YEGwPmHldGcSn/V6x2NyZFRAACxklzsn1vb//cjBr502w4nn1TeWLSnw3x9MdG3ZtZ8NjmeoXiN/nrQzd24l5PSysLPt/5W3t8GuQtaSzlVBXuYtNzBu9p0S2755KDXYA51SmZq8CV/T+0WPErLMLet/VJece4hThUgXdQHsIuayQzIGIozTFqe2/oOErOWYQ83MdC1vZ0PLxw=" on_pull_requests: false on_sucess: change services: - docker before_install: - sudo apt-get install shellcheck - pip install -U -r test-requirements.txt - git clone https://github.com/IBM/pattern-ci before_script: - "./pattern-ci/tests/shellcheck-lint.sh" - "./pattern-ci/tests/yaml-lint.sh" jobs: include: - install: ./pattern-ci/scripts/install-minikube.sh script: ./tests/deploy-minikube.sh ================================================ FILE: .yamllint.yml ================================================ --- rules: braces: min-spaces-inside: 0 max-spaces-inside: 0 min-spaces-inside-empty: 0 max-spaces-inside-empty: 0 brackets: min-spaces-inside: 0 max-spaces-inside: 0 min-spaces-inside-empty: 0 max-spaces-inside-empty: 0 colons: max-spaces-before: 0 max-spaces-after: 1 commas: max-spaces-before: 0 min-spaces-after: 1 max-spaces-after: 1 comments: require-starting-space: true min-spaces-from-content: 2 comments-indentation: enable document-end: disable document-start: present: true empty-lines: max: 2 max-start: 0 max-end: 0 hyphens: max-spaces-after: 1 indentation: spaces: consistent indent-sequences: true check-multi-line-strings: false key-duplicates: enable line-length: max: 80 allow-non-breakable-words: true allow-non-breakable-inline-mappings: true level: warning new-line-at-end-of-file: enable new-lines: type: unix trailing-spaces: enable truthy: enable ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing This is an open source project, and we appreciate your help! We use the GitHub issue tracker to discuss new features and non-trivial bugs. In addition to the issue tracker, [#journeys on Slack](https://dwopen.slack.com) is the best way to get into contact with the project's maintainers. To contribute code, documentation, or tests, please submit a pull request to the GitHub repository. Generally, we expect two maintainers to review your pull request before it is approved for merging. For more details, see the [MAINTAINERS](MAINTAINERS.md) page. ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: MAINTAINERS.md ================================================ # Maintainers Guide This guide is intended for maintainers - anybody with commit access to one or more Code Pattern repositories. ## Methodology This repository does not have a traditional release management cycle, but should instead be maintained as a useful, working, and polished reference at all times. While all work can therefore be focused on the master branch, the quality of this branch should never be compromised. The remainder of this document details how to merge pull requests to the repositories. ## Merge approval The project maintainers use LGTM (Looks Good To Me) in comments on the pull request to indicate acceptance prior to merging. A change requires LGTMs from two project maintainers. If the code is written by a maintainer, the change only requires one additional LGTM. ## Reviewing Pull Requests We recommend reviewing pull requests directly within GitHub. This allows a public commentary on changes, providing transparency for all users. When providing feedback be civil, courteous, and kind. Disagreement is fine, so long as the discourse is carried out politely. If we see a record of uncivil or abusive comments, we will revoke your commit privileges and invite you to leave the project. During your review, consider the following points: ### Does the change have positive impact? Some proposed changes may not represent a positive impact to the project. Ask whether or not the change will make understanding the code easier, or if it could simply be a personal preference on the part of the author (see [bikeshedding](https://en.wiktionary.org/wiki/bikeshedding)). Pull requests that do not have a clear positive impact should be closed without merging. ### Do the changes make sense? If you do not understand what the changes are or what they accomplish, ask the author for clarification. Ask the author to add comments and/or clarify test case names to make the intentions clear. At times, such clarification will reveal that the author may not be using the code correctly, or is unaware of features that accommodate their needs. If you feel this is the case, work up a code sample that would address the pull request for them, and feel free to close the pull request once they confirm. ### Does the change introduce a new feature? For any given pull request, ask yourself "is this a new feature?" If so, does the pull request (or associated issue) contain narrative indicating the need for the feature? If not, ask them to provide that information. Are new unit tests in place that test all new behaviors introduced? If not, do not merge the feature until they are! Is documentation in place for the new feature? (See the documentation guidelines). If not do not merge the feature until it is! Is the feature necessary for general use cases? Try and keep the scope of any given component narrow. If a proposed feature does not fit that scope, recommend to the user that they maintain the feature on their own, and close the request. You may also recommend that they see if the feature gains traction among other users, and suggest they re-submit when they can show such support. ================================================ FILE: README-jp.md ================================================ [![Build Status](https://travis-ci.org/IBM/Scalable-WordPress-deployment-on-Kubernetes.svg?branch=master)](https://travis-ci.org/IBM/Scalable-WordPress-deployment-on-Kubernetes) *他の言語で表示: [English](README.md) / [한국어](README-ko.md) / [português](README-po.md).* # スケーラブルな WordPress 実装を Kubernetes クラスター上にデプロイする このチュートリアルでは、Kubernetesクラスタの全機能を紹介し、世界で最も人気のあるWebサイトフレームワークを世界で最も人気のあるコンテナ・オーケストレーションプラットフォーム上に展開する方法を紹介します。KubernetesクラスタでWordPressをホストするための完全なロードマップを提供します。各コンポーネントは別々のコンテナまたはコンテナのグループで実行されます。 Wordpressは典型的な多層アプリケーションを表し、各コンポーネントはそれぞれのコンテナを持ちます。WordPressコンテナはフロントエンド層となり、MySQLコンテナはWordPressのデータベース/バックエンド層になります。 Kubernetesへのデプロイに加えて、フロントのWordPress層をどのように拡張できるか、そしてMySQLをIBM Cloudからのサービスとして仕様してWordPressフロントエンドで使用する方法も説明します。 ![kube-wordpress](images/kube-wordpress-code.png) ## Included Components - [WordPress (最新版)](https://hub.docker.com/_/wordpress/) - [MySQL (5.6)](https://hub.docker.com/_/mysql/) - [Kubernetes Clusters](https://cloud.ibm.com/docs/containers/cs_ov.html#cs_ov) - [IBM Cloud Compose for MySQL](https://cloud.ibm.com/catalog/services/compose-for-mysql) - [IBM Cloud DevOps Toolchain Service](https://cloud.ibm.com/catalog/services/continuous-delivery) - [IBM Cloud Kubernetes Service](https://cloud.ibm.com/catalog?taxonomyNavigation=apps&category=containers) ## 前提条件 ローカルテスト用の[Minikube](https://kubernetes.io/docs/setup/minikube/)や、[IBM Cloud Kubernetes Service](https://github.com/IBM/container-journey-template)または[IBM Cloud Private](https://github.com/IBM/deploy-ibm-cloud-private/blob/master/README.md) のいずれかでKubernetes Clusterを作成します。このレポジトリのコードは[Kubernetes Cluster from IBM Cloud Container Service](https://cloud.ibm.com/docs/containers/cs_ov.html#cs_ov)上でTravis CIを使用して定期的にテストされています。 ## 目的 このシナリオでは、以下の作業について説明します: - 永続ディスクを定義するためローカル永続ボリュームを作成 - 機密データを保護するためのシークレットを作成 - WordPressフロントエンドのポットを1つ以上作成してデプロイ - MySQLデータベースを作成してデプロイします。(コンテナ内、またはバックエンドとしてIBM CloudのMySQLを使用) ## Deploy to IBM Cloud WordPressを直接IBM Cloudへデプロイしたい場合は、下の`Deploy to IBM Cloud`ボタンをクリックしてWordPressサンプルをデプロイするためのIBM Cloud DepOps サービスツールチェインとパイプラインを作成します。それ以外の場合は、[手順](##手順)へジャンプします [![Create Toolchain](https://cloud.ibm.com/devops/setup/deploy/button.png)](https://cloud.ibm.com/devops/getting-started) ツールチェインとパイプラインを完成させるには、 [Toolchain instructions](https://github.com/IBM/container-journey-template/blob/master/Toolchain_Instructions_new.md) の指示に従ってください。 ## 手順 1. [MySQL シークレットの設定](#1-mysql-シークレットの設定) 2. [ローカル永続ボリュームの作成](#2-ローカル永続ボリュームの作成) 3. [WordPressとMySQLのサービス/デプロイメントの作成と配布](#3-WordPressとMySQLのサービス/デプロイメントの作成と配布) - 3.1 [コンテナ内でMySQLを使用する](#31-コンテナ内でMySQLを使用する) - 3.2 [バックエンドとしてIBM Cloud MySQLを使用する](#32-バックエンドとしてIBM-Cloud-MySQLを使用する) 4. [外部のWordPressリンクにアクセスする](#4-外部のWordPressリンクにアクセスする) 5. [WordPressを使用する](#5-WordPressを使用する) # 1. MySQL シークレットの設定 > *Quickstart option:* このレポジトリ内で `bash scripts/quickstart.sh`を実行します。 同じディレクトリに`password.txt`という名前の新しいファイルを作成し、希望のMySQLパスワードを`password.txt`の中に入れます。 (ASCII文字を含む任意の文字列). `password.txt`の末尾に改行が無いことを確認する必要があります。改行を削除するには、次のコマンドを使用します。 ```bash tr -d '\n' .strippedpassword.txt && mv .strippedpassword.txt password.txt ``` # 2. ローカル永続ボリュームの作成 Kubernetesポッドのライフサイクルを超えてデータを保存するには、MySQLおよびWordPressアプリケーションが接続するための永続的なボリュームを作成する必要があります。 #### IBM Cloud Kubernetes Service "ライト"クラスタ 次のコマンドを実行して、ローカル永続ボリュームを手動で作成します ```bash kubectl create -f local-volumes.yaml ``` #### IBM Cloud Kubernetes Service "有料"クラスタ または Minikube MySQLおよびWordPressアプリケーションがデプロイされると、永続ボリュームが動的に作成されます。この手順は不要です # 3. WordPressとMySQLのサービス/デプロイメントの作成と配布 ### 3.1 コンテナ内でMySQLを使用する > *Note:* IBM Cloud Compose-MySQLをバックエンドとして使用したい場合は、[バックエンドとしてIBM Cloud MySQLを使用する](#32-バックエンドとしてIBM-Cloud-MySQLを使用する)を参照してください 永続ボリュームをクラスタのローカルストレージにインストールします。その後、MySQLとWordPressのためのシークレットとサービスを作成します ```bash kubectl create secret generic mysql-pass --from-file=password.txt kubectl create -f mysql-deployment.yaml kubectl create -f wordpress-deployment.yaml ``` すべてのポッドが実行されたら、次のコマンドを実行してポッド名を確認します。 ```bash kubectl get pods ``` これにより、Kubernetesクラスタからのポッドのリストが返されます ```bash NAME READY STATUS RESTARTS AGE wordpress-3772071710-58mmd 1/1 Running 0 17s wordpress-mysql-2569670970-bd07b 1/1 Running 0 1m ``` それでは、[外部のWordPressリンクにアクセスする](#-4-外部のWordPressリンクにアクセスする)へ進んでください ### 3.2 バックエンドとしてIBM Cloud MySQLを使用する IBM CloudでCompose for MySQLをプロビジョニングします https://cloud.ibm.com/catalog/services/compose-for-mysql サービス認証情報に移動して、認証情報を確認してください。 MySQLのホスト名、ポート番号、ユーザー、パスワードがあなたの認証情報URIの下にあり、以下のように見えるはずです ![mysql](images/mysql.png) `wordpress-deployment.yaml`ファイルを編集し、WORDPRESS_DB_HOSTの値をMySQLのホスト名とポート番号に変更し(例: `value: :`)、 WORDPRESS_DB_USERの値をMySQLパスワードに変更します 環境変数は次のようになります ```yaml spec: containers: - image: wordpress:4.7.3-apache name: wordpress env: - name: WORDPRESS_DB_HOST value: sl-us-dal-9-portal.7.dblayer.com:22412 - name: WORDPRESS_DB_USER value: admin - name: WORDPRESS_DB_PASSWORD value: XMRXTOXTDWOOPXEE ``` `wordpress-deployment.yaml`を変更したら、次のコマンドを実行してWordPressをデプロイします ```bash kubectl create -f wordpress-deployment.yaml ``` すべてのポッドが実行されたら、次のコマンドを実行してポッド名を確認します ```bash kubectl get pods ``` これにより、Kubernetesクラスタからポッドのリストが返されます ```bash NAME READY STATUS RESTARTS AGE wordpress-3772071710-58mmd 1/1 Running 0 17s ``` # 4. 外部のWordPressリンクにアクセスする > 有料クラスタがある場合は、NodePortの代わりにLoadBalancerを使用することができます。 > >`kubectl edit services wordpress` > > `spec`の下で、 `type: NodePort` を `type: LoadBalancer` に変更してください > > **Note:** YAMLファイルを編集したあとに、`service "wordpress" edited`が表示されていることを確認してください。これはYAMLファイルが入力ミスや接続エラーなしで正常に編集されたことを意味します。 クラスタのIPアドレスを取得するには ```bash $ bx cs workers OK ID Public IP Private IP Machine Type State Status kube-hou02-pa817264f1244245d38c4de72fffd527ca-w1 169.47.220.142 10.10.10.57 free normal Ready ``` NodePort番号を取得するには、次のコマンドを実行する必要があります。 ```bash $ kubectl get svc wordpress NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE wordpress 10.10.10.57 80:30180/TCP 2m ``` おめでとうございます。今あなたはあなたのWordPressサイトへアクセスするためのリンク**http://[IP]:[port number]** を使用することができるようになりました。 > **Note:** 上記の例では、リンクは次のようになります http://169.47.220.142:30180 Kubernetes UIでdeploymentのステータスを確認することができます。`kubectl proxy`を実行し、URL 'http://127.0.0.1:8001/ui' に移動して、WordPressコンテナの準備が整ったことを確認します。 ![Kubernetes Status Page](images/kube_ui.png) > **Note:** ポッドが完全に機能するまで最大5分かかります。 **(Optional)** クラスタ内にさらにリソースがあり、WordPress Webサイトをスケールアップしたい場合は、次のコマンドを実行して現在のdeploymentsを確認できます。 ```bash $ kubectl get deployments NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE wordpress 1 1 1 1 23h wordpress-mysql 1 1 1 1 23h ``` これで、次のコマンドを実行してWordPressフロントエンドをスケールアップできます。 ```bash $ kubectl scale deployments/wordpress --replicas=2 deployment "wordpress" scaled $ kubectl get deployments NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE wordpress 2 2 2 2 23h wordpress-mysql 1 1 1 1 23h ``` ご覧のとおり、WordPressフロントエンドを実行している2つのポッドがあります。 > **Note:** 無料クラスタユーザーの場合、無料利用枠のユーザーには限られたリソースしかないため、スケールアップは最大10個のポッドまでとすることをおすすめします。 # 5. WordPressを使用する WordPressが起動しました。新しいユーザーとして登録して、WordPressをインストールすることができます。 ![wordpress home Page](images/wordpress.png) WordPresをインストール後、新しいコメントを投稿することができます。 ![wordpress comment Page](images/wordpress_comment.png) # トラブルシューティング 誤って改行付きのパスワードを作成した場合、MySQLサービスを認証することはできません。現在のシークレットを削除するには ```bash kubectl delete secret mysql-pass ``` サービス、deployments、永続ボリューム要求を削除したい場合は、次のコマンドで実行できます ```bash kubectl delete deployment,service,pvc -l app=wordpress ``` 永続ボリュームを削除したい場合は、次のコマンドで実行できます ```bash kubectl delete -f local-volumes.yaml ``` WordPressの動作に時間がかかる場合、ログを調べることでWordPressのデバックすることができます。 ```bash kubectl get pods # WordPressのポッド名を取得する kubectl logs [wordpress pod name] ``` # References - このWordPressの例は、 https://github.com/kubernetes/kubernetes/tree/master/examples/mysql-wordpress-pd にあるKubernetesのオープンソースの例[mysql-wordpress-pd](https://github.com/kubernetes/kubernetes/tree/master/examples/mysql-wordpress-pd)に基づいています。 # ライセンス このコードパターンは、Apache Software License, Version 2の元でライセンスされています。このコードパターン内で呼び出される個別のサードパーティコードオブジェクトは、独自の個別ライセンスに従って、それぞれのプロバイダによってライセンスされます。コントリビュートの対象は[Developer Certificate of Origin, Version 1.1 (DCO)](https://developercertificate.org/) と [Apache Software License, Version 2](https://www.apache.org/licenses/LICENSE-2.0.txt)です。 [Apache Software License (ASL) FAQ](https://www.apache.org/foundation/license-faq.html#WhatDoesItMEAN) ================================================ FILE: README-ko.md ================================================ [![Build Status](https://travis-ci.org/IBM/Scalable-WordPress-deployment-on-Kubernetes.svg?branch=master)](https://travis-ci.org/IBM/Scalable-WordPress-deployment-on-Kubernetes) *다른 언어로 보기: [English](README.md).* # 쿠버네티스 클러스터에 스케일링 가능한 워드프레스 구축하기 이 과정은 세계에서 가장 널리 이용되고 있는 컨테이너 오케스트레이션 플랫폼인 쿠버네티스의 여러 뛰어난 기능과 세계에서 가장 많이 이용되고 있는 웹사이트 프레임워크인 워드프레스를 쿠버네티스 상에 간단하게 배포하는 방법을 소개합니다. 단계별 가이드를 통해 IBM Bluemix 컨테이너 서비스의 쿠버네티스 클러스터에 워드프레스를 호스팅하는 방법 등을 안내합니다. 각 구성요소는 개별 컨테이너 또는 여러 컨테이너 그룹에서 실행됩니다. 워드프레스는 전형적인 멀티-티어(multi-tier) 앱으로, 각 구성요소마다 자체 컨테이너가 있습니다. 워드프레스 컨테이너는 프론트-엔드 티어가 되고, MySQL 컨테이너는 워드프레스의 데이터베이스/백엔드 티어가 됩니다. 쿠버네티스에서의 배포 외에도, 프론트 워드프레스 티어(front WordPress tier)를 스케일링하는 방법과 워드프레스 프론트 티어가 사용하는 MySQL을 Bluemix에서 DBaaS (Database as a Service)형태로 제공하는 Bluemix Compose for MySQL를 활용하여 사용하는 방법 또한 소개하겠습니다. ![kube-wordpress](images/kube-wordpress-code.png) ## 포함된 구성요소 - [워드프레스 (최신 버전)](https://hub.docker.com/_/wordpress/) - [MySQL (5.6)](https://hub.docker.com/_/mysql/) - [쿠버네티스 클러스터(Kubernetes Clusters)](https://console.ng.bluemix.net/docs/containers/cs_ov.html#cs_ov) - [Bluemix 컨테이너 서비스(Bluemix Container Service)](https://console.ng.bluemix.net/catalog/?taxonomyNavigation=apps&category=containers) - [Bluemix Compose for MySQL](https://console.ng.bluemix.net/catalog/services/compose-for-mysql) - [Bluemix DevOps 툴체인 서비스](https://console.ng.bluemix.net/catalog/services/continuous-delivery) ## 전제조건 로컬 테스트 환경에서는 [미니큐브(Minikube)](https://kubernetes.io/docs/getting-started-guides/minikube)를, 클라우드 환경에서는 [IBM Bluemix 컨테이너 서비스(Bluemix Container Service)](https://github.com/IBM/container-journey-template)를 활용하여 쿠버네티스 클러스터를 생성하십시오. 여기 제공되는 코드는  [Bluemix 컨테이너 서비스의 쿠버네티스 클러스터(Kubernetes Cluster from Bluemix Container Service)](https://console.ng.bluemix.net/docs/containers/cs_ov.html#cs_ov) 환경에서 Travis로 정기적인 테스트를 수행합니다. ## 목적 본 시나리오는 아래 작업의 진행을 위한 설명을 제공합니다. - 로컬 PersistentVolume(PV) 생성을 통한 영구적 디스크의 정의. - 비밀번호 생성을 통한 데이터의 보호. - 한 개 이상의 pod를 이용한 워드프레스 프론트엔드의 생성 및 배포. - MySQL 데이터베이스의 생성 및 배포(컨테이너 내에서의 생성 및 배포, 또는 Bluemix MySQL을 백엔드로 사용한 생성 및 배포). ## Bluemix에 배포하기 드프레스를 Bluemix에 직접 배포하려면, 아래의 ‘Deploy to Bluemix’ 버튼을 클릭하여 워드프레스 샘플 배포를 위한 Bluemix DevOps 서비스 툴체인과 파이프라인을 생성합니다. 그렇지 않은 경우,  [단계](##단계) 로 이동합니다. [![Create Toolchain](https://github.com/IBM/container-journey-template/blob/master/images/button.png)](https://console.ng.bluemix.net/devops/setup/deploy/) [툴체인 가이드를](https://github.com/IBM/container-journey-template/blob/master/Toolchain_Instructions_new.md) 참고하여 툴체인과 파이프라인을 생성하십시오. ## 단계 1. [MySQL 비밀키 설치](#1-mysql-비밀키-설치) 2. [워드프레스 및 MySQL의 서비스 및 배포 생성](#2-워드프레스-및-mysql의-서비스-및-배포-생성)  - 2.1 [컨테이너에서 MySQL 사용하기](#21-컨테이너에서-mysql-사용하기)  - 2.2 [Bluemix MySQL 사용하기](#22-bluemix-mysql-사용하기) 3. [외부 워드프레스 링크 이용하기](#3-외부-워드프레스-링크-이용하기) 4. [워드프레스 사용하기](#4-워드프레스-사용하기) # 1. MySQL 비밀키 설치 > *빠른 시작을 위한 옵션:* Git 저장소 내의  `bash scripts/quickstart.sh`를 실행합니다. 동일한 디렉토리에 `password.txt` 라는 이름의 신규 파일을 생성하고, 원하는 MySQL 암호를 `password.txt`에 기록하십시오(ASCII 형식의 문자열 가능). `password.txt` 에 줄바꿈 문자가 있어서는 안됩니다. 다음 명령을 이용하면 줄바꿈 문자를 제거할 수 있습니다. ```bash tr -d '\n' .strippedpassword.txt && mv .strippedpassword.txt password.txt ``` # 2. 워드프레스와 MySQL의 서비스 생성 및 배포하기 ### 2.1 컨테이너에서 MySQL 사용하기 > *참고:* Bluemix Compose-MySql을 백엔드로 이용하려는 경우, [Bluemix MySQL을 백엔드로 사용하기](#22-using-bluemix-mysql-as-backend)로 이동하십시오. 클러스터의 로컬 스토리지에 PersistentVolume(PV)를 설치하십시오. 그런 다음, MySQL 비밀 번호를 설정하고, MySQL 및 워드프레스의 서비스를 생성하십시오. ```bash kubectl create -f local-volumes.yaml kubectl create secret generic mysql-pass --from-file=password.txt kubectl create -f mysql-deployment.yaml kubectl create -f wordpress-deployment.yaml ``` Pod가 모두 실행 중일 때, 다음 명령을 실행하여 pod 목록을 확인하십시오. ```bash kubectl get pods ``` 다음 명령 이용 시, pod 목록이 쿠버네티스 클러스터로부터 반환됩니다. ```bash NAME READY STATUS RESTARTS AGE wordpress-3772071710-58mmd 1/1 Running 0 17s wordpress-mysql-2569670970-bd07b 1/1 Running 0 1m ``` 이제, [외부 링크 (external link) 이용하기](#3-외부-워드프레스-링크-이용하기)로 이동하십시오. ### 2.2 Bluemix MySQL을 백엔드로 사용하기 https://console.ng.bluemix.net/catalog/services/compose-for-mysql을 통해 Bluemix에 Compose for MySQL을 프로비저닝 하십시오. 서비스 신임정보로 이동하여 사용자 신임정보를 확인하십시오. 아래의 그림과 같이 사용자의 MySQL 호스트네임, 포트, 사용자, 암호 등이 사용자 신임정보 uri 밑에 있습니다. ![mysql](images/mysql.png) `wordpress-deployment.yaml` 파일을 수정합니다. WORDPRESS_DB_HOST 값을 사용자의 MySQL 호스트네임과 포트(`value: :`)로, WORDPRESS_DB_USER 값을 여러분의 MySQL 사용자로, WORDPRESS_DB_PASSWORD 값을 사용자의 MySQL 암호로 변경하십시오. 환경 변수는 다음과 같습니다. ```yaml spec: containers: - image: wordpress:4.7.3-apache name: wordpress env: - name: WORDPRESS_DB_HOST value: sl-us-dal-9-portal.7.dblayer.com:22412 - name: WORDPRESS_DB_USER value: admin - name: WORDPRESS_DB_PASSWORD value: XMRXTOXTDWOOPXEE ``` `wordpress-deployment.yaml`수정 후에는 다음 명령들을 실행하여 워드프레스를 배포합니다. ```bash kubectl create -f local-volumes.yaml kubectl create -f wordpress-deployment.yaml ``` 모든 pods가 실행 중일 때, 다음 명령을 실행하여 pod 이름들을 확인하십시오. ```bash kubectl get pods ``` 명령 실행을 통해 pod 목록이 쿠버네티스 클러스터로부터 반환됩니다. ```bash NAME READY STATUS RESTARTS AGE wordpress-3772071710-58mmd 1/1 Running 0 17s ``` # 3. 외부 워드프레스 링크 이용하기 >(유료 계정만 해당됨!!) 유료 계정이 있는 경우, 다음 명령을 실행하여 로드밸런서(LoadBalancer)를 생성할 수 있습니다. > >`kubectl edit services wordpress` > > `spec`아래의 `type: NodePort` 를 `type: LoadBalancer`로 변경하십시오. > > **참고:** yaml 파일 수정 후에 `service "wordpress" edited` 가 나타나야 yaml 파일이 오타나 연결 오류 없이 성공적으로 수정되었다는 뜻입니다. 다음 명령을 실행하여 클러스터의 IP 주소를 확인할 수 있습니다. ```bash $ kubectl get nodes NAME STATUS AGE 169.47.220.142 Ready 23h ``` 또한, 다음 명령을 실행하여 NodePort 번호를 확인해야 합니다. ```bash $ kubectl get svc wordpress NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE wordpress 10.10.10.57 80:30180/TCP 2m ``` 축하합니다. 지금부터는 **http://[IP]:[port number]** 링크를 이용하여 워드프레스 사이트에 접속할 수 있습니다. > **참고:** 위 예제의 링크는 http://169.47.220.142:30180 입니다. 쿠버네티스 UI에서 deployment를 확인할 수 있습니다. 'kubectl proxy' 를 실행하고 URL 'http://127.0.0.1:8001/ui' 로 이동하여 워드프레스 컨테이너가 언제 준비되는지 확인하십시오. ![Kubernetes Status Page](images/kube_ui.png) > **참고:** pod가 완전한 기능을 하기 전까지 최대 5분이 소요될 수 있습니다. **(선택사항)** 클러스터에 리소스가 추가적으로 있는 상황에서 워드프레스 웹사이트를 확장하려면, 다음 명령을 실행하여 현재 배포 현황을 확인할 수 있습니다. ```bash $ kubectl get deployments NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE wordpress 1 1 1 1 23h wordpress-mysql 1 1 1 1 23h ``` 이제, 다음 명령을 통해 워드프레스 프론트엔드의 스케일 아웃을 할 수 있습니다. ```bash $ kubectl scale deployments/wordpress --replicas=2 deployment "wordpress" scaled $ kubectl get deployments NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE wordpress 2 2 2 2 23h wordpress-mysql 1 1 1 1 23h ``` 보이는 것과 같이 워드프레스 프론트엔드을 실행 중인 pods는 2개입니다. > **참고:** 무료 티어(free tier) 사용자에게는 리소스가 제한적이므로 최대 10개까지만 pods를 확장할 것을 권장합니다. # 4. 워드프레스 사용하기 워드프레스가 실행되었고, 이제 신규 사용자로 등록 및 워드프레스 설치를 진행할 수 있습니다. ![wordpress home Page](images/wordpress.png) 워드프레스가 설치되면 새로운 코멘트를 포스팅할 수 있습니다. ![wordpress comment Page](images/wordpress_comment.png) # 문제 해결 줄바꿈을 통해 실수로 암호를 생성하여 MySQL 서비스에 권한을 부여할 수 없는 경우, 다음 명령을 사용하여 현재 비밀키를 삭제할 수 있습니다. ```bash kubectl delete secret mysql-pass ``` If you want to delete your services, deployments, and persistent volume claim, you can run ```bash kubectl delete deployment,service,pvc -l app=wordpress ``` PersistentVolume (PV)를 삭제하려면, 다음 명령을 실행하십시오. ```bash kubectl delete -f local-volumes.yaml ``` # 참조 - • 이 워드프레스 예제는 [mysql-wordpress-pd](https://github.com/kubernetes/kubernetes/tree/master/examples/mysql-wordpress-pd) 웹사이트의 쿠버네티스의 https://github.com/kubernetes/kubernetes/tree/master/examples/mysql-wordpress-pd 오픈 소스 예제를 기반으로 작성되었습니다. # 라이센스 [Apache 2.0](LICENSE) ================================================ FILE: README-pt.md ================================================ [![Build Status](https://travis-ci.org/IBM/Scalable-WordPress-deployment-on-Kubernetes.svg?branch=master)](https://travis-ci.org/IBM/Scalable-WordPress-deployment-on-Kubernetes) *Ler em outros idiomas: [한국어](README-ko.md).* # Implementação escalável do WordPress no Cluster Kubernetes Esta jornada apresenta toda a força dos clusters Kubernetes e mostra como podemos implementar a estrutura de website mais popular do mundo na plataforma de orquestração de contêineres mais popular do mundo. Fornecemos um roteiro completo para hospedar o WordPress em um Cluster Kubernetes. Cada componente é executado em um contêiner ou grupo de contêineres separado. O WordPress representa um aplicativo típico multicamada; cada componente terá seus próprios contêineres. Os contêineres do WordPress serão a camada de front-end; o contêiner do MySQL será a camada de banco de dados/backend para o WordPress. A lém da implementação no Kubernetes, mostraremos como é possível ajustar a escala da camada frontal do WordPress e como o MySQL pode ser utilizado como um serviço do Bluemix para uso pelo front-end do WordPress. ![kube-wordpress](images/kube-wordpress-code.png) ## Componentes inclusos - [WordPress (mais recente)](https://hub.docker.com/_/wordpress/) - [MySQL (5.6)](https://hub.docker.com/_/mysql/) - [Clusters Kubernetes](https://console.ng.bluemix.net/docs/containers/cs_ov.html#cs_ov) - [Bluemix Container Service](https://console.ng.bluemix.net/catalog/?taxonomyNavigation=apps&category=containers) - [Bluemix Compose for MySQL](https://console.ng.bluemix.net/catalog/services/compose-for-mysql) - [Bluemix DevOps Toolchain Service](https://console.ng.bluemix.net/catalog/services/continuous-delivery) ## Pré-requisito Crie um cluster Kubernetes com [Minikube](https://kubernetes.io/docs/getting-started-guides/minikube) para testes locais ou com o [IBM Bluemix Container Service](https://github.com/IBM/container-journey-template) para implementação na cloud. O código é testado regularmente com relação ao [Cluster Kubernetes do Bluemix Container Service](https://console.ng.bluemix.net/docs/containers/cs_ov.html#cs_ov) usando Travis. ## Objetivos Este cenário fornece instruções para as tarefas a seguir: - Criar volumes persistentes locais para definir discos persistentes. - Criar um segredo para proteger dados sensíveis. - Criar e implementar o front-end do WordPress com um ou mais pods. - Criar e implementar o banco de dados do MySQL (em um contêiner ou usando o Bluemix MySQL como backend). ## Implementar no Bluemix Se quiser implementar o WordPress diretamente no Bluemix, clique no botão 'Deploy to Bluemix' abaixo para criar uma cadeia de ferramentas de serviço do Bluemix DevOps e um canal para implementação da amostra do WordPress ou avance para [Etapas](##steps) [![Create Toolchain](https://github.com/IBM/container-journey-template/blob/master/images/button.png)](https://console.ng.bluemix.net/devops/setup/deploy/) Siga as [instruções da cadeia de ferramentas](https://github.com/IBM/container-journey-template/blob/master/Toolchain_Instructions_new.md) para concluir a cadeia de ferramentas e o canal. ## Etapas 1. [Configurar segredos do MySQL](#1-setup-mysql-secrets) 2. [Criar serviços e implementações para WordPress e MySQL](#2-create-services-and-deployments-for-wordpress-and-mysql) - 2.1 [Usando o MySQL no contêiner](#21-using-mysql-in-container) - 2.2 [Usando o Bluemix MySQL](#22-using-bluemix-mysql-as-backend) 3. [Acessando o link externo do WordPress](#3-accessing-the-external-wordpress-link) 4. [Usando o WordPress](#4-using-wordpress) # 1. Configurar segredos do MySQL > *Opção de iniciação rápida:* Neste repositório, execute `bash scripts/quickstart.sh`. Crie um novo arquivo chamado `password.txt` no mesmo diretório e coloque a senha desejada do MySQL em `password.txt` (pode ser qualquer cadeia de caractere com caracteres ASCII). Precisamos ter certeza de que `password.txt` não contém nenhuma linha nova posterior. Utilize o comando a seguir para remover possíveis linhas novas. ```bash tr -d '\n' .strippedpassword.txt && mv .strippedpassword.txt password.txt ``` # 2. Criar serviços e implementações para WordPress e MySQL ### 2.1 Usando o MySQL no contêiner > *Observação:* se quiser usar o Bluemix Compose-MySql como backend, acesse [Usando o Bluemix MySQL como backend](#22-using-bluemix-mysql-as-backend). Instale o volume persistente no armazenamento local do cluster. Em seguida, crie o segredo e serviços para MySQL e WordPress. ```bash kubectl create -f local-volumes.yaml kubectl create secret generic mysql-pass --from-file=password.txt kubectl create -f mysql-deployment.yaml kubectl create -f wordpress-deployment.yaml ``` Quando todos os pods estiverem em execução, execute os comandos a seguir para verificar os nomes deles. ```bash kubectl get pods ``` Isso deve gerar uma lista de pods a partir do cluster Kubernetes. ```bash NAME READY STATUS RESTARTS AGE wordpress-3772071710-58mmd 1/1 Running 0 17s wordpress-mysql-2569670970-bd07b 1/1 Running 0 1m ``` Agora, prossiga para [Acessando o link externo](#3-accessing-the-external-link). ### 2.2 Usando o Bluemix MySQL como backend Provision Compose for MySQL no Bluemix por meio de https://console.ng.bluemix.net/catalog/services/compose-for-mysql Acesse as credenciais de serviço e visualize suas credenciais. O nome do host, porta, usuário e senha do MySQL estão na URI da credencial e devem ter esta aparência: ![mysql](images/mysql.png) Modifique o arquivo `wordpress-deployment.yaml`, altere o valor WORDPRESS_DB_HOST para o nome do host e a porta do MySQL (ou seja, `value: :`), o valor WORDPRESS_DB_USER para o usuário do MySQL e o valor WORDPRESS_DB_PASSWORD para a senha do MySQL. As variáveis de ambiente devem ter esta aparência: ```yaml spec: containers: - image: wordpress:4.7.3-apache name: wordpress env: - name: WORDPRESS_DB_HOST value: sl-us-dal-9-portal.7.dblayer.com:22412 - name: WORDPRESS_DB_USER value: admin - name: WORDPRESS_DB_PASSWORD value: XMRXTOXTDWOOPXEE ``` Depois de modificar o `wordpress-deployment.yaml`, execute os comandos a seguir para implementar o WordPress. ```bash kubectl create -f local-volumes.yaml kubectl create -f wordpress-deployment.yaml ``` Quando todos os pods estiverem em execução, execute os comandos a seguir para verificar os nomes deles. ```bash kubectl get pods ``` Isso deve gerar uma lista de pods a partir do cluster Kubernetes. ```bash NAME READY STATUS RESTARTS AGE wordpress-3772071710-58mmd 1/1 Running 0 17s ``` # 3. Acessando o link externo do WordPress > Se tiver um cluster pago, será possível usar o LoadBalancer em vez do NodePort executando > >`kubectl edit services wordpress` > > Em `spec`, altere `type: NodePort` para `type: LoadBalancer` > > **Observação:** confira se `service "wordpress" edited` é exibido após a edição do arquivo yaml, porque isso significa que o arquivo yaml foi editado com sucesso, sem erros tipográficos ou de conexão. Para obter o endereço IP do cluster, utilize ```bash $ bx cs workers OK ID Public IP Private IP Machine Type State Status kube-hou02-pa817264f1244245d38c4de72fffd527ca-w1 169.47.220.142 10.10.10.57 free normal Ready ``` Você também precisará executar o comando a seguir para obter o número NodePort. ```bash $ kubectl get svc wordpress NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE wordpress 10.10.10.57 80:30180/TCP 2m ``` Parabéns. Agora, você pode usar o link **http://[IP]:[número da porta]** para acessar seu site no WordPress. > **Observação:** para o exemplo acima, o link seria http://169.47.220.142:30180 É possível verificar o status da implementação na interface com o usuário do Kubernetes. Execute `kubectl proxy` e acesse a URL 'http://127.0.0.1:8001/ui' para verificar quando o contêiner do WordPress ficará pronto. ![Kubernetes Status Page](images/kube_ui.png) >**Observação:** os pods podem levar até cinco minutos para começar a funcionar por completo. **(Opcional)** Se você tiver mais recursos no cluster e quiser aumentar a capacidade do website do WordPress, poderá executar os comandos a seguir para verificar as implementações atuais. ```bash $ kubectl get deployments NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE wordpress 1 1 1 1 23h wordpress-mysql 1 1 1 1 23h ``` Agora, é possível usar os comandos a seguir para aumentar a capacidade para o front-end do WordPress. ```bash $ kubectl scale deployments/wordpress --replicas=2 deployment "wordpress" scaled $ kubectl get deployments NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE wordpress 2 2 2 2 23h wordpress-mysql 1 1 1 1 23h ``` Como pode ser visto, temos dois pods que estão em execução no front-end do WordPress. > **Observação:** caso você seja um usuário de camada gratuita, recomendamos aumentar a capacidade para apenas 10 pods, uma vez que os usuários de camada gratuita têm recursos limitados. # 4. Usando o WordPress Com o WordPress em execução, é possível se inscrever como novo usuário e instalar o WordPress. ![wordpress home Page](images/wordpress.png) Depois de instalar o WordPress, você poderá publicar novos comentários. ![wordpress comment Page](images/wordpress_comment.png) # Resolução de problemas Caso tenha criado acidentalmente uma senha com linhas novas e não consiga autorizar o serviço do MySQL, você pode excluir o segredo atual usando ```bash kubectl delete secret mysql-pass ``` Se quiser excluir seus serviços, implementações e a solicitação de volume persistente, você poderá executar ```bash kubectl delete deployment,service,pvc -l app=wordpress ``` Para excluir seu volume persistente, é possível executar os comandos a seguir ```bash kubectl delete -f local-volumes.yaml ``` # Referências - Este exemplo do WordPress baseia-se no exemplo de software livre do Kubernetes [mysql-wordpress-pd](https://github.com/kubernetes/kubernetes/tree/master/examples/mysql-wordpress-pd) em https://github.com/kubernetes/kubernetes/tree/master/examples/mysql-wordpress-pd. # Licença [Apache 2.0](LICENÇA) ================================================ FILE: README.md ================================================ [![Build Status](https://travis-ci.org/IBM/Scalable-WordPress-deployment-on-Kubernetes.svg?branch=master)](https://travis-ci.org/IBM/Scalable-WordPress-deployment-on-Kubernetes) # Scalable WordPress deployment on Kubernetes Cluster This journey showcases the full power of Kubernetes clusters and shows how can we deploy the world's most popular website framework on top of world's most popular container orchestration platform. We provide a full roadmap for hosting WordPress on a Kubernetes Cluster. Each component runs in a separate container or group of containers. WordPress represents a typical multi-tier app and each component will have its own container(s). The WordPress containers will be the frontend tier and the MySQL container will be the database/backend tier for WordPress. In addition to deployment on Kubernetes, we will also show how you can scale the front WordPress tier, as well as how you can use MySQL as a service from IBM Cloud to be used by WordPress frontend. ![kube-wordpress](images/kube-wordpress-code.png) ## Included Components - [WordPress (Latest)](https://hub.docker.com/_/wordpress/) - [MySQL (5.6)](https://hub.docker.com/_/mysql/) - [Kubernetes Clusters](https://cloud.ibm.com/docs/containers/cs_ov.html#cs_ov) - [IBM Cloud Compose for MySQL](https://cloud.ibm.com/catalog/services/compose-for-mysql) ## Prerequisite Create a Kubernetes cluster with either [Minikube](https://kubernetes.io/docs/setup/minikube/) for local testing, with [IBM Cloud Container Service](https://github.com/IBM/container-journey-template), or [IBM Cloud Private](https://github.com/IBM/deploy-ibm-cloud-private/blob/master/README.md) to deploy in cloud. The code here is regularly tested against [Kubernetes Cluster from IBM Cloud Container Service](https://cloud.ibm.com/docs/containers/cs_ov.html#cs_ov) using Travis. ## Objectives This scenario provides instructions for the following tasks: - Create local persistent volumes to define persistent disks. - Create a secret to protect sensitive data. - Create and deploy the WordPress frontend with one or more pods. - Create and deploy the MySQL database (either in a container or using IBM Cloud MySQL as backend). ## Deply to IBM Cloud If you want to deploy the WordPress directly to IBM Cloud, click on `Deploy to IBM Cloud` button below to create an IBM Cloud DevOps service toolchain and pipeline for deploying the WordPress sample, else jump to [steps](##Methods-to-Deploy) [![Deploy to IBM Cloud](https://cloud.ibm.com/devops/setup/deploy/button.png)](https://cloud.ibm.com/devops/setup/deploy?repository=https://github.com/IBM/Scalable-WordPress-deployment-on-Kubernetes&branch=master) # Methods to Deploy - [Using The Kustomization File](#Using-The-Kustomization-File) - [Manually deploying each file](#Manually-deploying-each-deployment) - [Using Compose for MySQL as Backend](#Using-IBM-Cloud-Compose-for-MySQL-as-backend) # Using The Kustomization File `kustomize` lets you customize raw, template-free YAML files for multiple purposes, leaving the original YAML untouched and usable as is. Create a new file called `password.txt` in the same directory and put your desired MySQL password inside `password.txt` (Could be any string with ASCII characters). How does our `kustomization.yaml` file looks like: ```yaml secretGenerator: #generates secrets within the cluster - name: mysql-pass files: - password.txt resources: #runs the .yaml files which are written below - local-volumes.yaml - mysql-deployment.yaml - wordpress-deployment.yaml ``` #### To run the kustomization file ```bash kubectl apply -k ./ ``` #### Output ```bash secret/mysql-pass-c2f8979ct6 created service/wordpress-mysql created service/wordpress created deployment.apps/wordpress-mysql created deployment.apps/wordpress created persistentvolume/local-volume-1 created persistentvolume/local-volume-2 created persistentvolumeclaim/mysql-pv-claim created persistentvolumeclaim/wp-pv-claim created ``` ![Kubernetes Status Page](images/kube_kust.png) [To read more about kustomization please click here](https://github.com/kubernetes-sigs/kustomize) Now please move on to [Accessing the External Link](#Accessing-the-external-wordpress-link). #### To remove the deployment ```bash kubectl delete -k ./ ``` # Manually deploying each deployment 1. [Setup MySQL Secrets](#1-setup-mysql-secrets) 2. [Create local persistent volumes](#2-create-local-persistent-volumes) 3. [Create Services and Deployments for WordPress and MySQL](#3-create-services-and-deployments-for-wordpress-and-mysql) 4. [Accessing the external WordPress link](#Accessing-the-external-wordpress-link) 5. [Using WordPress](#5-using-wordpress) ### 1. Setup MySQL Secrets Create a new file called `password.txt` in the same directory and put your desired MySQL password inside `password.txt` (Could be any string with ASCII characters). We need to make sure `password.txt` does not have any trailing newline. Use the following command to remove possible newlines. ```bash tr -d '\n' .strippedpassword.txt && mv .strippedpassword.txt password.txt ``` ### 2. Create Local Persistent Volumes To save your data beyond the lifecycle of a Kubernetes pod, you will want to create persistent volumes for your MySQL and Wordpress applications to attach to. #### For "lite" IBM Cloud Kubernetes Service Create the local persistent volumes manually by running ```bash kubectl create -f local-volumes.yaml ``` #### For paid IBM Cloud Kubernetes Service OR Minikube Persistent volumes are created dynamically for you when the MySQL and Wordpress applications are deployed. No action is needed. ### 3. Create Services and deployments for WordPress and MySQL > *Note:* If you want to use IBM Cloud Compose for MySql as your backend, please go to [Using IBM Cloud MySQL as backend](#Using-IBM-Cloud-MySQL-as-backend). Install persistent volume on your cluster's local storage. Then, create the secret and services for MySQL and WordPress. ```bash kubectl create secret generic mysql-pass --from-file=password.txt kubectl create -f mysql-deployment.yaml kubectl create -f wordpress-deployment.yaml ``` When all your pods are running, run the following commands to check your pod names. ```bash kubectl get pods ``` This should return a list of pods from the kubernetes cluster. ```bash NAME READY STATUS RESTARTS AGE wordpress-3772071710-58mmd 1/1 Running 0 17s wordpress-mysql-2569670970-bd07b 1/1 Running 0 1m ``` Now please move on to [Accessing the External Link](#Accessing-the-external-wordpress-link). # Using IBM Cloud Compose for MySQL as backend ### Create Local Persistent Volumes To save your data beyond the lifecycle of a Kubernetes pod, you will want to create persistent volumes for your Wordpress applications to attach to. #### For "lite" IBM Cloud Kubernetes Service Create the local persistent volumes manually by running ```bash kubectl create -f local-volumes-compose.yaml ``` #### For paid IBM Cloud Kubernetes Service OR Minikube Persistent volumes are created dynamically for you when the MySQL and Wordpress applications are deployed. No action is needed. Provision Compose for MySQL in IBM Cloud via https://cloud.ibm.com/catalog/services/compose-for-mysql Go to Service credentials and view your credentials (or add one if you don't see one created already). Your MySQL hostname, port, user, and password are under your credential url and it should look like this ```script db_type": "mysql", "uri_cli_1": "mysql -u <> -p<> --host sl-us-south-1-portal.47.dblayer.com --port 22817 --ssl-mode=REQUIRED", ``` **Alternatively** you could also go to the manage tab and under "Connection Strings" you will be able to find the username, password, hostname as well as the port as shown below ![mysqlmanage](images/mysql_manage.png) Go to your `wordpress-deployment-compose.yaml` file, change WORDPRESS_DB_HOST's value to your MySQL hostname and port (i.e. `value: :`), WORDPRESS_DB_USER's value to your MySQL user, and WORDPRESS_DB_PASSWORD's value to your MySQL password. And the environment variables should look like this ```yaml spec: containers: - image: wordpress:latest name: wordpress-c env: - name: WORDPRESS_DB_HOST value: <>:<> - name: WORDPRESS_DB_USER value: <> - name: WORDPRESS_DB_PASSWORD value: <> ``` After you modified the `wordpress-deployment-compose.yaml`, run the following commands to deploy WordPress. ```bash kubectl create -f wordpress-deployment-compose.yaml ``` When all your pods are running, run the following commands to check your pod names. ```bash kubectl get pods ``` This should return a list of pods from the kubernetes cluster. ```bash NAME READY STATUS RESTARTS AGE wordpress-3772071710-58mmd 1/1 Running 0 17s ``` #### To access the service You can obtain your cluster's IP address using ```bash $ ibmcloud ks workers --cluster OK ID Public IP Private IP Machine Type State Status kube-hou02-pa817264f1244245d38c4de72fffd527ca-w1 169.47.220.142 10.10.10.57 free normal Ready ``` You will also need to run the following command to get your NodePort number. ```bash $ kubectl get svc wordpress-c NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE wordpress-c NodePort 172.21.179.176 80:30126/TCP 21s ``` Congratulations. Now you can use the link **http://[IP of worker node]:[service port number]** to access your WordPress site. > **Note:** For the above example, the link would be http://169.47.220.142:30126 ### To delete your deployment ````bash kubectl delete -f wordpress-deployment-compose.yaml kubectl delete -f local-volumes-compose.yaml ```` # Accessing the external WordPress link > If you have a paid cluster, you can use LoadBalancer instead of NodePort by running > >`kubectl edit services wordpress` > > Under `spec`, change `type: NodePort` to `type: LoadBalancer` > > **Note:** Make sure you have `service "wordpress" edited` shown after editing the yaml file because that means the yaml file is successfully edited without any typo or connection errors. You can obtain your cluster's IP address using ```bash $ ibmcloud ks workers --cluster OK ID Public IP Private IP Machine Type State Status kube-hou02-pa817264f1244245d38c4de72fffd527ca-w1 169.47.220.142 10.10.10.57 free normal Ready ``` You will also need to run the following command to get your NodePort number. ```bash $ kubectl get svc wordpress NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE wordpress 10.10.10.57 80:30180/TCP 2m ``` Congratulations. Now you can use the link **http://[IP of worker node]:[service port number]** to access your WordPress site. > **Note:** For the above example, the link would be http://169.47.220.142:30180 You can check the status of your deployment on Kubernetes UI. Run `kubectl proxy` and go to URL 'http://127.0.0.1:8001/ui' to check when the WordPress container becomes ready. ![Kubernetes Status Page](images/kube_ui.png) > **Note:** It can take up to 5 minutes for the pods to be fully functioning. **(Optional)** If you have more resources in your cluster, and you want to scale up your WordPress website, you can run the following commands to check your current deployments. ```bash $ kubectl get deployments NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE wordpress 1 1 1 1 23h wordpress-mysql 1 1 1 1 23h ``` # To Scale Your Application Now, you can run the following commands to scale up for WordPress frontend. ```bash $ kubectl scale deployments/wordpress --replicas=2 deployment "wordpress" scaled ``` #### Check your added replica ```bash $ kubectl get deployments NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE wordpress 2 2 2 2 23h wordpress-mysql 1 1 1 1 23h ``` As you can see, we now have 2 pods that are running the WordPress frontend. > **Note:** If you are a free tier user, we recommend you only scale up to 10 pods since free tier users have limited resources. # 5. Using WordPress Now that WordPress is running you can register as a new user and install WordPress. ![wordpress home Page](images/wordpress.png) After installing WordPress, you can post new comments. ![wordpress comment Page](images/wordpress_comment.png) # Troubleshooting If you accidentally created a password with newlines and you can not authorize your MySQL service, you can delete your current secret using ```bash kubectl delete secret mysql-pass ``` If you want to delete your services, deployments, and persistent volume claim, you can run ```bash kubectl delete deployment,service,pvc -l app=wordpress ``` If you want to delete your persistent volume, you can run the following commands ```bash kubectl delete -f local-volumes.yaml ``` If WordPress is taking a long time, you can debug it by inspecting the logs ```bash kubectl get pods # Get the name of the wordpress pod kubectl logs [wordpress pod name] ``` # References - This WordPress example is based on Kubernetes's open source example [mysql-wordpress-pd](https://github.com/kubernetes/kubernetes/tree/master/examples/mysql-wordpress-pd) at https://github.com/kubernetes/kubernetes/tree/master/examples/mysql-wordpress-pd. ## License This code pattern is licensed under the Apache Software License, Version 2. Separate third-party code objects invoked within this code pattern are licensed by their respective providers pursuant to their own separate licenses. Contributions are subject to the [Developer Certificate of Origin, Version 1.1](https://developercertificate.org/) and the [Apache License, Version 2](https://www.apache.org/licenses/LICENSE-2.0.txt). [Apache License FAQ](https://www.apache.org/foundation/license-faq.html#WhatDoesItMEAN) ================================================ FILE: docs/deploy-with-docker-on-linuxone.md ================================================ # Deploy with Docker on LinuxONE Open source software has expanded from a low-cost alternative to a platform for enterprise databases, clouds and next-generation apps. These workloads need higher levels of scalability, security and availability from the underlying hardware infrastructure. LinuxONE was built for open source so you can harness the agility of the open revolution on the industry’s most secure, scalable and high-performing Linux server. In this journey we will show how to run open source Cloud-Native workloads on LinuxONE ## Included Components - [LinuxONE](https://www-03.ibm.com/systems/linuxone/open-source/index.html) - [Docker](https://www.docker.com) - [Docker Store](https://sore.docker.com) - [WordPress](https://workpress.com) - [MariaDB](https://mariadb.org) ## Prerequisites Register at [LinuxONE Community Cloud](https://developer.ibm.com/linuxone/) for a trial account. We will be using a Ret Hat base image for this journey, so be sure to chose the red 'Request your trial' button on the lower left side of this page: ![testdrive](../images/linuxone_testdrive.png) ## Steps [Docker Hub](https://hub.docker.com) makes it rather simple to get started with containers, as there are quite a few images ready to for your to use. You can browse the list of images that are compatable with LinuxONE by doing a search on the ['s390x'](https://hub.docker.com/search/?isAutomated=0&isOfficial=0&page=1&pullCount=0&q=s390x&starCount=0) tag. We will start off with everyone's favorite demo: an installation of WordPress. These instructions assume a base RHEL 7.2 image. If you are using Ubuntu, please follow the separate [instructions](docs/ubuntu.md) ### 1. Install docker ```text :~$ yum install docker.io ``` ### 2. Install docker-compose Install dependencies ```text sudo yum install -y python-setuptools ``` Install pip with easy_install ```text sudo easy_install pip ``` Upgrade backports.ssl_match_hostname ```text sudo pip install backports.ssl_match_hostname --upgrade ``` Finally, install docker-compose itself ```text sudo pip install docker-compose ``` ### 3. Run and install WordPress Now that we have docker-compose installed, we will create a docker-compose.yml file. This will specify a couple of containers from the Docker Store that have been specifically written for z systems. ```text vim docker-compose.yml ``` ```text version: '2' services: wordpress: image: s390x/wordpress ports: - 8080:80 environment: WORDPRESS_DB_PASSWORD: example mysql: image: brunswickheads/mariadb-5.5-s390x environment: MYSQL_ROOT_PASSWORD: example ``` And finally, run docker-compose (from the same directory you created the .yml) ```text sudo docker-compose up -d ``` After all is installed, you can check the status of your containers ```text :~$ sudo docker-compose ps Name Command State Ports ---------------------------------------------------------------------------------- linux1_mysql_1 /docker-entrypoint.sh mysq ... Up 3306/tcp linux1_wordpress_1 /entrypoint.sh apache2-for ... Up 0.0.0.0:8080->80/tcp ``` and checkout your new blog by using a webbrowser to access 'http://[Your LinuxONE IP Address]:8080' ![after_deploy](../images/wpinstall-language.png) You will see the default setup screen requesting your language. The following screen will ask you to specify a default username/password for the WordPress installation, after which you will be up and running! ================================================ FILE: docs/ubuntu.md ================================================ ### 1. Install docker ```text :~$ apt install docker.io ``` ### 2. Install docker-compose Install dependencies ```text sudo apt-get update sudo apt-get install -y python-pip pip install --upgrade ``` Then docker-compose itself ```text sudo pip install docker-compose ``` ================================================ FILE: kustomization.yaml ================================================ --- secretGenerator: - name: mysql-pass files: - password.txt resources: - local-volumes.yaml - mysql-deployment.yaml - wordpress-deployment.yaml ================================================ FILE: local-volumes-compose.yaml ================================================ --- apiVersion: v1 kind: PersistentVolume metadata: name: local-volume-3 labels: type: local spec: capacity: storage: 20Gi accessModes: - ReadWriteOnce hostPath: path: /tmp/data/lv-3 persistentVolumeReclaimPolicy: Recycle ================================================ FILE: local-volumes.yaml ================================================ --- apiVersion: v1 kind: PersistentVolume metadata: name: local-volume-1 labels: type: local spec: capacity: storage: 20Gi accessModes: - ReadWriteOnce hostPath: path: /tmp/data/lv-1 persistentVolumeReclaimPolicy: Recycle --- apiVersion: v1 kind: PersistentVolume metadata: name: local-volume-2 labels: type: local spec: capacity: storage: 20Gi accessModes: - ReadWriteOnce hostPath: path: /tmp/data/lv-2 persistentVolumeReclaimPolicy: Recycle ================================================ FILE: mysql-deployment.yaml ================================================ apiVersion: v1 kind: Service metadata: name: wordpress-mysql labels: app: wordpress-mysql spec: ports: - port: 3306 selector: app: wordpress-mysql --- apiVersion: apps/v1 kind: Deployment metadata: name: wordpress-mysql labels: app: wordpress-mysql spec: selector: matchLabels: app: wordpress-mysql strategy: type: Recreate template: metadata: labels: app: wordpress-mysql spec: containers: - image: mysql:5.6 name: mysql env: - name: MYSQL_DATABASE value: wordpress - name: MYSQL_ROOT_PASSWORD valueFrom: secretKeyRef: name: mysql-pass key: password ports: - containerPort: 3306 name: mysql volumeMounts: - name: mysql-persistent-storage mountPath: /var/lib/mysql volumes: - name: mysql-persistent-storage persistentVolumeClaim: claimName: mysql-pv-claim --- apiVersion: v1 kind: PersistentVolume metadata: name: mysql-pv-volume labels: type: local spec: storageClassName: manual capacity: storage: 20Gi accessModes: - ReadWriteOnce hostPath: path: "/tmp/mysql/data" persistentVolumeReclaimPolicy: Recycle --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pv-claim spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 20Gi ================================================ FILE: scripts/bx_auth.sh ================================================ #!/bin/bash -e # This script is intended to be run by Travis CI. If running elsewhere, invoke # it with: TRAVIS_PULL_REQUEST=false [path to script] # If no credentials are provided at runtime, bx will use the environment # variable BLUEMIX_API_KEY. If no API key is set, it will prompt for # credentials. # shellcheck disable=SC1090 source "$(dirname "$0")"/../scripts/resources.sh BLUEMIX_ORG="Developer Advocacy" BLUEMIX_SPACE="dev" is_pull_request "$0" echo "Authenticating to Bluemix" bx login -a https://api.ng.bluemix.net echo "Targeting Bluemix org and space" bx target -o "$BLUEMIX_ORG" -s "$BLUEMIX_SPACE" echo "Initializing Bluemix Container Service" bx cs init ================================================ FILE: scripts/install.sh ================================================ #!/bin/bash -e # This script is intended to be run by Travis CI. If running elsewhere, invoke # it with: TRAVIS_PULL_REQUEST=false [path to script] # shellcheck disable=SC1090 source "$(dirname "$0")"/../scripts/resources.sh is_pull_request "$0" echo "Install Bluemix CLI" curl -L https://public.dhe.ibm.com/cloud/bluemix/cli/bluemix-cli/latest/IBM_Cloud_CLI_amd64.tar.gz > Bluemix_CLI.tar.gz tar -xvf Bluemix_CLI.tar.gz sudo ./Bluemix_CLI/install_bluemix_cli echo "Install kubectl" curl -LO https://storage.googleapis.com/kubernetes-release/release/"$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)"/bin/linux/amd64/kubectl chmod 0755 kubectl sudo mv kubectl /usr/local/bin echo "Configuring bx to disable version check" bx config --check-version=false echo "Checking bx version" bx --version echo "Install the Bluemix container-service plugin" bx plugin install container-service -r Bluemix if [[ -n "$DEBUG" ]]; then bx --version bx plugin list fi ================================================ FILE: scripts/quickstart.sh ================================================ #!/bin/bash echo 'password' > password.txt tr -d '\n' .strippedpassword.txt && mv .strippedpassword.txt password.txt kubectl apply -k ./ ================================================ FILE: scripts/resources.sh ================================================ #!/bin/bash # This script contains functions used by many of the scripts found in scripts/ # and tests/. test_failed(){ echo -e >&2 "\033[0;31m$1 test failed!\033[0m" exit 1 } test_passed(){ echo -e "\033[0;32m$1 test passed!\033[0m" } is_pull_request(){ if [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then echo -e "\033[0;33mPull Request detected; not running $1!\033[0m" exit 0 fi } ================================================ FILE: test-requirements.txt ================================================ yamllint ================================================ FILE: tests/deploy-minikube.sh ================================================ #!/bin/bash -e # shellcheck disable=SC1090 source "$(dirname "$0")"/../pattern-ci/scripts/resources.sh kubectl_deploy() { echo "Running scripts/quickstart.sh" "$(dirname "$0")"/../scripts/quickstart.sh echo "Waiting for pods to be running..." i=0 while [[ $(kubectl get pods -l app=wordpress | grep -c Running) -ne 2 ]]; do if [[ ! "$i" -lt 24 ]]; then echo "Timeout waiting on pods to be ready" test_failed "$0" fi sleep 10 echo "...$i * 10 seconds elapsed..." ((i++)) done kubectl get pods echo "All pods are running" } verify_deploy(){ echo "Verifying deployment..." kubectl get services sleep 60 if ! curl -sS "$(minikube service --url wordpress)"; then test_failed "$0" fi } main(){ if ! kubectl_deploy; then test_failed "$0" elif ! verify_deploy; then test_failed "$0" else test_passed "$0" fi } main ================================================ FILE: tests/test-kubernetes.sh ================================================ #!/bin/bash # This script is intended to be run by Travis CI. If running elsewhere, invoke # it with: TRAVIS_PULL_REQUEST=false [path to script] # CLUSTER_NAME must be set prior to running (see environment variables in the # Travis CI documentation). # shellcheck disable=SC1090 source "$(dirname "$0")"/../scripts/resources.sh kubectl_clean() { echo "Cleaning cluster" kubectl delete --ignore-not-found=true svc,pvc,deployment -l app=wordpress kubectl delete --ignore-not-found=true secret mysql-pass kubectl delete --ignore-not-found=true -f local-volumes.yaml kuber=$(kubectl get pods -l app=wordpress) while [ ${#kuber} -ne 0 ] do sleep 5s kubectl get pods -l app=wordpress kuber=$(kubectl get pods -l app=wordpress) done } kubectl_config() { echo "Configuring kubectl" #shellcheck disable=SC2091 $(bx cs cluster-config "$CLUSTER_NAME" | grep export) } kubectl_deploy() { kubectl_clean echo "Modifying yaml files to ignore storage-class" sed -i '$!N;/PersistentVolumeClaim.*\n.*metadata/a \ \ annotations: \n\ \ \ \ volume.beta.kubernetes.io/storage-class: ""' mysql-deployment.yaml sed -i '$!N;/PersistentVolumeClaim.*\n.*metadata/a \ \ annotations: \n\ \ \ \ volume.beta.kubernetes.io/storage-class: ""' wordpress-deployment.yaml echo "Running scripts/quickstart.sh" "$(dirname "$0")"/../scripts/quickstart.sh echo "Waiting for pods to be running..." i=0 while [[ $(kubectl get pods -l app=wordpress | grep -c Running) -ne 2 ]]; do if [[ ! "$i" -lt 24 ]]; then echo "Timeout waiting on pods to be ready" test_failed "$0" fi sleep 10 echo "...$i * 10 seconds elapsed..." ((i++)) done echo "All pods are running" sleep 30 } verify_deploy() { echo "Verifying deployment was successful" IPS=$(bx cs workers "$CLUSTER_NAME" | awk '{ print $2 }' | grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}') for IP in $IPS; do if ! curl -sS http://"$IP":30180/version; then test_failed "$0" fi done } main(){ is_pull_request "$0" if ! kubectl_config; then test_failed "$0" elif ! kubectl_deploy; then test_failed "$0" elif ! verify_deploy; then test_failed "$0" else test_passed "$0" kubectl_clean fi } main ================================================ FILE: wordpress-deployment-compose.yaml ================================================ --- apiVersion: v1 kind: Service metadata: name: wordpress-c labels: app: wordpress-c spec: ports: - port: 80 selector: app: wordpress-c tier: frontend-c type: NodePort --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: wpc-pv-claim labels: app: wordpress-c spec: accessModes: - ReadWriteOnce resources: requests: storage: 20Gi --- apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2 kind: Deployment metadata: name: wordpress-c labels: app: wordpress-c spec: selector: matchLabels: app: wordpress-c tier: frontend-c strategy: type: Recreate template: metadata: labels: app: wordpress-c tier: frontend-c spec: containers: - image: wordpress:latest name: wordpress-c env: - name: WORDPRESS_DB_HOST value: <>:<> - name: WORDPRESS_DB_USER value: <> - name: WORDPRESS_DB_PASSWORD value: <> ports: - containerPort: 80 name: wordpress-c volumeMounts: - name: wordpress-c-persistent-storage mountPath: /var/www/html volumes: - name: wordpress-c-persistent-storage persistentVolumeClaim: claimName: wpc-pv-claim ================================================ FILE: wordpress-deployment.yaml ================================================ --- apiVersion: v1 kind: Service metadata: name: wordpress labels: app: wordpress tier: frontend spec: ports: - port: 80 selector: app: wordpress tier: frontend type: NodePort --- apiVersion: v1 kind: PersistentVolume metadata: name: wp-pv-volume labels: type: local spec: storageClassName: manual capacity: storage: 20Gi accessModes: - ReadWriteOnce hostPath: path: "/tmp/wp/data" persistentVolumeReclaimPolicy: Recycle --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: wp-pv-claim labels: app: wordpress spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 20Gi --- apiVersion: apps/v1 # versions before 1.9.0 use apps/v1beta2 kind: Deployment metadata: name: wordpress labels: app: wordpress tier: frontend spec: selector: matchLabels: app: wordpress tier: frontend strategy: type: Recreate template: metadata: labels: app: wordpress tier: frontend spec: containers: - image: wordpress:5.8.1-php7.4 name: wordpress env: - name: WORDPRESS_DB_HOST value: wordpress-mysql - name: WORDPRESS_DB_NAME value: wordpress - name: WORDPRESS_DB_USER value: root - name: WORDPRESS_DB_PASSWORD valueFrom: secretKeyRef: name: mysql-pass key: password ports: - containerPort: 80 name: wordpress volumeMounts: - name: wordpress-persistent-storage mountPath: /var/www/html volumes: - name: wordpress-persistent-storage persistentVolumeClaim: claimName: wp-pv-claim