├── 00-before-you-begin └── README.md ├── 10-local-build-run-with-minikube ├── README.md └── skaffold.yaml ├── 20-local-build-run-with-docker-desktop └── README.md ├── 30-remote-build-to-gke ├── README.md └── skaffold.yaml ├── LICENSE ├── README.md └── voting-app ├── .github └── ISSUE_TEMPLATE ├── .gitignore ├── LICENSE ├── MAINTAINERS ├── architecture.png ├── k8s-specifications ├── db-deployment.yaml ├── db-service.yaml ├── redis-deployment.yaml ├── redis-service.yaml ├── result-deployment.yaml ├── result-service.yaml ├── vote-deployment.yaml ├── vote-service.yaml └── worker-deployment.yaml ├── result ├── Dockerfile ├── docker-compose.test.yml ├── package.json ├── server.js ├── tests │ ├── Dockerfile │ ├── render.js │ └── tests.sh └── views │ ├── app.js │ ├── index.html │ ├── socket.io.js │ └── stylesheets │ └── style.css ├── vote ├── Dockerfile ├── app.py ├── requirements.txt ├── static │ └── stylesheets │ │ └── style.css └── templates │ └── index.html └── worker ├── Dockerfile └── src └── Worker ├── Program.cs └── Worker.csproj /00-before-you-begin/README.md: -------------------------------------------------------------------------------- 1 | # 0. Before you begin 2 | 3 | - Install Skaffold: ([binary 4 | releases](https://github.com/GoogleContainerTools/skaffold/releases)) 5 | 6 | ``` 7 | brew install skaffold 8 | ``` 9 | 10 | - Clone this repo: 11 | 12 | ``` 13 | git clone https://github.com/ahmetb/skaffold-from-laptop-to-cloud demo 14 | 15 | cd demo 16 | ``` 17 | -------------------------------------------------------------------------------- /10-local-build-run-with-minikube/README.md: -------------------------------------------------------------------------------- 1 | # 1. Use Skaffold to build & run apps locally on Minikube 2 | 3 | Start `minikube` (verify via `minikube status`). 4 | 5 | Skaffold will automatically detect you have minikube turned on. 6 | 7 | Run: 8 | 9 | ``` 10 | skaffold dev -f 10-local-build-run-with-minikube/skaffold.yaml 11 | ``` 12 | 13 | This will build all images and deploy everything. 14 | 15 | Run `minikube service vote` & `minikube service result` to visit the apps. 16 | 17 | Make a change to one of the apps and watch `skaffold dev` rebuild and redeploy 18 | the manifests. 19 | 20 | Hit Ctrl+C to once to exit (cleanup will take some time). 21 | -------------------------------------------------------------------------------- /10-local-build-run-with-minikube/skaffold.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: skaffold/v1alpha2 2 | kind: Config 3 | build: 4 | artifacts: 5 | - imageName: vote 6 | workspace: voting-app/vote/ 7 | - imageName: worker 8 | workspace: voting-app/worker/ 9 | - imageName: result 10 | workspace: voting-app/result/ 11 | deploy: 12 | kubectl: 13 | manifests: 14 | - ./voting-app/k8s-specifications/* 15 | -------------------------------------------------------------------------------- /20-local-build-run-with-docker-desktop/README.md: -------------------------------------------------------------------------------- 1 | # 2. Use Skaffold to build & run apps locally on Docker for Desktop 2 | 3 | - (If you have Minikube running, stop it with `minikube stop`, otherwise it 4 | will be used.) 5 | - Download and install "Docker for Mac" 6 | - Go to Docker's Settings and enable "Kubernetes" 7 | - Wait until Kubernetes is enabled, run `kubectl get nodes` to verify. 8 | - Make sure your current context is docker-for-desktop: 9 | 10 | ```sh 11 | kubectl config current-context docker-for-desktop 12 | 13 | 14 | At this point you can just reuse the [same Skaffold manifest 15 | file][ff] you used for Minikube. 16 | 17 | Run: 18 | 19 | ``` 20 | skaffold dev -f 10-local-build-run-with-minikube/skaffold.yaml 21 | ``` 22 | 23 | This will build all images and deploy everything. 24 | 25 | Visit the `vote` app at http://localhost:31000 and the `result` app at 26 | http://localhost:31001. 27 | 28 | Make a change to the app and watch Skaffold rebuild the image and redeploy it. 29 | 30 | [ff]: ../10-local-build-run-with-minikube/skaffold.yaml 31 | -------------------------------------------------------------------------------- /30-remote-build-to-gke/README.md: -------------------------------------------------------------------------------- 1 | # 3. Use Skaffold to build & run apps remotely on GKE 2 | 3 | This will: 4 | - submit your source code to Google Cloud Container Builder (GCB) 5 | - GCB push your image onto Google Container Registry (GCR) 6 | - Skaffold will deploy it on Google Kubernetes Engine (GKE). 7 | 8 | If you managed to run the voting app locally (Minikube or DockerForDesktop), 9 | you can easily run it one GKE by just changing the image name. 10 | 11 | ### Before you begin, do these 12 | 13 | 1. Create a GKE cluster and make sure your `kubectl` is configured to use it. 14 | 2. Enable Google Container Registry (GCR) API 15 | 3. Enable Google Container Builder (GCB) API 16 | 4. Install GCR credentials helper: 17 | 18 | gcloud components install -q docker-credential-gcr 19 | gcloud auth configure-docker -q 20 | 21 | ### Steps 22 | 23 | 1. Take a look at the modified [skaffold.yaml](./skaffold.yaml). Prepend 24 | `gcr.io/YOUR_PROJECT/` string to `imageName:` fields. 25 | 26 | 1. In the same file, change `YOUR_PROJECT` under the `profiles:` section. 27 | 28 | 1. Visit the following files and update the `image:` field with these: 29 | 30 | - [voting-app/result-deployment.yaml](../voting-app/k8s-specifications/result-deployment.yaml) 31 | - [voting-app/worker-deployment.yaml](../voting-app/k8s-specifications/worker-deployment.yaml) 32 | - [voting-app/vote-deployment.yaml](../voting-app/k8s-specifications/vote-deployment.yaml) 33 | 34 | Don't worry about tagging. Skaffold automatically handles that. 35 | 36 | 1. Run: 37 | 38 | ``` 39 | skaffold dev -p gcb -f 30-remote-build-to-gke/skaffold.yaml 40 | ``` 41 | 42 | Now, Skaffold is uploading your source code to GCB, which pushes the resulting 43 | images to your GCR registry and it uses the active cluster on `kubectl` to 44 | deploy the result. 45 | -------------------------------------------------------------------------------- /30-remote-build-to-gke/skaffold.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: skaffold/v1alpha2 2 | kind: Config 3 | build: 4 | artifacts: 5 | - imageName: gcr.io/YOUR_PROJECT_ID/vote 6 | workspace: voting-app/vote/ 7 | - imageName: gcr.io/YOUR_PROJECT_ID/worker 8 | workspace: voting-app/worker/ 9 | - imageName: gcr.io/YOUR_PROJECT_ID/result 10 | workspace: voting-app/result/ 11 | deploy: 12 | kubectl: 13 | manifests: 14 | - ./voting-app/k8s-specifications/* 15 | profiles: 16 | - name: gcb 17 | build: 18 | googleCloudBuild: 19 | projectId: YOUR_PROJECT_ID 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Skaffold: From code on your laptop to cloud 💻→📦→☁️ 2 | 3 | [Skaffold](https://github.com/GoogleContainerTools/skaffold) is an open source 4 | tool by Google that helps you build and run your source on Kubernetes locally, 5 | or remotely on the cloud. 6 | 7 | This repository uses [Docker's example voting app][voting] and adds Skaffold 8 | manifest files to it and walks you through using Skaffold. 9 | 10 | ## Start your journey "from zero to Skaffold" 11 | 12 | 0. [Before you begin](00-before-you-begin/README.md) 13 | 1. [Use Skaffold to build & run apps locally on 14 | Minikube](10-local-build-run-with-minikube/README.md) 15 | 1. [Use Skaffold to build & run apps locally on 16 | Docker for Mac/Windows](20-local-build-run-with-docker-desktop/README.md) 17 | 18 | 1. [Use Skaffold to build & run apps remotely 19 | on GKE (Google Kubernetes Engine)](30-remote-build-to-gke/README.md) 20 | 21 | 22 | ## Voting app architecture 23 | 24 | ![Voting app architecture 25 | diagram](voting-app/architecture.png) 26 | 27 | [voting]: https://github.com/dockersamples/example-voting-app 28 | 29 | 30 | ### About this tutorial 31 | 32 | Author: [@ahmetb](https://twitter.com/ahmetb/) 33 | 34 | - This workshop is licensed under Apache License Version 2.0. Copright 2018 Google Inc. 35 | 36 | - Voting App (`./voting-app`) is licensed under Apache License Version 2.0. Copyright 2016 Docker, Inc. Visit 37 | its [repository][voting]. 38 | 39 | 40 | -------------------------------------------------------------------------------- /voting-app/.github/ISSUE_TEMPLATE: -------------------------------------------------------------------------------- 1 | ** PLEASE ONLY USE THIS ISSUE TRACKER TO SUBMIT ISSUES WITH THE EXAMPLE VOTING APP ** 2 | 3 | * If you have a bug working with Docker itself, not related to these labs, please file the bug on the [Docker repo](https://github.com/docker/docker) * 4 | * If you would like general support figuring out how to do something with Docker, please use the Docker Slack channel. If you're not on that channel, sign up for the [Docker Community](http://dockr.ly/MeetUp) and you'll get an invite. * 5 | * Or go to the [Docker Forums](https://forums.docker.com/) * 6 | 7 | Please provide the following information so we can assess the issue you're having 8 | 9 | **Description** 10 | 11 | 14 | 15 | **Steps to reproduce the issue, if relevant:** 16 | 1. 17 | 2. 18 | 3. 19 | 20 | **Describe the results you received:** 21 | 22 | 23 | **Describe the results you expected:** 24 | 25 | 26 | **Additional information you deem important (e.g. issue happens only occasionally):** 27 | 28 | **Output of `docker version`:** 29 | 30 | ``` 31 | (paste your output here) 32 | ``` 33 | 34 | **Output of `docker info`:** 35 | 36 | ``` 37 | (paste your output here) 38 | ``` 39 | 40 | **Additional environment details (AWS, Docker for Mac, Docker for Windows, VirtualBox, physical, etc.):** 41 | -------------------------------------------------------------------------------- /voting-app/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | project.lock.json 3 | bin/ 4 | obj/ 5 | 6 | skaffold.yaml 7 | -------------------------------------------------------------------------------- /voting-app/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | Copyright 2016 Docker, Inc. 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /voting-app/MAINTAINERS: -------------------------------------------------------------------------------- 1 | Aanand Prasad 2 | Ben Firshman 3 | Fernando Mayo 4 | Mano Marks 5 | Maxime Heckel 6 | -------------------------------------------------------------------------------- /voting-app/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmetb/skaffold-from-laptop-to-cloud/ba0e811850a329d906399f576552fb53cc490e69/voting-app/architecture.png -------------------------------------------------------------------------------- /voting-app/k8s-specifications/db-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: db 5 | spec: 6 | replicas: 1 7 | template: 8 | metadata: 9 | labels: 10 | app: db 11 | spec: 12 | containers: 13 | - image: postgres:9.4 14 | name: db 15 | volumeMounts: 16 | - mountPath: /var/lib/postgresql/data 17 | name: db-data 18 | volumes: 19 | - name: db-data 20 | emptyDir: {} 21 | -------------------------------------------------------------------------------- /voting-app/k8s-specifications/db-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: db 5 | spec: 6 | type: ClusterIP 7 | ports: 8 | - port: 5432 9 | targetPort: 5432 10 | selector: 11 | app: db 12 | 13 | -------------------------------------------------------------------------------- /voting-app/k8s-specifications/redis-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: redis 5 | spec: 6 | replicas: 1 7 | template: 8 | metadata: 9 | labels: 10 | app: redis 11 | spec: 12 | containers: 13 | - image: redis:alpine 14 | name: redis 15 | volumeMounts: 16 | - mountPath: /data 17 | name: redis-data 18 | volumes: 19 | - name: redis-data 20 | emptyDir: {} 21 | -------------------------------------------------------------------------------- /voting-app/k8s-specifications/redis-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: redis 5 | spec: 6 | type: ClusterIP 7 | ports: 8 | - port: 6379 9 | targetPort: 6379 10 | selector: 11 | app: redis 12 | 13 | -------------------------------------------------------------------------------- /voting-app/k8s-specifications/result-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: result 5 | spec: 6 | replicas: 1 7 | template: 8 | metadata: 9 | labels: 10 | app: result 11 | spec: 12 | containers: 13 | - image: gcr.io/YOUR_PROJECT/result 14 | name: result 15 | -------------------------------------------------------------------------------- /voting-app/k8s-specifications/result-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: result 5 | spec: 6 | type: NodePort 7 | ports: 8 | - name: "result-service" 9 | port: 5001 10 | targetPort: 80 11 | nodePort: 31001 12 | selector: 13 | app: result 14 | --- 15 | apiVersion: v1 16 | kind: Service 17 | metadata: 18 | name: result-external 19 | spec: 20 | type: LoadBalancer 21 | ports: 22 | - name: "result-service" 23 | port: 8001 24 | targetPort: 80 25 | selector: 26 | app: result 27 | -------------------------------------------------------------------------------- /voting-app/k8s-specifications/vote-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: vote 5 | spec: 6 | replicas: 1 7 | template: 8 | metadata: 9 | labels: 10 | app: vote 11 | spec: 12 | containers: 13 | - image: gcr.io/YOUR_PROJECT/vote 14 | name: vote 15 | -------------------------------------------------------------------------------- /voting-app/k8s-specifications/vote-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: vote 5 | spec: 6 | type: NodePort 7 | ports: 8 | - name: "vote-service" 9 | port: 5000 10 | targetPort: 80 11 | nodePort: 31000 12 | selector: 13 | app: vote 14 | --- 15 | apiVersion: v1 16 | kind: Service 17 | metadata: 18 | name: vote-external 19 | spec: 20 | type: LoadBalancer 21 | ports: 22 | - name: "vote-service" 23 | port: 8000 24 | targetPort: 80 25 | selector: 26 | app: vote 27 | -------------------------------------------------------------------------------- /voting-app/k8s-specifications/worker-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: worker 5 | spec: 6 | replicas: 1 7 | template: 8 | metadata: 9 | labels: 10 | app: worker 11 | spec: 12 | containers: 13 | - image: gcr.io/YOUR_PROJECT/worker 14 | name: worker 15 | -------------------------------------------------------------------------------- /voting-app/result/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:8.9-alpine 2 | 3 | RUN mkdir -p /app 4 | WORKDIR /app 5 | 6 | RUN npm install -g nodemon 7 | RUN npm config set registry https://registry.npmjs.org 8 | COPY package.json /app/package.json 9 | RUN npm install \ 10 | && npm ls \ 11 | && npm cache clean --force \ 12 | && mv /app/node_modules /node_modules 13 | COPY . /app 14 | 15 | ENV PORT 80 16 | EXPOSE 80 17 | 18 | CMD ["node", "server.js"] 19 | -------------------------------------------------------------------------------- /voting-app/result/docker-compose.test.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | services: 4 | 5 | sut: 6 | build: ./tests/ 7 | depends_on: 8 | - vote 9 | - result 10 | - worker 11 | networks: 12 | - front-tier 13 | 14 | vote: 15 | build: ../vote/ 16 | ports: ["80"] 17 | depends_on: 18 | - redis 19 | - db 20 | networks: 21 | - front-tier 22 | - back-tier 23 | 24 | result: 25 | build: . 26 | ports: ["80"] 27 | depends_on: 28 | - redis 29 | - db 30 | networks: 31 | - front-tier 32 | - back-tier 33 | 34 | worker: 35 | build: ../worker/ 36 | depends_on: 37 | - redis 38 | - db 39 | networks: 40 | - back-tier 41 | 42 | redis: 43 | image: redis:alpine 44 | ports: ["6379"] 45 | networks: 46 | - back-tier 47 | 48 | db: 49 | image: postgres:9.4 50 | volumes: 51 | - "db-data:/var/lib/postgresql/data" 52 | networks: 53 | - back-tier 54 | 55 | volumes: 56 | db-data: 57 | 58 | networks: 59 | front-tier: 60 | back-tier: 61 | -------------------------------------------------------------------------------- /voting-app/result/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "result", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "server.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "MIT", 11 | "dependencies": { 12 | "body-parser": "^1.14.1", 13 | "cookie-parser": "^1.4.0", 14 | "express": "^4.13.3", 15 | "method-override": "^2.3.5", 16 | "async": "^1.5.0", 17 | "pg": "^4.4.3", 18 | "socket.io": "^1.3.7" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /voting-app/result/server.js: -------------------------------------------------------------------------------- 1 | var express = require('express'), 2 | async = require('async'), 3 | pg = require("pg"), 4 | path = require("path"), 5 | cookieParser = require('cookie-parser'), 6 | bodyParser = require('body-parser'), 7 | methodOverride = require('method-override'), 8 | app = express(), 9 | server = require('http').Server(app), 10 | io = require('socket.io')(server); 11 | 12 | io.set('transports', ['polling']); 13 | 14 | var port = process.env.PORT || 4000; 15 | 16 | io.sockets.on('connection', function (socket) { 17 | 18 | socket.emit('message', { text : 'Welcome!' }); 19 | 20 | socket.on('subscribe', function (data) { 21 | socket.join(data.channel); 22 | }); 23 | }); 24 | 25 | async.retry( 26 | {times: 1000, interval: 1000}, 27 | function(callback) { 28 | pg.connect('postgres://postgres@db/postgres', function(err, client, done) { 29 | if (err) { 30 | console.error("Waiting for db"); 31 | } 32 | callback(err, client); 33 | }); 34 | }, 35 | function(err, client) { 36 | if (err) { 37 | return console.error("Giving up"); 38 | } 39 | console.log("Connected to db"); 40 | getVotes(client); 41 | } 42 | ); 43 | 44 | function getVotes(client) { 45 | client.query('SELECT vote, COUNT(id) AS count FROM votes GROUP BY vote', [], function(err, result) { 46 | if (err) { 47 | console.error("Error performing query: " + err); 48 | } else { 49 | var votes = collectVotesFromResult(result); 50 | io.sockets.emit("scores", JSON.stringify(votes)); 51 | } 52 | 53 | setTimeout(function() {getVotes(client) }, 1000); 54 | }); 55 | } 56 | 57 | function collectVotesFromResult(result) { 58 | var votes = {a: 0, b: 0}; 59 | 60 | result.rows.forEach(function (row) { 61 | votes[row.vote] = parseInt(row.count); 62 | }); 63 | 64 | return votes; 65 | } 66 | 67 | app.use(cookieParser()); 68 | app.use(bodyParser()); 69 | app.use(methodOverride('X-HTTP-Method-Override')); 70 | app.use(function(req, res, next) { 71 | res.header("Access-Control-Allow-Origin", "*"); 72 | res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 73 | res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS"); 74 | next(); 75 | }); 76 | 77 | app.use(express.static(__dirname + '/views')); 78 | 79 | app.get('/', function (req, res) { 80 | res.sendFile(path.resolve(__dirname + '/views/index.html')); 81 | }); 82 | 83 | server.listen(port, function () { 84 | var port = server.address().port; 85 | console.log('App running on port ' + port); 86 | }); 87 | -------------------------------------------------------------------------------- /voting-app/result/tests/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:8.9-slim 2 | 3 | RUN apt-get update -qq && apt-get install -qy \ 4 | ca-certificates \ 5 | bzip2 \ 6 | curl \ 7 | libfontconfig \ 8 | --no-install-recommends 9 | RUN yarn global add phantomjs-prebuilt 10 | ADD . /app 11 | WORKDIR /app 12 | CMD ["/app/tests.sh"] 13 | -------------------------------------------------------------------------------- /voting-app/result/tests/render.js: -------------------------------------------------------------------------------- 1 | var system = require('system'); 2 | var page = require('webpage').create(); 3 | var url = system.args[1]; 4 | 5 | page.onLoadFinished = function() { 6 | setTimeout(function(){ 7 | console.log(page.content); 8 | phantom.exit(); 9 | }, 1000); 10 | }; 11 | 12 | page.open(url, function() { 13 | page.evaluate(function() { 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /voting-app/result/tests/tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | while ! timeout 1 bash -c "echo > /dev/tcp/vote/80"; do 4 | sleep 1 5 | done 6 | 7 | curl -sS -X POST --data "vote=b" http://vote > /dev/null 8 | sleep 10 9 | 10 | if phantomjs render.js http://result | grep -q '1 vote'; then 11 | echo -e "\\e[42m------------" 12 | echo -e "\\e[92mTests passed" 13 | echo -e "\\e[42m------------" 14 | exit 0 15 | else 16 | echo -e "\\e[41m------------" 17 | echo -e "\\e[91mTests failed" 18 | echo -e "\\e[41m------------" 19 | exit 1 20 | fi 21 | -------------------------------------------------------------------------------- /voting-app/result/views/app.js: -------------------------------------------------------------------------------- 1 | var app = angular.module('catsvsdogs', []); 2 | var socket = io.connect({transports:['polling']}); 3 | 4 | var bg1 = document.getElementById('background-stats-1'); 5 | var bg2 = document.getElementById('background-stats-2'); 6 | 7 | app.controller('statsCtrl', function($scope){ 8 | $scope.aPercent = 50; 9 | $scope.bPercent = 50; 10 | 11 | var updateScores = function(){ 12 | socket.on('scores', function (json) { 13 | data = JSON.parse(json); 14 | var a = parseInt(data.a || 0); 15 | var b = parseInt(data.b || 0); 16 | 17 | var percentages = getPercentages(a, b); 18 | 19 | bg1.style.width = percentages.a + "%"; 20 | bg2.style.width = percentages.b + "%"; 21 | 22 | $scope.$apply(function () { 23 | $scope.aPercent = percentages.a; 24 | $scope.bPercent = percentages.b; 25 | $scope.total = a + b; 26 | }); 27 | }); 28 | }; 29 | 30 | var init = function(){ 31 | document.body.style.opacity=1; 32 | updateScores(); 33 | }; 34 | socket.on('message',function(data){ 35 | init(); 36 | }); 37 | }); 38 | 39 | function getPercentages(a, b) { 40 | var result = {}; 41 | 42 | if (a + b > 0) { 43 | result.a = Math.round(a / (a + b) * 100); 44 | result.b = 100 - result.a; 45 | } else { 46 | result.a = result.b = 50; 47 | } 48 | 49 | return result; 50 | } -------------------------------------------------------------------------------- /voting-app/result/views/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Cats vs Dogs -- Result 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
Cats
24 |
{{aPercent | number:1}}%
25 |
26 |
27 |
28 |
Dogs
29 |
{{bPercent | number:1}}%
30 |
31 |
32 |
33 |
34 |
35 | No votes yet 36 | {{total}} vote 37 | {{total}} votes 38 |
39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /voting-app/result/views/stylesheets/style.css: -------------------------------------------------------------------------------- 1 | @import url(//fonts.googleapis.com/css?family=Open+Sans:400,700,600); 2 | 3 | *{ 4 | box-sizing:border-box; 5 | } 6 | html,body{ 7 | margin:0; 8 | padding:0; 9 | height:100%; 10 | font-family: 'Open Sans'; 11 | } 12 | body{ 13 | opacity:0; 14 | transition: all 1s linear; 15 | } 16 | 17 | .divider{ 18 | height: 150px; 19 | width:2px; 20 | background-color: #C0C9CE; 21 | position: relative; 22 | top: 50%; 23 | float: left; 24 | transform: translateY(-50%); 25 | } 26 | 27 | #background-stats-1{ 28 | background-color: #2196f3; 29 | } 30 | 31 | #background-stats-2{ 32 | background-color: #00cbca; 33 | } 34 | 35 | #content-container{ 36 | z-index:2; 37 | position:relative; 38 | margin:0 auto; 39 | display:table; 40 | padding:10px; 41 | max-width:940px; 42 | height:100%; 43 | } 44 | #content-container-center{ 45 | display:table-cell; 46 | text-align:center; 47 | vertical-align:middle; 48 | } 49 | #result{ 50 | z-index: 3; 51 | position: absolute; 52 | bottom: 40px; 53 | right: 20px; 54 | color: #fff; 55 | opacity: 0.5; 56 | font-size: 45px; 57 | font-weight: 600; 58 | } 59 | #choice{ 60 | transition: all 300ms linear; 61 | line-height:1.3em; 62 | background:#fff; 63 | box-shadow: 10px 0 0 #fff, -10px 0 0 #fff; 64 | vertical-align:middle; 65 | font-size:40px; 66 | font-weight: 600; 67 | width: 450px; 68 | height: 200px; 69 | } 70 | #choice a{ 71 | text-decoration:none; 72 | } 73 | #choice a:hover, #choice a:focus{ 74 | outline:0; 75 | text-decoration:underline; 76 | } 77 | 78 | #choice .choice{ 79 | width: 49%; 80 | position: relative; 81 | top: 50%; 82 | transform: translateY(-50%); 83 | text-align: left; 84 | padding-left: 50px; 85 | } 86 | 87 | #choice .choice .label{ 88 | text-transform: uppercase; 89 | } 90 | 91 | #choice .choice.dogs{ 92 | color: #00cbca; 93 | float: right; 94 | } 95 | 96 | #choice .choice.cats{ 97 | color: #2196f3; 98 | float: left; 99 | } 100 | #background-stats{ 101 | z-index:1; 102 | height:100%; 103 | width:100%; 104 | position:absolute; 105 | } 106 | #background-stats div{ 107 | transition: width 400ms ease-in-out; 108 | display:inline-block; 109 | margin-bottom:-4px; 110 | width:50%; 111 | height:100%; 112 | } 113 | -------------------------------------------------------------------------------- /voting-app/vote/Dockerfile: -------------------------------------------------------------------------------- 1 | # Using official python runtime base image 2 | FROM python:2.7-alpine 3 | 4 | # Set the application directory 5 | WORKDIR /app 6 | 7 | # Install our requirements.txt 8 | ADD requirements.txt /app/requirements.txt 9 | RUN pip install -r requirements.txt 10 | 11 | # Copy our code from the current folder to /app inside the container 12 | ADD . /app 13 | 14 | # Make port 80 available for links and/or publish 15 | EXPOSE 80 16 | 17 | # Define our command to be run when launching the container 18 | CMD ["gunicorn", "app:app", "-b", "0.0.0.0:80", "--log-file", "-", "--access-logfile", "-", "--workers", "4", "--keep-alive", "0"] 19 | -------------------------------------------------------------------------------- /voting-app/vote/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request, make_response, g 2 | from redis import Redis 3 | import os 4 | import socket 5 | import random 6 | import json 7 | 8 | option_a = os.getenv('OPTION_A', "Cats") 9 | option_b = os.getenv('OPTION_B', "Dogs") 10 | hostname = socket.gethostname() 11 | 12 | app = Flask(__name__) 13 | 14 | def get_redis(): 15 | if not hasattr(g, 'redis'): 16 | g.redis = Redis(host="redis", db=0, socket_timeout=5) 17 | return g.redis 18 | 19 | @app.route("/", methods=['POST','GET']) 20 | def hello(): 21 | voter_id = request.cookies.get('voter_id') 22 | if not voter_id: 23 | voter_id = hex(random.getrandbits(64))[2:-1] 24 | 25 | vote = None 26 | 27 | if request.method == 'POST': 28 | redis = get_redis() 29 | vote = request.form['vote'] 30 | data = json.dumps({'voter_id': voter_id, 'vote': vote}) 31 | redis.rpush('votes', data) 32 | 33 | resp = make_response(render_template( 34 | 'index.html', 35 | option_a=option_a, 36 | option_b=option_b, 37 | hostname=hostname, 38 | vote=vote, 39 | )) 40 | resp.set_cookie('voter_id', voter_id) 41 | return resp 42 | 43 | 44 | if __name__ == "__main__": 45 | app.run(host='0.0.0.0', port=80, debug=True, threaded=True) 46 | -------------------------------------------------------------------------------- /voting-app/vote/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask 2 | Redis 3 | gunicorn 4 | -------------------------------------------------------------------------------- /voting-app/vote/static/stylesheets/style.css: -------------------------------------------------------------------------------- 1 | @import url(//fonts.googleapis.com/css?family=Open+Sans:400,700,600); 2 | 3 | *{ 4 | box-sizing:border-box; 5 | } 6 | html,body{ 7 | margin: 0; 8 | padding: 0; 9 | background-color: #F7F8F9; 10 | height: 100vh; 11 | font-family: 'Open Sans'; 12 | } 13 | 14 | button{ 15 | border-radius: 0; 16 | width: 100%; 17 | height: 50%; 18 | } 19 | 20 | button[type="submit"] { 21 | -webkit-appearance:none; -webkit-border-radius:0; 22 | } 23 | 24 | button i{ 25 | float: right; 26 | padding-right: 30px; 27 | margin-top: 3px; 28 | } 29 | 30 | button.a{ 31 | background-color: #1aaaf8; 32 | } 33 | 34 | button.b{ 35 | background-color: #00cbca; 36 | } 37 | 38 | #tip{ 39 | text-align: left; 40 | color: #c0c9ce; 41 | font-size: 14px; 42 | } 43 | 44 | #hostname{ 45 | position: absolute; 46 | bottom: 100px; 47 | right: 0; 48 | left: 0; 49 | color: #8f9ea8; 50 | font-size: 24px; 51 | } 52 | 53 | #content-container{ 54 | z-index: 2; 55 | position: relative; 56 | margin: 0 auto; 57 | display: table; 58 | padding: 10px; 59 | max-width: 940px; 60 | height: 100%; 61 | } 62 | #content-container-center{ 63 | display: table-cell; 64 | text-align: center; 65 | } 66 | 67 | #content-container-center h3{ 68 | color: #254356; 69 | } 70 | 71 | #choice{ 72 | transition: all 300ms linear; 73 | line-height: 1.3em; 74 | display: inline; 75 | vertical-align: middle; 76 | font-size: 3em; 77 | } 78 | #choice a{ 79 | text-decoration:none; 80 | } 81 | #choice a:hover, #choice a:focus{ 82 | outline:0; 83 | text-decoration:underline; 84 | } 85 | 86 | #choice button{ 87 | display: block; 88 | height: 80px; 89 | width: 330px; 90 | border: none; 91 | color: white; 92 | text-transform: uppercase; 93 | font-size:18px; 94 | font-weight: 700; 95 | margin-top: 10px; 96 | margin-bottom: 10px; 97 | text-align: left; 98 | padding-left: 50px; 99 | } 100 | 101 | #choice button.a:hover{ 102 | background-color: #1488c6; 103 | } 104 | 105 | #choice button.b:hover{ 106 | background-color: #00a2a1; 107 | } 108 | 109 | #choice button.a:focus{ 110 | background-color: #1488c6; 111 | } 112 | 113 | #choice button.b:focus{ 114 | background-color: #00a2a1; 115 | } 116 | 117 | #background-stats{ 118 | z-index:1; 119 | height:100%; 120 | width:100%; 121 | position:absolute; 122 | } 123 | #background-stats div{ 124 | transition: width 400ms ease-in-out; 125 | display:inline-block; 126 | margin-bottom:-4px; 127 | width:50%; 128 | height:100%; 129 | } 130 | -------------------------------------------------------------------------------- /voting-app/vote/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {{option_a}} vs {{option_b}}! 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 |

{{option_a}} vs {{option_b}}!

17 |
18 | 19 | 20 |
21 |
22 | (Tip: you can change your vote) 23 |
24 |
25 | Processed by container ID {{hostname}} 26 |
27 |
28 |
29 | 30 | 31 | 32 | {% if vote %} 33 | 47 | {% endif %} 48 | 49 | 50 | -------------------------------------------------------------------------------- /voting-app/worker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM microsoft/dotnet:2.0.0-sdk 2 | 3 | WORKDIR /code 4 | 5 | ADD src/Worker /code/src/Worker 6 | 7 | RUN dotnet restore -v minimal src/Worker \ 8 | && dotnet publish -c Release -o "./" "src/Worker/" 9 | 10 | CMD dotnet src/Worker/Worker.dll -------------------------------------------------------------------------------- /voting-app/worker/src/Worker/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Common; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Sockets; 6 | using System.Threading; 7 | using Newtonsoft.Json; 8 | using Npgsql; 9 | using StackExchange.Redis; 10 | 11 | namespace Worker 12 | { 13 | public class Program 14 | { 15 | public static int Main(string[] args) 16 | { 17 | try 18 | { 19 | var pgsql = OpenDbConnection("Server=db;Username=postgres;"); 20 | var redisConn = OpenRedisConnection("redis"); 21 | var redis = redisConn.GetDatabase(); 22 | 23 | // Keep alive is not implemented in Npgsql yet. This workaround was recommended: 24 | // https://github.com/npgsql/npgsql/issues/1214#issuecomment-235828359 25 | var keepAliveCommand = pgsql.CreateCommand(); 26 | keepAliveCommand.CommandText = "SELECT 1"; 27 | 28 | var definition = new { vote = "", voter_id = "" }; 29 | while (true) 30 | { 31 | // Slow down to prevent CPU spike, only query each 100ms 32 | Thread.Sleep(100); 33 | 34 | // Reconnect redis if down 35 | if (redisConn == null || !redisConn.IsConnected) { 36 | Console.WriteLine("Reconnecting Redis"); 37 | redisConn = OpenRedisConnection("redis"); 38 | redis = redisConn.GetDatabase(); 39 | } 40 | string json = redis.ListLeftPopAsync("votes").Result; 41 | if (json != null) 42 | { 43 | var vote = JsonConvert.DeserializeAnonymousType(json, definition); 44 | Console.WriteLine($"Processing vote for '{vote.vote}' by '{vote.voter_id}'"); 45 | // Reconnect DB if down 46 | if (!pgsql.State.Equals(System.Data.ConnectionState.Open)) 47 | { 48 | Console.WriteLine("Reconnecting DB"); 49 | pgsql = OpenDbConnection("Server=db;Username=postgres;"); 50 | } 51 | else 52 | { // Normal +1 vote requested 53 | UpdateVote(pgsql, vote.voter_id, vote.vote); 54 | } 55 | } 56 | else 57 | { 58 | keepAliveCommand.ExecuteNonQuery(); 59 | } 60 | } 61 | } 62 | catch (Exception ex) 63 | { 64 | Console.Error.WriteLine(ex.ToString()); 65 | return 1; 66 | } 67 | } 68 | 69 | private static NpgsqlConnection OpenDbConnection(string connectionString) 70 | { 71 | NpgsqlConnection connection; 72 | 73 | while (true) 74 | { 75 | try 76 | { 77 | connection = new NpgsqlConnection(connectionString); 78 | connection.Open(); 79 | break; 80 | } 81 | catch (SocketException) 82 | { 83 | Console.Error.WriteLine("Waiting for db"); 84 | Thread.Sleep(1000); 85 | } 86 | catch (DbException) 87 | { 88 | Console.Error.WriteLine("Waiting for db"); 89 | Thread.Sleep(1000); 90 | } 91 | } 92 | 93 | Console.Error.WriteLine("Connected to db"); 94 | 95 | var command = connection.CreateCommand(); 96 | command.CommandText = @"CREATE TABLE IF NOT EXISTS votes ( 97 | id VARCHAR(255) NOT NULL UNIQUE, 98 | vote VARCHAR(255) NOT NULL 99 | )"; 100 | command.ExecuteNonQuery(); 101 | 102 | return connection; 103 | } 104 | 105 | private static ConnectionMultiplexer OpenRedisConnection(string hostname) 106 | { 107 | // Use IP address to workaround hhttps://github.com/StackExchange/StackExchange.Redis/issues/410 108 | var ipAddress = GetIp(hostname); 109 | Console.WriteLine($"Found redis at {ipAddress}"); 110 | 111 | while (true) 112 | { 113 | try 114 | { 115 | Console.Error.WriteLine("Connecting to redis"); 116 | return ConnectionMultiplexer.Connect(ipAddress); 117 | } 118 | catch (RedisConnectionException) 119 | { 120 | Console.Error.WriteLine("Waiting for redis"); 121 | Thread.Sleep(1000); 122 | } 123 | } 124 | } 125 | 126 | private static string GetIp(string hostname) 127 | => Dns.GetHostEntryAsync(hostname) 128 | .Result 129 | .AddressList 130 | .First(a => a.AddressFamily == AddressFamily.InterNetwork) 131 | .ToString(); 132 | 133 | private static void UpdateVote(NpgsqlConnection connection, string voterId, string vote) 134 | { 135 | var command = connection.CreateCommand(); 136 | try 137 | { 138 | command.CommandText = "INSERT INTO votes (id, vote) VALUES (@id, @vote)"; 139 | command.Parameters.AddWithValue("@id", voterId); 140 | command.Parameters.AddWithValue("@vote", vote); 141 | command.ExecuteNonQuery(); 142 | } 143 | catch (DbException) 144 | { 145 | command.CommandText = "UPDATE votes SET vote = @vote WHERE id = @id"; 146 | command.ExecuteNonQuery(); 147 | } 148 | finally 149 | { 150 | command.Dispose(); 151 | } 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /voting-app/worker/src/Worker/Worker.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | true 6 | Worker 7 | Exe 8 | Worker 9 | true 10 | 2.0.0 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | --------------------------------------------------------------------------------