├── .gitignore
├── LICENSE
├── README.md
├── fib-calc
├── client-webapp
│ ├── .gitignore
│ ├── Dockerfile.dev
│ ├── README.md
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ │ ├── favicon.ico
│ │ ├── index.html
│ │ └── manifest.json
│ └── src
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Fib.js
│ │ ├── SecondPage.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── logo.svg
│ │ └── serviceWorker.js
├── docker-compose.yml
├── exp-server
│ ├── Dockerfile
│ ├── Dockerfile.dev
│ ├── index.js
│ ├── keys.js
│ └── package.json
├── nginx
│ ├── Dockerfile
│ ├── Dockerfile.dev
│ └── default.conf
└── worker
│ ├── Dockerfile
│ ├── Dockerfile.dev
│ ├── index.js
│ ├── keys.js
│ └── package.json
├── react-app
├── .gitignore
├── Dockerfile
├── Dockerfile.dev
├── README.md
├── docker-compose.yml
├── package-lock.json
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ └── serviceWorker.js
├── redis-image
└── Dockerfile
├── visits-counter
├── Dockerfile
├── app.js
├── docker-compose.yml
└── package.json
└── webapp
├── Dockerfile
├── app.js
└── package.json
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .vscode/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Manasés Jesús
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Docker and Kubernetes: The Complete Guide
2 |
3 | Build, test and deploy Docker applications with Kubernetes while learning production-style development workflows.
4 |
5 | This repository contains the exercises from the course with my additions/modifications/notes.
6 | Course available at https://www.udemy.com/docker-and-kubernetes-the-complete-guide
7 |
8 |
9 | ## fib-calc
10 | A multicontainer and "complicated" version of a Fibonacci calculator. It runs on a Nginx server, uses React for the frontend and Express for the backend API. All calculated values get stored in a Postgres database and it uses Redis for the logs. A worker process watches Redis for new indexes and calculates the Fibonacci value.
11 |
12 | ## react-app
13 | A bootstrapped React application running on a container.
14 | Multi-step Docker process to have a build phase and a run phase.
15 | It uses Nginx to serve the application.
16 |
17 | ## redis-image
18 | Use an existing user image as a base, download and install a dependency and tell the image what to do when it starts as a container.
19 |
20 | ## visits-counter
21 | A Node.js application that counts the number of page visits. It uses two containers, one for the Node.js server and one for Redis to store the value.
22 |
23 | Docker compose creates the two containers (redis, node); both have free access to each other and can exchange as much information as they need.
24 |
25 | ## webapp
26 | A simple "Hello world" application in using Node.js and Express.
27 | Using Docker to specify a base image and working directory, copy/install dependencies and run a default command.
28 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/Dockerfile.dev:
--------------------------------------------------------------------------------
1 | FROM node:alpine
2 | WORKDIR /usr/app
3 |
4 | COPY ./package.json ./
5 | RUN npm install
6 | COPY ./ ./
7 |
8 | CMD ["npm", "run", "dev"]
9 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `npm start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `npm test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `npm run build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `npm run eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
35 |
36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
37 |
38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "client-webapp",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "react": "^16.6.3",
7 | "react-dom": "^16.6.3",
8 | "react-scripts": "2.1.1",
9 | "react-router-dom": "4.3.1",
10 | "axios": ">=0.21.2"
11 | },
12 | "scripts": {
13 | "start": "react-scripts start",
14 | "build": "react-scripts build",
15 | "test": "react-scripts test",
16 | "eject": "react-scripts eject"
17 | },
18 | "eslintConfig": {
19 | "extends": "react-app"
20 | },
21 | "browserslist": [
22 | ">0.2%",
23 | "not dead",
24 | "not ie <= 11",
25 | "not op_mini all"
26 | ]
27 | }
28 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/manasesjesus/docker-and-kubernetes/326155025c471bc6d05ed98f88ccc2ab1d0fd596/fib-calc/client-webapp/public/favicon.ico
--------------------------------------------------------------------------------
/fib-calc/client-webapp/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
26 | You need to enable JavaScript to run this app.
27 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 40vmin;
8 | }
9 |
10 | .App-header {
11 | background-color: #282c34;
12 | min-height: 100vh;
13 | display: flex;
14 | flex-direction: column;
15 | align-items: center;
16 | justify-content: center;
17 | font-size: calc(10px + 2vmin);
18 | color: white;
19 | }
20 |
21 | .App-link {
22 | color: #61dafb;
23 | }
24 |
25 | @keyframes App-logo-spin {
26 | from {
27 | transform: rotate(0deg);
28 | }
29 | to {
30 | transform: rotate(360deg);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import logo from './logo.svg';
3 | import './App.css';
4 |
5 | import { BrowserRouter as Router, Route, Link } from "react-router-dom";
6 | import SecondPage from "./SecondPage";
7 | import Fib from "./Fib";
8 |
9 | class App extends Component {
10 | render() {
11 | return (
12 |
13 |
14 |
15 |
16 | Fibonacci Calculator
17 | Home
18 | 2nd Page
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | );
27 | }
28 | }
29 |
30 | export default App;
31 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render( , div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/Fib.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from "react";
2 | import axios from "axios";
3 |
4 | class Fib extends Component {
5 | state = {
6 | seenIndexes: [ ],
7 | values: { },
8 | index: ''
9 | }
10 |
11 | componentDidMount() {
12 | this.fetchValues();
13 | this.fetchIndexes();
14 | }
15 |
16 | async fetchValues () {
17 | const values = await axios.get("/api/values/current");
18 | this.setState({ values: values.data });
19 | }
20 |
21 | async fetchIndexes () {
22 | const seenIndexes = await axios.get("/api/values/all");
23 | this.setState({ seenIndexes: seenIndexes.data });
24 | }
25 |
26 | handleSubmit = async (event) => {
27 | event.preventDefault();
28 |
29 | await axios.post("/api/values", {
30 | index: this.state.index
31 | });
32 | this.setState({ index: '' });
33 | };
34 |
35 | renderSeenIndexes() {
36 | return this.state.seenIndexes.map(({ number }) => number).join(", ");
37 | }
38 |
39 | renderCalculatedValues () {
40 | const entries = [];
41 |
42 | for (let key in this.state.values) {
43 | entries.push(
44 |
45 | Fibonacci of {key} is {this.state.values[key]}
46 |
47 | );
48 | }
49 |
50 | return entries;
51 | }
52 |
53 | render() {
54 | return(
55 |
56 |
64 |
65 |
Seen indexes:
66 | { this.renderSeenIndexes() }
67 |
68 |
Calculated values:
69 | { this.renderCalculatedValues() }
70 |
71 | );
72 | }
73 | };
74 |
75 | export default Fib;
76 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/SecondPage.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Link } from "react-router-dom";
3 |
4 | export default () => {
5 | return (
6 |
7 |
This is a second page!
8 |
Go back ;)
9 |
10 | );
11 | };
12 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
6 | sans-serif;
7 | -webkit-font-smoothing: antialiased;
8 | -moz-osx-font-smoothing: grayscale;
9 | }
10 |
11 | code {
12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
13 | monospace;
14 | }
15 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render( , document.getElementById('root'));
8 |
9 | // If you want your app to work offline and load faster, you can change
10 | // unregister() to register() below. Note this comes with some pitfalls.
11 | // Learn more about service workers: http://bit.ly/CRA-PWA
12 | serviceWorker.unregister();
13 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/fib-calc/client-webapp/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/fib-calc/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3"
2 | services:
3 | postgres:
4 | image: "postgres:latest"
5 |
6 | redis:
7 | image: "redis:latest"
8 |
9 | api:
10 | build:
11 | dockerfile: Dockerfile.dev
12 | context: ./exp-server
13 | volumes:
14 | - /usr/app/node_modules
15 | - ./exp-server:/usr/app
16 | environment:
17 | - REDIS_HOST=redis # name of the service defined above
18 | - REDIS_PORT=6379
19 | - PGUSER=postgres
20 | - PGHOST=postgres # name of the service defined above
21 | - PGDATABASE=postgres
22 | - PGPASSWORD=postgres_password
23 | - PGPORT=5432
24 |
25 | client:
26 | build:
27 | dockerfile: Dockerfile.dev
28 | context: ./client-webapp
29 | volumes:
30 | - /usr/app/node_modules
31 | - ./client-webapp:/usr/app
32 |
33 | worker:
34 | build:
35 | dockerfile: Dockerfile.dev
36 | context: ./worker
37 | volumes:
38 | - /usr/app/node_modules
39 | - ./worker:/usr/app
40 | environment:
41 | - REDIS_HOST=redis
42 | - REDIS_PORT=6379
43 |
44 | nginx:
45 | restart: always
46 | build:
47 | dockerfile: Dockerfile.dev
48 | context: ./nginx
49 | ports:
50 | - "80:80"
51 |
--------------------------------------------------------------------------------
/fib-calc/exp-server/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:alpine
2 | WORKDIR /usr/app
3 |
4 | COPY ./package.json ./
5 | RUN npm install
6 | COPY ./ ./
7 |
8 | CMD ["npm", "run", "start"]
9 |
--------------------------------------------------------------------------------
/fib-calc/exp-server/Dockerfile.dev:
--------------------------------------------------------------------------------
1 | FROM node:alpine
2 | WORKDIR /usr/app
3 |
4 | COPY ./package.json ./
5 | RUN npm install
6 | COPY ./ ./
7 |
8 | CMD ["npm", "run", "dev"]
9 |
--------------------------------------------------------------------------------
/fib-calc/exp-server/index.js:
--------------------------------------------------------------------------------
1 | const keys = require("./keys");
2 |
3 | // Express app setup
4 | const express = require("express");
5 | const bodyParser = require("body-parser");
6 | const cors = require("cors");
7 |
8 | const app = express();
9 | app.use(cors()); // Cross-Origin Resource Sharing
10 | app.use(bodyParser.json());
11 |
12 |
13 | // Postgres client setup
14 | const { Pool } = require("pg");
15 | const pgClient = new Pool({
16 | user: keys.pgUser,
17 | host: keys.pgHost,
18 | database: keys.pgDatabase,
19 | password: keys.pgPassword,
20 | port: keys.pgPort
21 | });
22 | pgClient.on("error", () => console.error("Database connection lost!"));
23 |
24 | pgClient
25 | .query("CREATE TABLE IF NOT EXISTS values (number INT)")
26 | .catch(err => console.error(err));
27 |
28 |
29 | // Redis client setup
30 | const redis = require("redis");
31 | const redisClient = redis.createClient({
32 | host: keys.redisHost,
33 | port: keys.redisPort,
34 | retry_strategy: () => 1000 // if connection is lost, try to reconnect once every 1000 milliseconds
35 | });
36 | const redisPublisher = redisClient.duplicate();
37 |
38 |
39 | /*** Express route handlers ***/
40 |
41 | app.get("/", (req, res) => {
42 | res.send("Express server running");
43 | });
44 |
45 | // Retrieve all values stored in the database (postgres)
46 | app.get("/values/all", async (req, res) => {
47 | const values = await pgClient.query("SELECT * FROM values");
48 |
49 | res.send(values.rows);
50 | });
51 |
52 | // Retrieve all pair of values from redis
53 | app.get("/values/current", async (req, res) => {
54 | redisClient.hgetall("values", (err, values) => {
55 | res.send(values);
56 | });
57 | });
58 |
59 | // Endpoint to submit an index
60 | app.post("/values", async (req, res) => {
61 | const index = parseInt(req.body.index);
62 |
63 | if (index < 0 && index > 40) { // avoid negative and big numbers
64 | return res.status(422).send("Index out of bounds");
65 | }
66 |
67 | // store the index
68 | redisClient.hset("values", index, "Nothing yet...");
69 | redisPublisher.publish("insert", index);
70 | pgClient.query("INSERT INTO values(number) VALUES ($1)", [index]);
71 |
72 | res.send({ status: "working" });
73 | });
74 |
75 | // start listening
76 | app.listen(5000, err => {
77 | console.log("Express server up and listening...");
78 | })
79 |
--------------------------------------------------------------------------------
/fib-calc/exp-server/keys.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | redisHost: process.env.REDIS_HOST,
3 | redisPort: process.env.REDIS_PORT,
4 | pgUser: process.env.PGUSER,
5 | pgHost: process.env.PGHOST,
6 | pgDatabase: process.env.PGDATABASE,
7 | pgPassword: process.env.PGPASSWORD,
8 | pgPort: process.env.PGPORT
9 | };
10 |
--------------------------------------------------------------------------------
/fib-calc/exp-server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "express": "4.16.3",
4 | "pg": "7.4.3",
5 | "redis": ">=3.1.1",
6 | "cors": "2.8.4",
7 | "nodemon": "1.18.3",
8 | "body-parser": "*"
9 | },
10 | "scripts" : {
11 | "start": "node index.js",
12 | "dev": "nodemon"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/fib-calc/nginx/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM nginx
2 | COPY ./default.conf /etc/nginx/conf.d/default.conf
3 |
--------------------------------------------------------------------------------
/fib-calc/nginx/Dockerfile.dev:
--------------------------------------------------------------------------------
1 | FROM nginx
2 | COPY ./default.conf /etc/nginx/conf.d/default.conf
3 |
--------------------------------------------------------------------------------
/fib-calc/nginx/default.conf:
--------------------------------------------------------------------------------
1 | upstream client {
2 | server client:3000;
3 | }
4 |
5 | upstream api {
6 | server api:5000;
7 | }
8 |
9 | server {
10 | listen 80;
11 |
12 | location / {
13 | proxy_pass http://client;
14 | }
15 |
16 | location /sockjs-node {
17 | proxy_pass http://client;
18 | proxy_http_version 1.1;
19 | proxy_set_header Upgrade $http_upgrade;
20 | proxy_set_header Connection "Upgrade";
21 | }
22 |
23 | location /api {
24 | rewrite /api/(.*) /$1 break;
25 | proxy_pass http://api;
26 | }
27 | }
--------------------------------------------------------------------------------
/fib-calc/worker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:alpine
2 | WORKDIR /usr/app
3 |
4 | COPY ./package.json ./
5 | RUN npm install
6 | COPY ./ ./
7 |
8 | CMD ["npm", "run", "start"]
9 |
--------------------------------------------------------------------------------
/fib-calc/worker/Dockerfile.dev:
--------------------------------------------------------------------------------
1 | FROM node:alpine
2 | WORKDIR /usr/app
3 |
4 | COPY ./package.json ./
5 | RUN npm install
6 | COPY ./ ./
7 |
8 | CMD ["npm", "run", "dev"]
9 |
--------------------------------------------------------------------------------
/fib-calc/worker/index.js:
--------------------------------------------------------------------------------
1 | const keys = require("./keys");
2 | const redis = require("redis");
3 |
4 | // create a redis client
5 | const redisClient = redis.createClient({
6 | host: keys.redisHost,
7 | port: keys.redisPort,
8 | retry_strategy: () => 1000
9 | });
10 |
11 | // Fibonacci classic implementation
12 | function fib (i) {
13 | return i < 2 ? 1 : fib(i - 1) + fib(i - 2);
14 | }
15 |
16 | // duplicate the redis client
17 | const sub = redisClient.duplicate();
18 |
19 | // subscription on new message (index)
20 | sub.on("message", (channel, message) => {
21 | // calculate the fibonacci value and insert into a hash of values
22 | redisClient.hset("values", message, fib(parseInt(message)));
23 | });
24 | sub.subscribe("insert");
25 |
26 |
--------------------------------------------------------------------------------
/fib-calc/worker/keys.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | redisHost: process.env.REDIS_HOST,
3 | redisPort: process.env.REDIS_PORT
4 | };
5 |
--------------------------------------------------------------------------------
/fib-calc/worker/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "nodemon": "1.18.3",
4 | "redis": ">=3.1.1"
5 | },
6 | "scripts" : {
7 | "start": "node index.js",
8 | "dev": "nodemon"
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/react-app/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/react-app/Dockerfile:
--------------------------------------------------------------------------------
1 | # build phase
2 | FROM node:alpine as builder
3 | WORKDIR /usr/app
4 | COPY package.json .
5 | RUN npm install
6 | COPY . .
7 | RUN npm run build
8 |
9 | # run phase (automatically starts the server)
10 | FROM nginx
11 | COPY --from=builder /usr/app/build /usr/share/nginx/html
12 |
13 | # run using:
14 | # docker run -p 8080:80
15 | # Nginx uses port 80 by default
16 |
--------------------------------------------------------------------------------
/react-app/Dockerfile.dev:
--------------------------------------------------------------------------------
1 | FROM node:alpine
2 |
3 | WORKDIR /usr/app
4 |
5 | COPY package.json .
6 | RUN npm install
7 | COPY . .
8 |
9 | CMD ["npm", "run", "start"]
10 |
11 | # Commands to use:
12 | #
13 | # Build from a file
14 | # docker build -f Dockerfile.dev .
15 | #
16 | # Map the ports (local:remote), use the remote volume for node_modules (do not try to map/reference)
17 | # and map/reference the other directories/files
18 | # docker run -p 3000:3000 -v /usr/app/node_modules -v $(pwd):/usr/app 81275fec7a56
19 | #
20 | # or use docker-compose instead :)
21 |
--------------------------------------------------------------------------------
/react-app/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `npm start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `npm test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `npm run build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `npm run eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
35 |
36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
37 |
38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
--------------------------------------------------------------------------------
/react-app/docker-compose.yml:
--------------------------------------------------------------------------------
1 | # version of docker compose
2 | version: "3"
3 |
4 | # services to include
5 | services:
6 | react-webapp:
7 | build:
8 | context: .
9 | dockerfile: Dockerfile.dev
10 | ports:
11 | - "3000:3000"
12 | volumes:
13 | - /usr/app/node_modules
14 | - .:/usr/app
15 |
--------------------------------------------------------------------------------
/react-app/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-frontend",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "react": "^16.6.3",
7 | "react-dom": "^16.6.3",
8 | "react-scripts": "2.1.1"
9 | },
10 | "scripts": {
11 | "start": "react-scripts start",
12 | "build": "react-scripts build",
13 | "test": "react-scripts test",
14 | "eject": "react-scripts eject"
15 | },
16 | "eslintConfig": {
17 | "extends": "react-app"
18 | },
19 | "browserslist": [
20 | ">0.2%",
21 | "not dead",
22 | "not ie <= 11",
23 | "not op_mini all"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/react-app/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/manasesjesus/docker-and-kubernetes/326155025c471bc6d05ed98f88ccc2ab1d0fd596/react-app/public/favicon.ico
--------------------------------------------------------------------------------
/react-app/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
26 | You need to enable JavaScript to run this app.
27 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/react-app/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/react-app/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 40vmin;
8 | }
9 |
10 | .App-header {
11 | background-color: #282c34;
12 | min-height: 100vh;
13 | display: flex;
14 | flex-direction: column;
15 | align-items: center;
16 | justify-content: center;
17 | font-size: calc(10px + 2vmin);
18 | color: white;
19 | }
20 |
21 | .App-link {
22 | color: #61dafb;
23 | }
24 |
25 | @keyframes App-logo-spin {
26 | from {
27 | transform: rotate(0deg);
28 | }
29 | to {
30 | transform: rotate(360deg);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/react-app/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import logo from './logo.svg';
3 | import './App.css';
4 |
5 | class App extends Component {
6 | render() {
7 | return (
8 |
25 | );
26 | }
27 | }
28 |
29 | export default App;
30 |
--------------------------------------------------------------------------------
/react-app/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render( , div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/react-app/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
6 | sans-serif;
7 | -webkit-font-smoothing: antialiased;
8 | -moz-osx-font-smoothing: grayscale;
9 | }
10 |
11 | code {
12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
13 | monospace;
14 | }
15 |
--------------------------------------------------------------------------------
/react-app/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render( , document.getElementById('root'));
8 |
9 | // If you want your app to work offline and load faster, you can change
10 | // unregister() to register() below. Note this comes with some pitfalls.
11 | // Learn more about service workers: http://bit.ly/CRA-PWA
12 | serviceWorker.unregister();
13 |
--------------------------------------------------------------------------------
/react-app/src/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/react-app/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/redis-image/Dockerfile:
--------------------------------------------------------------------------------
1 | # Use an existing user image as a base
2 | FROM alpine
3 |
4 | # Download and install a dependency
5 | RUN apk add --update redis
6 | RUN apk add --update gcc
7 |
8 | # Tell the image what to do when it starts as a container
9 | CMD [ "redis-server" ]
10 |
--------------------------------------------------------------------------------
/visits-counter/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:alpine
2 |
3 | WORKDIR /usr/app
4 |
5 | COPY package.json .
6 | RUN npm install
7 | COPY . .
8 |
9 | CMD [ "npm", "start" ]
10 |
--------------------------------------------------------------------------------
/visits-counter/app.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const redis = require("redis");
3 | const process = require("process");
4 |
5 | const app = express();
6 | const client = redis.createClient({
7 | host: "redis-server", // specified in the docker-compose.yml
8 | port: 6379 // default redis port
9 | });
10 |
11 | // Initialize the number of visits
12 | client.set("visits", 0);
13 |
14 | // Increase and store the number of visits
15 | app.get("/", (req, res) => {
16 | client.get("visits", (err, visits) => {
17 | let total_visits = parseInt(visits) + 1;
18 |
19 | client.set("visits", total_visits);
20 | res.send("This page has been visited " + total_visits + " times!");
21 |
22 | // Aborting... docker will restart the container as specified in the yml file
23 | if (total_visits > 5) {
24 | process.exit(0);
25 | }
26 | });
27 | });
28 |
29 | // Start the server
30 | app.listen(8080, () => {
31 | console.log("Listening on port 8080");
32 | });
33 |
--------------------------------------------------------------------------------
/visits-counter/docker-compose.yml:
--------------------------------------------------------------------------------
1 | # version of docker compose
2 | version: "3"
3 |
4 | # services to include
5 | services:
6 | redis-server:
7 | image: "redis"
8 | node-app:
9 | restart: always
10 | build: .
11 | ports:
12 | - "80:8080"
13 |
14 | # port on local: 80
15 | # port on node server: 8080
16 |
17 | # docker compose creates the two containers (redis, node)
18 | # both have free access to each other and can exchange
19 | # as much information as they need
20 |
--------------------------------------------------------------------------------
/visits-counter/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "express": "*",
4 | "redis": ">=3.1.1"
5 | },
6 | "scripts": {
7 | "start": "node app.js"
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/webapp/Dockerfile:
--------------------------------------------------------------------------------
1 | # Specify a base image
2 | FROM node:alpine
3 |
4 | # Specify working directory
5 | WORKDIR /usr/app
6 |
7 | # Install dependencies and copy resources
8 | COPY ./package.json ./
9 | RUN npm install
10 | COPY ./ ./
11 |
12 | # Default command
13 | CMD ["npm", "start"]
14 |
15 |
16 |
17 | # Terminal commands
18 |
19 | # Build and tag the image
20 | # docker build -t mj/webapp .
21 |
22 | # Run the container with port forwarding
23 | # docker run -p 5000:8080 mj/webapp
24 |
--------------------------------------------------------------------------------
/webapp/app.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const app = express();
3 |
4 | app.get("/", (req, res) => {
5 | res.send("Hello there, hooman!");
6 | });
7 |
8 | app.listen(8080, () => {
9 | console.log("Listening on port 8080");
10 | });
11 |
--------------------------------------------------------------------------------
/webapp/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "express": "*"
4 | },
5 | "scripts": {
6 | "start": "node app.js"
7 | }
8 | }
--------------------------------------------------------------------------------