From e5a780b6c059fc5b4d28edcfe870d87b6d5e27e0 Mon Sep 17 00:00:00 2001 From: buildmaster Date: Thu, 28 Feb 2019 16:52:04 +0000 Subject: [PATCH] Sync docs from master to gh-pages --- multi/multi__contributing.html | 2 +- ...multi__discoveryclient_for_kubernetes.html | 17 +- multi/multi__examples.html | 6 +- ...multi__kubernetes_ecosystem_awareness.html | 22 +- ...__kubernetes_native_service_discovery.html | 2 +- ...rnetes_propertysource_implementations.html | 149 +++-- multi/multi__leader_election.html | 2 +- multi/multi__other_resources.html | 2 +- multi/multi__pod_health_indicator.html | 4 +- ...multi__ribbon_discovery_in_kubernetes.html | 27 +- ...rity_configurations_inside_kubernetes.html | 14 +- multi/multi__starters.html | 6 +- ...y_do_you_need_spring_cloud_kubernetes.html | 4 +- multi/multi_pr01.html | 3 + multi/multi_spring-cloud-kubernetes.html | 2 +- single/spring-cloud-kubernetes.html | 241 ++++---- spring-cloud-kubernetes.xml | 547 ++++++++++-------- 17 files changed, 563 insertions(+), 487 deletions(-) create mode 100644 multi/multi_pr01.html diff --git a/multi/multi__contributing.html b/multi/multi__contributing.html index 95d743a7..45650415 100644 --- a/multi/multi__contributing.html +++ b/multi/multi__contributing.html @@ -84,4 +84,4 @@ $ touch .springformat
4       └── Intellij_Spring_Boot_Java_Conventions.xml 5

-

3

Default Checkstyle rules

2

File header setup

1

Default suppression rules

4

Project defaults for Intellij that apply most of Checkstyle rules

5

Project style conventions for Intellij that apply most of Checkstyle rules

Figure 14.1. Code style

Code style

Go to FileSettingsEditorCode style. There click on the icon next to the Scheme section. There, click on the Import Scheme value and pick the Intellij IDEA code style XML option. Import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml file.

Figure 14.2. Inspection profiles

Code style

Go to FileSettingsEditorInspections. There click on the icon next to the Profile section. There, click on the Import Profile and import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml file.

Checkstyle. To have Intellij work with Checkstyle, you have to install the Checkstyle plugin. It’s advisable to also install the Assertions2Assertj to automatically convert the JUnit assertions

Checkstyle

Go to FileSettingsOther settingsCheckstyle. There click on the + icon in the Configuration file section. There, you’ll have to define where the checkstyle rules should be picked from. In the image above, we’ve picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build’s GitHub repository (e.g. for the checkstyle.xml : https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml). We need to provide the following variables:

[Important]Important

Remember to set the Scan Scope to All sources since we apply checkstyle rules for production and test sources.

\ No newline at end of file +

3

Default Checkstyle rules

2

File header setup

1

Default suppression rules

4

Project defaults for Intellij that apply most of Checkstyle rules

5

Project style conventions for Intellij that apply most of Checkstyle rules

Figure 14.1. Code style

Code style

Go to FileSettingsEditorCode style. There click on the icon next to the Scheme section. There, click on the Import Scheme value and pick the Intellij IDEA code style XML option. Import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml file.

Figure 14.2. Inspection profiles

Code style

Go to FileSettingsEditorInspections. There click on the icon next to the Profile section. There, click on the Import Profile and import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml file.

Checkstyle. To have Intellij work with Checkstyle, you have to install the Checkstyle plugin. It’s advisable to also install the Assertions2Assertj to automatically convert the JUnit assertions

Checkstyle

Go to FileSettingsOther settingsCheckstyle. There click on the + icon in the Configuration file section. There, you’ll have to define where the checkstyle rules should be picked from. In the image above, we’ve picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build’s GitHub repository (e.g. for the checkstyle.xml : https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml). We need to provide the following variables:

[Important]Important

Remember to set the Scan Scope to All sources since we apply checkstyle rules for production and test sources.

\ No newline at end of file diff --git a/multi/multi__discoveryclient_for_kubernetes.html b/multi/multi__discoveryclient_for_kubernetes.html index f304be4c..b050f202 100644 --- a/multi/multi__discoveryclient_for_kubernetes.html +++ b/multi/multi__discoveryclient_for_kubernetes.html @@ -1,16 +1,19 @@ 3. DiscoveryClient for Kubernetes

3. DiscoveryClient for Kubernetes

This project provides an implementation of Discovery Client -for Kubernetes. -This allows you to query Kubernetes endpoints (see services) by name. -A service is typically exposed by the Kubernetes API server as a collection of endpoints which represent http, https addresses that a client can +for Kubernetes. +This client lets you query Kubernetes endpoints (see services) by name. +A service is typically exposed by the Kubernetes API server as a collection of endpoints that represent http and https addresses and that a client can access from a Spring Boot application running as a pod. This discovery feature is also used by the Spring Cloud Kubernetes Ribbon project -to fetch the list of the endpoints defined for an application to be load balanced.

To enable loading of the DiscoveryClient, add @EnableDiscoveryClient to the according configuration or application class like this:

@SpringBootApplication
+to fetch the list of the endpoints defined for an application to be load balanced.

This is something that you get for free by adding the following dependency inside your project:

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-starter-kubernetes</artifactId>
+</dependency>

To enable loading of the DiscoveryClient, add @EnableDiscoveryClient to the according configuration or application class, as the following example shows:

@SpringBootApplication
 @EnableDiscoveryClient
 public class Application {
   public static void main(String[] args) {
     SpringApplication.run(Application.class, args);
   }
-}

Then you can inject the client in your code simply by:

@Autowired
-private DiscoveryClient discoveryClient;

If for any reason you need to disable the DiscoveryClient you can simply set the following property in application.properties:

spring.cloud.kubernetes.discovery.enabled=false

Some Spring Cloud components use the DiscoveryClient in order to obtain info about the local service instance. For -this to work you need to align the Kubernetes service name with the spring.application.name property.

\ No newline at end of file +}

Then you can inject the client in your code simply by autowiring it, as the following example shows:

@Autowired
+private DiscoveryClient discoveryClient;

If, for any reason, you need to disable the DiscoveryClient, you can set the following property in application.properties:

spring.cloud.kubernetes.discovery.enabled=false

Some Spring Cloud components use the DiscoveryClient in order to obtain information about the local service instance. For +this to work, you need to align the Kubernetes service name with the spring.application.name property.

\ No newline at end of file diff --git a/multi/multi__examples.html b/multi/multi__examples.html index 9fde54e2..e23fce1c 100644 --- a/multi/multi__examples.html +++ b/multi/multi__examples.html @@ -1,5 +1,5 @@ - 11. Examples

11. Examples

Spring Cloud Kubernetes tries to make it transparent for your applications to consume Kubernetes Native Services -following the Spring Cloud interfaces.

In your applications, you need to add the spring-cloud-kubernetes-discovery dependency to your classpath and remove any other dependency that contains a DiscoveryClient implementation (ie. Eureka Discovery Client). -The same applies for PropertySourceLocator, where you need to add to the classpath the spring-cloud-kubernetes-config and remove any other dependency that contains a PropertySourceLocator implementation (ie. Config Server Client).

The following projects highlight the usage of these dependencies and demonstrate how these libraries can be used from any Spring Boot application.

List of examples using these projects:

\ No newline at end of file + 11. Examples

11. Examples

Spring Cloud Kubernetes tries to make it transparent for your applications to consume Kubernetes Native Services by +following the Spring Cloud interfaces.

In your applications, you need to add the spring-cloud-kubernetes-discovery dependency to your classpath and remove any other dependency that contains a DiscoveryClient implementation (that is, a Eureka discovery client). +The same applies for PropertySourceLocator, where you need to add to the classpath the spring-cloud-kubernetes-config and remove any other dependency that contains a PropertySourceLocator implementation (that is, a configuration server client).

The following projects highlight the usage of these dependencies and demonstrate how you can use these libraries from any Spring Boot application:

\ No newline at end of file diff --git a/multi/multi__kubernetes_ecosystem_awareness.html b/multi/multi__kubernetes_ecosystem_awareness.html index 6cb73868..73415cd9 100644 --- a/multi/multi__kubernetes_ecosystem_awareness.html +++ b/multi/multi__kubernetes_ecosystem_awareness.html @@ -1,14 +1,14 @@ - 7. Kubernetes Ecosystem Awareness

7. Kubernetes Ecosystem Awareness

All of the features described above will work equally well regardless of whether your application is running inside -Kubernetes or not. This is really helpful for development and troubleshooting. -From a development point of view, this is really helpful as you can start your Spring Boot application and debug one -of the modules part of this project. It is not required to deploy it in Kubernetes + 7. Kubernetes Ecosystem Awareness

7. Kubernetes Ecosystem Awareness

All of the features described earlier in this guide work equally well, regardless of whether your application is running inside +Kubernetes. This is really helpful for development and troubleshooting. +From a development point of view, this lets you start your Spring Boot application and debug one +of the modules that is part of this project. You need not deploy it in Kubernetes, as the code of the project relies on the -Fabric8 Kubernetes Java client which is a fluent DSL able to -communicate using http protocol to the REST API of Kubernetes Server.

7.1 Kubernetes Profile Autoconfiguration

When the application runs as a pod inside Kubernetes a Spring profile named kubernetes will automatically get activated. -This allows the developer to customize the configuration, to define beans that will be applied when the Spring Boot application is deployed -within the Kubernetes platform (e.g. different dev and prod configuration).

7.2 Istio Awareness

When including the spring-cloud-kubernetes-istio module into the application classpath a new profile will be added to the application, -if the application is running inside a Kubernetes Cluster with Istio installed. Then you can use -spring @Profile("istio") annotations into your Beans and @Configuration's.

The Istio awareness module uses the me.snowdrop:istio-client to interact with Istio APIs enabling us to discover traffic rules, circuit breakers, etc. -Making it easy for our Spring Boot applications to consume this data to dynamically configure themselves according the environment.

\ No newline at end of file +Fabric8 Kubernetes Java client, which is a fluent DSL that can +communicate by using http protocol to the REST API of the Kubernetes Server.

7.1 Kubernetes Profile Autoconfiguration

When the application runs as a pod inside Kubernetes, a Spring profile named kubernetes automatically gets activated. +This lets you customize the configuration, to define beans that are applied when the Spring Boot application is deployed +within the Kubernetes platform (for example, different development and production configuration).

7.2 Istio Awareness

When you include the spring-cloud-kubernetes-istio module in the application classpath, a new profile is added to the application, +provided the application is running inside a Kubernetes Cluster with Istio installed. You can then use +spring @Profile("istio") annotations in your Beans and @Configuration classes.

The Istio awareness module uses me.snowdrop:istio-client to interact with Istio APIs, letting us discover traffic rules, circuit breakers, and so on, +making it easy for our Spring Boot applications to consume this data to dynamically configure themselves according to the environment.

\ No newline at end of file diff --git a/multi/multi__kubernetes_native_service_discovery.html b/multi/multi__kubernetes_native_service_discovery.html index 4b1954bf..6896747a 100644 --- a/multi/multi__kubernetes_native_service_discovery.html +++ b/multi/multi__kubernetes_native_service_discovery.html @@ -1,4 +1,4 @@ 4. Kubernetes native service discovery

4. Kubernetes native service discovery

Kubernetes itself is capable of (server side) service discovery (see: https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services). -Using native kubernetes service discovery ensures compatibility with additional tooling, like: istio https://istio.io (service mesh, capable of load balancing, ribbon, circuit breaker, failover and much more).

The caller service just needs to refer to names resolvable in particular kubernetes cluster then. Simplest implementation might use the spring RestTemplate referring to fully qualified domain name (FQDN) http://{service-name}.{namespace}.svc.{cluster}.local:{service-port}.

Additionally, hystrix can be used for:

  • circuit breaker implementation on the caller side, just by annotating the spring boot application class: @EnableCircuitBreaker
  • and for the fallback functionality, annotating the respective method via: @HystrixCommand(fallbackMethod= does the job.
\ No newline at end of file +Using native kubernetes service discovery ensures compatibility with additional tooling, such as Istio (https://istio.io), a service mesh that is capable of load balancing, ribbon, circuit breaker, failover, and much more.

The caller service then need only refer to names resolvable in a particular Kubernetes cluster. A simple implementation might use a spring RestTemplate that refers to a fully qualified domain name (FQDN), such as https://{service-name}.{namespace}.svc.{cluster}.local:{service-port}.

Additionally, you can use Hystrix for:

\ No newline at end of file diff --git a/multi/multi__kubernetes_propertysource_implementations.html b/multi/multi__kubernetes_propertysource_implementations.html index fd38a7c5..781073f5 100644 --- a/multi/multi__kubernetes_propertysource_implementations.html +++ b/multi/multi__kubernetes_propertysource_implementations.html @@ -1,17 +1,17 @@ - 5. Kubernetes PropertySource implementations

5. Kubernetes PropertySource implementations

The most common approach to configure your Spring Boot application is to create an application.properties|yaml or -an application-profile.properties|yaml file containing key-value pairs providing customization values to your -application or Spring Boot starters. Users may override these properties by specifying system properties or environment -variables.

5.1 ConfigMap PropertySource

Kubernetes provides a resource named ConfigMap to externalize the -parameters to pass to your application in the form of key-value pairs or embedded application.properties|yaml files. -The Spring Cloud Kubernetes Config project makes Kubernetes `ConfigMap`s available + 5. Kubernetes PropertySource implementations

5. Kubernetes PropertySource implementations

The most common approach to configuring your Spring Boot application is to create an application.properties or applicaiton.yaml or +an application-profile.properties or application-profile.yaml file that contains key-value pairs that provide customization values to your +application or Spring Boot starters. You can override these properties by specifying system properties or environment +variables.

5.1 Using a ConfigMap PropertySource

Kubernetes provides a resource named ConfigMap to externalize the +parameters to pass to your application in the form of key-value pairs or embedded application.properties or application.yaml files. +The Spring Cloud Kubernetes Config project makes Kubernetes ConfigMap instances available during application bootstrapping and triggers hot reloading of beans or Spring context when changes are detected on -observed `ConfigMap`s.

The default behavior is to create a ConfigMapPropertySource based on a Kubernetes ConfigMap which has metadata.name of either the name of +observed ConfigMap instances.

The default behavior is to create a ConfigMapPropertySource based on a Kubernetes ConfigMap that has a metadata.name value of either the name of your Spring application (as defined by its spring.application.name property) or a custom name defined within the -bootstrap.properties file under the following key spring.cloud.kubernetes.config.name.

However, more advanced configuration are possible where multiple ConfigMaps can be used -This is made possible by the spring.cloud.kubernetes.config.sources list. -For example one could define the following ConfigMaps

spring:
+bootstrap.properties file under the following key: spring.cloud.kubernetes.config.name.

However, more advanced configuration is possible where you can use multiple ConfigMap instances. +The spring.cloud.kubernetes.config.sources list makes this possible. +For example, you could define the following ConfigMap instances:

spring:
   application:
     name: cloud-k8s-app
   cloud:
@@ -20,25 +20,25 @@ For example one could define the following ConfigMaps

        name: default-name
         namespace: default-namespace
         sources:
-         # Spring Cloud Kubernetes will lookup a ConfigMap named c1 in namespace default-namespace
+         # Spring Cloud Kubernetes looks up a ConfigMap named c1 in namespace default-namespace
          - name: c1
-         # Spring Cloud Kubernetes will lookup a ConfigMap named default-name in whatever namespace n2
+         # Spring Cloud Kubernetes looks up a ConfigMap named default-name in whatever namespace n2
          - namespace: n2
-         # Spring Cloud Kubernetes will lookup a ConfigMap named c3 in namespace n3
+         # Spring Cloud Kubernetes looks up a ConfigMap named c3 in namespace n3
          - namespace: n3
-           name: c3

In the example above, it spring.cloud.kubernetes.config.namespace had not been set, -then the ConfigMap named c1 would be looked up in the namespace that the application runs

Any matching ConfigMap that is found, will be processed as follows:

  • apply individual configuration properties.
  • apply as yaml the content of any property named application.yaml
  • apply as properties file the content of any property named application.properties

The single exception to the aforementioned flow is when the ConfigMap contains a single key that indicates -the file is a YAML or Properties file. In that case the name of the key does NOT have to be application.yaml or -application.properties (it can be anything) and the value of the property will be treated correctly. -This features facilitates the use case where the ConfigMap was created using something like:

kubectl create configmap game-config --from-file=/path/to/app-config.yaml

Example:

Let’s assume that we have a Spring Boot application named demo that uses properties to read its thread pool -configuration.

  • pool.size.core
  • pool.size.maximum

This can be externalized to config map in yaml format:

kind: ConfigMap
+           name: c3

In the preceding example, if spring.cloud.kubernetes.config.namespace had not been set, +the ConfigMap named c1 would be looked up in the namespace that the application runs.

Any matching ConfigMap that is found is processed as follows:

  • Apply individual configuration properties.
  • Apply as yaml the content of any property named application.yaml.
  • Apply as a properties file the content of any property named application.properties.

The single exception to the aforementioned flow is when the ConfigMap contains a single key that indicates +the file is a YAML or properties file. In that case, the name of the key does NOT have to be application.yaml or +application.properties (it can be anything) and the value of the property is treated correctly. +This features facilitates the use case where the ConfigMap was created by using something like the following:

kubectl create configmap game-config --from-file=/path/to/app-config.yaml

Assume that we have a Spring Boot application named demo that uses the following properties to read its thread pool +configuration.

  • pool.size.core
  • pool.size.maximum

This can be externalized to config map in yaml format as follows:

kind: ConfigMap
 apiVersion: v1
 metadata:
   name: demo
 data:
   pool.size.core: 1
-  pool.size.max: 16

Individual properties work fine for most cases but sometimes embedded yaml is more convenient. In this case we will -use a single property named application.yaml to embed our yaml:

kind: ConfigMap
+  pool.size.max: 16

Individual properties work fine for most cases. However, sometimes, embedded yaml is more convenient. In this case, we +use a single property named application.yaml to embed our yaml, as follows:

kind: ConfigMap
 apiVersion: v1
 metadata:
   name: demo
@@ -47,7 +47,7 @@ use a single property named application.yaml to emb
     pool:
       size:
         core: 1
-        max:16

The following also works:

kind: ConfigMap
+        max:16

The following example also works:

kind: ConfigMap
 apiVersion: v1
 metadata:
   name: demo
@@ -56,10 +56,10 @@ use a single property named application.yaml to emb
     pool:
       size:
         core: 1
-        max:16

Spring Boot applications can also be configured differently depending on active profiles which will be merged together -when the ConfigMap is read. It is possible to provide different property values for different profiles using an -application.properties|yaml property, specifying profile-specific values each in their own document -(indicated by the --- sequence) as follows:

kind: ConfigMap
+        max:16

You can also configure Spring Boot applications differently depending on active profiles that are merged together +when the ConfigMap is read. You can provide different property values for different profiles by using an +application.properties or application.yaml property, specifying profile-specific values, each in their own document +(indicated by the --- sequence), as follows:

kind: ConfigMap
 apiVersion: v1
 metadata:
   name: demo
@@ -80,15 +80,15 @@ when the ConfigMap is read. It is possible to provide different property values
     spring:
       profiles: production
     greeting:
-      message: Say Hello to the Ops

In the above case, the configuration loaded into your Spring Application with the development profile will be:

  greeting:
+      message: Say Hello to the Ops

In the preceding case, the configuration loaded into your Spring Application with the development profile is as follows:

  greeting:
     message: Say Hello to the Developers
   farewell:
-    message: Say Goodbye to the Developers

whereas if the production profile is active, the configuration will be:

  greeting:
+    message: Say Goodbye to the Developers

However, if the production profile is active, the configuration becomes:

  greeting:
     message: Say Hello to the Ops
   farewell:
-    message: Say Goodbye

If both profiles are active, the property which appears last within the configmap will overwrite preceding values.

To tell to Spring Boot which profile should be enabled at bootstrap, a system property can be passed to the Java -command launching your Spring Boot application using an env variable that you will define with the OpenShift -DeploymentConfig or Kubernetes ReplicationConfig resource file as follows:

apiVersion: v1
+    message: Say Goodbye

If both profiles are active, the property that appears last within the ConfigMap overwrites any preceding values.

To tell Spring Boot which profile should be enabled at bootstrap, you can pass a system property to the Java +command. To do so, you can launch your Spring Boot application with an environment variable that you can define with the OpenShift +DeploymentConfig or Kubernetes ReplicationConfig resource file, as follows:

apiVersion: v1
 kind: DeploymentConfig
 spec:
   replicas: 1
@@ -99,20 +99,18 @@ command launching your Spring Boot application using an env variable that you wi
         - name: JAVA_APP_DIR
           value: /deployments
         - name: JAVA_OPTIONS
-          value: -Dspring.profiles.active=developer

Notes: -- check the security configuration section, to access config maps from inside a pod you need to have the correct -Kubernetes service accounts, roles and role bindings.

Another option for using ConfigMaps, is to mount them into the Pod running the Spring Cloud Kubernetes application -and have Spring Cloud Kubernetes read them from the file system. -This behavior is controlled by the spring.cloud.kubernetes.config.paths property and can be used in + value: -Dspring.profiles.active=developer

[Note]Note

You should check the security configuration section. To access config maps from inside a pod you need to have the correct +Kubernetes service accounts, roles and role bindings.

Another option for using ConfigMap instances is to mount them into the Pod by running the Spring Cloud Kubernetes application +and having Spring Cloud Kubernetes read them from the file system. +This behavior is controlled by the spring.cloud.kubernetes.config.paths property. You can use it in addition to or instead of the mechanism described earlier. -Multiple (exact) file paths can be specified in spring.cloud.kubernetes.config.paths by using the , delimiter

Notes: -You have to provide full exact path to each property file, because directories are not being recursively parsed.

Table 5.1. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.config.enableApi

Boolean

true

Enable/Disable consuming ConfigMaps via APIs

spring.cloud.kubernetes.config.enabled

Boolean

true

Enable Secrets PropertySource

spring.cloud.kubernetes.config.name

String

${spring.application.name}

Sets the name of ConfigMap to lookup

spring.cloud.kubernetes.config.namespace

String

Client namespace

Sets the Kubernetes namespace where to lookup

spring.cloud.kubernetes.config.paths

List

null

Sets the paths where ConfigMaps are mounted


5.2 Secrets PropertySource

Kubernetes has the notion of Secrets for storing -sensitive data such as password, OAuth tokens, etc. This project provides integration with Secrets to make secrets -accessible by Spring Boot applications. This feature can be explicitly enabled/disabled using the spring.cloud.kubernetes.secrets.enabled property.

The SecretsPropertySource when enabled will lookup Kubernetes for Secrets from the following sources:

  1. reading recursively from secrets mounts
  2. named after the application (as defined by spring.application.name)
  3. matching some labels

Please note that by default, consuming Secrets via API (points 2 and 3 above) is not enabled for security reasons -and it is recommended that containers share secrets via mounted volumes. -If you enable consuming Secrets via API, then it is recommended access to Secrets is limited by an -[authorization policy such as RBAC](https://kubernetes.io/docs/concepts/configuration/secret/#best-practices).

If the secrets are found their data is made available to the application.

Example:

Let’s assume that we have a spring boot application named demo that uses properties to read its database -configuration. We can create a Kubernetes secret using the following command:

oc create secret generic db-secret --from-literal=username=user --from-literal=password=p455w0rd

This would create the following secret (shown using oc get secrets db-secret -o yaml):

apiVersion: v1
+You can specify multiple (exact) file paths in spring.cloud.kubernetes.config.paths by using the , delimiter.

[Note]Note

You have to provide the full exact path to each property file, because directories are not being recursively parsed.

Table 5.1. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.config.enableApi

Boolean

true

Enable or disable consuming ConfigMap instances through APIs

spring.cloud.kubernetes.config.enabled

Boolean

true

Enable Secrets PropertySource

spring.cloud.kubernetes.config.name

String

${spring.application.name}

Sets the name of ConfigMap to look up

spring.cloud.kubernetes.config.namespace

String

Client namespace

Sets the Kubernetes namespace where to lookup

spring.cloud.kubernetes.config.paths

List

null

Sets the paths where ConfigMap instances are mounted


5.2 Secrets PropertySource

Kubernetes has the notion of Secrets for storing +sensitive data such as passwords, OAuth tokens, and so on. This project provides integration with Secrets to make secrets +accessible by Spring Boot applications. You can explicitly enable or disable This feature by setting the spring.cloud.kubernetes.secrets.enabled property.

When enabled, the SecretsPropertySource looks up Kubernetes for Secrets from the following sources:

  1. Reading recursively from secrets mounts
  2. Named after the application (as defined by spring.application.name)
  3. Matching some labels

Note that, by default, consuming Secrets through the API (points 2 and 3 above) is not enabled for security reasons. +Further, we recommend that containers share secrets through mounted volumes. +If you enable consuming Secrets through the API, we recommend that you limit access to Secrets by using an +[authorization policy, such as RBAC](https://kubernetes.io/docs/concepts/configuration/secret/#best-practices).

If the secrets are found, their data is made available to the application.

Assume that we have a spring boot application named demo that uses properties to read its database +configuration. We can create a Kubernetes secret by using the following command:

oc create secret generic db-secret --from-literal=username=user --from-literal=password=p455w0rd

The preceding command would create the following secret (which you can see by using oc get secrets db-secret -o yaml):

apiVersion: v1
 data:
   password: cDQ1NXcwcmQ=
   username: dXNlcg==
@@ -124,7 +122,7 @@ configuration. We can create a Kubernetes secret using the following command:

resourceVersion: "357496" selfLink: /api/v1/namespaces/default/secrets/db-secret uid: 63c89263-6099-11e7-b3da-76d6186905a8 -type: Opaque

Note that the data contains Base64-encoded versions of the literal provided by the create command.

This secret can then be used by your application for example by exporting the secret’s value as environment variables:

apiVersion: v1
+type: Opaque

Note that the data contains Base64-encoded versions of the literal provided by the create command.

Your application can then use this secret — for example, by exporting the secret’s value as environment variables:

apiVersion: v1
 kind: Deployment
 metadata:
   name: ${project.artifactId}
@@ -142,31 +140,30 @@ configuration. We can create a Kubernetes secret using the following command:

valueFrom: secretKeyRef: name: db-secret - key: password

You can select the Secrets to consume in a number of ways:

  1. By listing the directories where secrets are mapped:

    -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets/db-secret,etc/secrets/postgresql

    If you have all the secrets mapped to a common root, you can set them like:

    -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets
  2. By setting a named secret:

    -Dspring.cloud.kubernetes.secrets.name=db-secret
  3. By defining a list of labels:

    -Dspring.cloud.kubernetes.secrets.labels.broker=activemq
    --Dspring.cloud.kubernetes.secrets.labels.db=postgresql

Table 5.2. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.secrets.enableApi

Boolean

false

Enable/Disable consuming secrets via APIs (examples 2 and 3)

spring.cloud.kubernetes.secrets.enabled

Boolean

true

Enable Secrets PropertySource

spring.cloud.kubernetes.secrets.name

String

${spring.application.name}

Sets the name of the secret to lookup

spring.cloud.kubernetes.secrets.namespace

String

Client namespace

Sets the Kubernetes namespace where to lookup

spring.cloud.kubernetes.secrets.labels

Map

null

Sets the labels used to lookup secrets

spring.cloud.kubernetes.secrets.paths

List

null

Sets the paths where secrets are mounted (example 1)


Notes: -- The property spring.cloud.kubernetes.secrets.labels behaves as defined by + key: password

You can select the Secrets to consume in a number of ways:

  1. By listing the directories where secrets are mapped:

    -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets/db-secret,etc/secrets/postgresql

    If you have all the secrets mapped to a common root, you can set them like:

    -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets
  2. By setting a named secret:

    -Dspring.cloud.kubernetes.secrets.name=db-secret
  3. By defining a list of labels:

    -Dspring.cloud.kubernetes.secrets.labels.broker=activemq
    +-Dspring.cloud.kubernetes.secrets.labels.db=postgresql

Table 5.2. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.secrets.enableApi

Boolean

false

Enables or disables consuming secrets through APIs (examples 2 and 3)

spring.cloud.kubernetes.secrets.enabled

Boolean

true

Enable Secrets PropertySource

spring.cloud.kubernetes.secrets.name

String

${spring.application.name}

Sets the name of the secret to look up

spring.cloud.kubernetes.secrets.namespace

String

Client namespace

Sets the Kubernetes namespace where to look up

spring.cloud.kubernetes.secrets.labels

Map

null

Sets the labels used to lookup secrets

spring.cloud.kubernetes.secrets.paths

List

null

Sets the paths where secrets are mounted (example 1)


Notes: +* The spring.cloud.kubernetes.secrets.labels property behaves as defined by Map-based binding. -- The property spring.cloud.kubernetes.secrets.paths behaves as defined by +* The spring.cloud.kubernetes.secrets.paths property behaves as defined by Collection-based binding. -- Access to secrets via API may be restricted for security reasons, the preferred way is to mount secret to the POD.

Example of application using secrets (though it hasn’t been updated to use the new spring-cloud-kubernetes project): -spring-boot-camel-config

5.3 PropertySource Reload

Some applications may need to detect changes on external property sources and update their internal status to reflect the new configuration. +* Access to secrets through the API may be restricted for security reasons. The preferred way is to mount secrets to the Pod.

You can find an example of an application that uses secrets (though it has not been updated to use the new spring-cloud-kubernetes project) at +spring-boot-camel-config

5.3 PropertySource Reload

Some applications may need to detect changes on external property sources and update their internal status to reflect the new configuration. The reload feature of Spring Cloud Kubernetes is able to trigger an application reload when a related ConfigMap or -Secret changes.

This feature is disabled by default and can be enabled using the configuration property spring.cloud.kubernetes.reload.enabled=true - (eg. in the application.properties file).

The following levels of reload are supported (property spring.cloud.kubernetes.reload.strategy): -- refresh (default): only configuration beans annotated with @ConfigurationProperties or @RefreshScope are reloaded. +Secret changes.

By default, this feature is disabled. You can enable it by using the spring.cloud.kubernetes.reload.enabled=true configuration property (for example, in the application.properties file).

The following levels of reload are supported (by setting the spring.cloud.kubernetes.reload.strategy property): +* refresh (default): Only configuration beans annotated with @ConfigurationProperties or @RefreshScope are reloaded. This reload level leverages the refresh feature of Spring Cloud Context. -- restart_context: the whole Spring ApplicationContext is gracefully restarted. Beans are recreated with the new configuration. -- shutdown: the Spring ApplicationContext is shut down to activate a restart of the container. - When using this level, make sure that the lifecycle of all non-daemon threads is bound to the ApplicationContext - and that a replication controller or replica set is configured to restart the pod.

Example:

Assuming that the reload feature is enabled with default settings (refresh mode), the following bean will be refreshed when the config map changes:

@Configuration
-@ConfigurationProperties(prefix = "bean")
-public class MyConfig {
+* restart_context: the whole Spring ApplicationContext is gracefully restarted. Beans are recreated with the new configuration.
+* shutdown: the Spring ApplicationContext is shut down to activate a restart of the container.
+ When you use this level, make sure that the lifecycle of all non-daemon threads is bound to the ApplicationContext
+and that a replication controller or replica set is configured to restart the pod.

Assuming that the reload feature is enabled with default settings (refresh mode), the following bean is refreshed when the config map changes:

@Configuration
+@ConfigurationProperties(prefix = "bean")
+public class MyConfig {
 
-    private String message = "a message that can be changed live";
+    private String message = "a message that can be changed live";
 
-    // getter and setters
+    // getter and setters
 
-}

A way to see that changes effectively happen is creating another bean that prints the message periodically.

@Component
+}

To see that changes effectively happen, you can create another bean that prints the message periodically, as follows

@Component
 public class MyBean {
 
     @Autowired
@@ -176,23 +173,23 @@ This reload level leverages the refresh feature of Spring Cloud Context.
     public void hello() {
         System.out.println("The message is: " + config.getMessage());
     }
-}

The message printed by the application can be changed using a ConfigMap as follows:

apiVersion: v1
+}

You can change the message printed by the application by using a ConfigMap, as follows:

apiVersion: v1
 kind: ConfigMap
 metadata:
   name: reload-example
 data:
   application.properties: |-
-    bean.message=Hello World!

Any change to the property named bean.message in the ConfigMap associated to the pod will be reflected in the + bean.message=Hello World!

Any change to the property named bean.message in the ConfigMap associated with the pod is reflected in the output. More generally speaking, changes associated to properties prefixed with the value defined by the prefix -field of the @ConfigurationProperties annotation will be detected and reflected in the application. -[Associating a ConfigMap to a pod](#configmap-propertysource) is explained above.

The full example is available in [spring-cloud-kubernetes-reload-example](spring-cloud-kubernetes-examples/kubernetes-reload-example).

The reload feature supports two operating modes: -- event (default): watches for changes in config maps or secrets using the Kubernetes API (web socket). -Any event will produce a re-check on the configuration and a reload in case of changes. -The view role on the service account is required in order to listen for config map changes. A higher level role (eg. edit) is required for secrets -(secrets are not monitored by default). -- polling: re-creates the configuration periodically from config maps and secrets to see if it has changed. -The polling period can be configured using the property spring.cloud.kubernetes.reload.period and defaults to 15 seconds. +field of the @ConfigurationProperties annotation are detected and reflected in the application. +Associating a ConfigMap with a pod is explained earlier in this chapter.

The full example is available in spring-cloud-kubernetes-reload-example.

The reload feature supports two operating modes: +* Event (default): Watches for changes in config maps or secrets by using the Kubernetes API (web socket). +Any event produces a re-check on the configuration and, in case of changes, a reload. +The view role on the service account is required in order to listen for config map changes. A higher level role (such as edit) is required for secrets +(by default, secrets are not monitored). +* Polling: Oeriodically re-creates the configuration from config maps and secrets to see if it has changed. +You can configure the polling period by using the spring.cloud.kubernetes.reload.period property and defaults to 15 seconds. It requires the same role as the monitored property source. -This means, for example, that using polling on file mounted secret sources does not require particular privileges.

Table 5.3. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.reload.period

Duration

15s

The period for verifying changes when using the polling strategy

spring.cloud.kubernetes.reload.enabled

Boolean

false

Enables monitoring of property sources and configuration reload

spring.cloud.kubernetes.reload.monitoring-config-maps

Boolean

true

Allow monitoring changes in config maps

spring.cloud.kubernetes.reload.monitoring-secrets

Boolean

false

Allow monitoring changes in secrets

spring.cloud.kubernetes.reload.strategy

Enum

refresh

The strategy to use when firing a reload (refresh, restart_context, shutdown)

spring.cloud.kubernetes.reload.mode

Enum

event

Specifies how to listen for changes in property sources (event, polling)


Notes: -- Properties under spring.cloud.kubernetes.reload. should not be used in config maps or secrets: changing such properties at runtime may lead to unexpected results; -- Deleting a property or the whole config map does not restore the original state of the beans when using the refresh level.

\ No newline at end of file +This means, for example, that using polling on file-mounted secret sources does not require particular privileges.

Table 5.3. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.reload.period

Duration

15s

The period for verifying changes when using the polling strategy

spring.cloud.kubernetes.reload.enabled

Boolean

false

Enables monitoring of property sources and configuration reload

spring.cloud.kubernetes.reload.monitoring-config-maps

Boolean

true

Allow monitoring changes in config maps

spring.cloud.kubernetes.reload.monitoring-secrets

Boolean

false

Allow monitoring changes in secrets

`spring.cloud.kubernetes.reload.strategy `

Enum

refresh

The strategy to use when firing a reload (refresh, restart_context, or shutdown)

spring.cloud.kubernetes.reload.mode

Enum

event

Specifies how to listen for changes in property sources (event or polling)


Notes: +* You should not use properties under spring.cloud.kubernetes.reload in config maps or secrets. Changing such properties at runtime may lead to unexpected results. +* Deleting a property or the whole config map does not restore the original state of the beans when you use the refresh level.

\ No newline at end of file diff --git a/multi/multi__leader_election.html b/multi/multi__leader_election.html index 259d1e39..19ddb1c0 100644 --- a/multi/multi__leader_election.html +++ b/multi/multi__leader_election.html @@ -1,3 +1,3 @@ - 9. Leader Election

9. Leader Election

<TBD>

\ No newline at end of file + 9. Leader Election

9. Leader Election

<TBD>

\ No newline at end of file diff --git a/multi/multi__other_resources.html b/multi/multi__other_resources.html index 44dcf986..4bf36588 100644 --- a/multi/multi__other_resources.html +++ b/multi/multi__other_resources.html @@ -1,3 +1,3 @@ - 12. Other Resources

12. Other Resources

Here you can find other resources such as presentations(slides) and videos about Spring Cloud Kubernetes.

Please feel free to submit other resources via PR to this repository.

\ No newline at end of file + 12. Other Resources

12. Other Resources

This section lists other resources, such as presentations (slides) and videos about Spring Cloud Kubernetes.

Please feel free to submit other resources through pull requests to this repository.

\ No newline at end of file diff --git a/multi/multi__pod_health_indicator.html b/multi/multi__pod_health_indicator.html index 8a3391ff..9eb22672 100644 --- a/multi/multi__pod_health_indicator.html +++ b/multi/multi__pod_health_indicator.html @@ -1,4 +1,4 @@ - 8. Pod Health Indicator

8. Pod Health Indicator

Spring Boot uses HealthIndicator to expose info about the health of an application. -That makes it really useful for exposing health related information to the user and are also a good fit for use as readiness probes.

The Kubernetes health indicator which is part of the core module exposes the following info:

  • pod name, ip address, namespace, service account, node name and its ip address
  • flag that indicates if the Spring Boot application is internal or external to Kubernetes
\ No newline at end of file + 8. Pod Health Indicator

8. Pod Health Indicator

Spring Boot uses HealthIndicator to expose info about the health of an application. +That makes it really useful for exposing health-related information to the user and makes it a good fit for use as readiness probes.

The Kubernetes health indicator (which is part of the core module) exposes the following info:

  • Pod name, IP address, namespace, service account, node name, and its IP address
  • A flag that indicates whether the Spring Boot application is internal or external to Kubernetes
\ No newline at end of file diff --git a/multi/multi__ribbon_discovery_in_kubernetes.html b/multi/multi__ribbon_discovery_in_kubernetes.html index e4c055ff..9dfc89a8 100644 --- a/multi/multi__ribbon_discovery_in_kubernetes.html +++ b/multi/multi__ribbon_discovery_in_kubernetes.html @@ -1,17 +1,20 @@ - 6. Ribbon discovery in Kubernetes

6. Ribbon discovery in Kubernetes

Spring Cloud client applications calling a microservice should be interested on relying on a client load-balancing + 6. Ribbon Discovery in Kubernetes

6. Ribbon Discovery in Kubernetes

Spring Cloud client applications that call a microservice should be interested on relying on a client load-balancing feature in order to automatically discover at which endpoint(s) it can reach a given service. This mechanism has been -implemented within the [spring-cloud-kubernetes-ribbon](spring-cloud-kubernetes-ribbon/pom.xml) project where a -Kubernetes client will populate a Ribbon ServerList containing information -about such endpoints.

When the list of the endpoints is populated, the Kubernetes client will search the registered endpoints living in -the current namespace/project matching the service name defined using the Ribbon Client annotation:

@RibbonClient(name = "name-service")

You can configure Ribbon’s behavior by providing properties in your application.properties (via your application’s -dedicated ConfigMap) using the following format: <name of your service>.ribbon.<Ribbon configuration key> where:

  • <name of your service> corresponds to the service name you’re accessing over Ribbon, as configured using the -@RibbonClient annotation (e.g. name-service in the example above)
  • <Ribbon configuration key> is one of the Ribbon configuration key defined by -Ribbon’s CommonClientConfigKey class

Additionally, the spring-cloud-kubernetes-ribbon project defines two additional configuration keys to further +implemented within the spring-cloud-kubernetes-ribbon project, where a +Kubernetes client populates a Ribbon ServerList that contains information +about such endpoints.

The implementation is part of the following starter that you can use by adding its dependency to your pom file:

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-starter-kubernetes-ribbon</artifactId>
+    <version>${latest.version}</version>
+</dependency>

When the list of the endpoints is populated, the Kubernetes client searches the registered endpoints that live in +the current namespace or project by matching the service name defined in the Ribbon Client annotation, as follows:

@RibbonClient(name = "name-service")

You can configure Ribbon’s behavior by providing properties in your application.properties (through your application’s +dedicated ConfigMap) by using the following format: <name of your service>.ribbon.<Ribbon configuration key>, where:

  • <name of your service> corresponds to the service name you access over Ribbon, as configured by using the +@RibbonClient annotation (such as name-service in the preceding example).
  • <Ribbon configuration key> is one of the Ribbon configuration keys defined by +Ribbon’s CommonClientConfigKey class.

Additionally, the spring-cloud-kubernetes-ribbon project defines two additional configuration keys to further control how Ribbon interacts with Kubernetes. In particular, if an endpoint defines multiple ports, the default -behavior is to use the first one found. To select more specifically which port to use, in a multi-port service, use -the PortName key. If you want to specify in which Kubernetes' namespace the target service should be looked up, use +behavior is to use the first one found. To select more specifically which port to use in a multi-port service, you can use +the PortName key. If you want to specify in which Kubernetes namespace the target service should be looked up, you can use the KubernetesNamespace key, remembering in both instances to prefix these keys with your service name and -ribbon prefix as specified above.

Examples that are using this module for ribbon discovery are:

Note: The Ribbon discovery client can be disabled by setting this key within the application properties file -spring.cloud.kubernetes.ribbon.enabled=false.

\ No newline at end of file +ribbon prefix, as specified earlier.

The following examples use this module for ribbon discovery:

[Note]Note

You can disable the Ribbon discovery client by setting the spring.cloud.kubernetes.ribbon.enabled=false key within the application properties file.

\ No newline at end of file diff --git a/multi/multi__security_configurations_inside_kubernetes.html b/multi/multi__security_configurations_inside_kubernetes.html index 2f65bd3f..b655e24b 100644 --- a/multi/multi__security_configurations_inside_kubernetes.html +++ b/multi/multi__security_configurations_inside_kubernetes.html @@ -1,9 +1,9 @@ - 10. Security Configurations inside Kubernetes

10. Security Configurations inside Kubernetes

10.1 Namespace

Most of the components provided in this project need to know the namespace. For Kubernetes (1.3+) the namespace is made available to pod as part of the service account secret and automatically detected by the client. -For earlier version it needs to be specified as an env var to the pod. A quick way to do this is:

env:
-- name: "KUBERNETES_NAMESPACE"
-  valueFrom:
-    fieldRef:
-      fieldPath: "metadata.namespace"

10.2 Service Account

For distros of Kubernetes that support more fine-grained role-based access within the cluster, you need to make sure a pod that runs with spring-cloud-kubernetes has access to the Kubernetes API. -For any service accounts you assign to a deployment/pod, you need to make sure it has the correct roles. For example, you can add cluster-reader permissions to your default service account depending on the project you’re in:

\ No newline at end of file + 10. Security Configurations Inside Kubernetes

10. Security Configurations Inside Kubernetes

10.1 Namespace

Most of the components provided in this project need to know the namespace. For Kubernetes (1.3+), the namespace is made available to the pod as part of the service account secret and is automatically detected by the client. +For earlier versions, it needs to be specified as an environment variable to the pod. A quick way to do this is as follows:

      env:
+      - name: "KUBERNETES_NAMESPACE"
+        valueFrom:
+          fieldRef:
+            fieldPath: "metadata.namespace"

10.2 Service Account

For distributions of Kubernetes that support more fine-grained role-based access within the cluster, you need to make sure a pod that runs with spring-cloud-kubernetes has access to the Kubernetes API. +For any service accounts you assign to a deployment or pod, you need to make sure they have the correct roles. For example, you can add cluster-reader permissions to your default service account, depending on the project you’re in.

\ No newline at end of file diff --git a/multi/multi__starters.html b/multi/multi__starters.html index 8d23af83..c35d67ee 100644 --- a/multi/multi__starters.html +++ b/multi/multi__starters.html @@ -10,12 +10,12 @@ resolves service names to Kubernetes Services.

<groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-kubernetes-config</artifactId> </dependency>

Load application properties from Kubernetes -ConfigMaps and Secrets. -Reload application properties when a ConfigMap or +ConfigMaps and Secrets. +Reload application properties when a ConfigMap or Secret changes.

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-kubernetes-ribbon</artifactId>
-</dependency>

Ribbon client-side load balancer with +</dependency>

Ribbon client-side load balancer with server list obtained from Kubernetes Endpoints.

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-kubernetes-all</artifactId>
diff --git a/multi/multi__why_do_you_need_spring_cloud_kubernetes.html b/multi/multi__why_do_you_need_spring_cloud_kubernetes.html
index 0abfc5de..4c132aa3 100644
--- a/multi/multi__why_do_you_need_spring_cloud_kubernetes.html
+++ b/multi/multi__why_do_you_need_spring_cloud_kubernetes.html
@@ -1,4 +1,4 @@
 
       
-   1. Why do you need Spring Cloud Kubernetes?

1. Why do you need Spring Cloud Kubernetes?

Spring Cloud Kubernetes provide Spring Cloud common interfaces implementations to consume Kubernetes native services. -The main objective of the projects provided in this repository is to facilitate the integration of Spring Cloud/Spring Boot applications running inside Kubernetes.

\ No newline at end of file + 1. Why do you need Spring Cloud Kubernetes?

1. Why do you need Spring Cloud Kubernetes?

Spring Cloud Kubernetes provide Spring Cloud common interface implementations that consume Kubernetes native services. +The main objective of the projects provided in this repository is to facilitate the integration of Spring Cloud and Spring Boot applications running inside Kubernetes.

\ No newline at end of file diff --git a/multi/multi_pr01.html b/multi/multi_pr01.html new file mode 100644 index 00000000..5b76f02b --- /dev/null +++ b/multi/multi_pr01.html @@ -0,0 +1,3 @@ + + +

This reference guide covers how to use Spring Cloud Kubernetes.

\ No newline at end of file diff --git a/multi/multi_spring-cloud-kubernetes.html b/multi/multi_spring-cloud-kubernetes.html index 884719ab..6eef4c5e 100644 --- a/multi/multi_spring-cloud-kubernetes.html +++ b/multi/multi_spring-cloud-kubernetes.html @@ -1,3 +1,3 @@ - Spring Cloud Kubernetes \ No newline at end of file + Spring Cloud Kubernetes \ No newline at end of file diff --git a/single/spring-cloud-kubernetes.html b/single/spring-cloud-kubernetes.html index 1e8555bc..90faf6ff 100644 --- a/single/spring-cloud-kubernetes.html +++ b/single/spring-cloud-kubernetes.html @@ -1,7 +1,7 @@ - Spring Cloud Kubernetes

Spring Cloud Kubernetes


1. Why do you need Spring Cloud Kubernetes?

Spring Cloud Kubernetes provide Spring Cloud common interfaces implementations to consume Kubernetes native services. -The main objective of the projects provided in this repository is to facilitate the integration of Spring Cloud/Spring Boot applications running inside Kubernetes.

2. Starters

Starters are convenient dependency descriptors you can include in your + Spring Cloud Kubernetes

Spring Cloud Kubernetes


This reference guide covers how to use Spring Cloud Kubernetes.

1. Why do you need Spring Cloud Kubernetes?

Spring Cloud Kubernetes provide Spring Cloud common interface implementations that consume Kubernetes native services. +The main objective of the projects provided in this repository is to facilitate the integration of Spring Cloud and Spring Boot applications running inside Kubernetes.

2. Starters

Starters are convenient dependency descriptors you can include in your application. Include a starter to get the dependencies and Spring Boot auto-configuration for a feature set.

StarterFeatures
<dependency>
     <groupId>org.springframework.cloud</groupId>
@@ -11,41 +11,44 @@ resolves service names to Kubernetes Services.

<groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-kubernetes-config</artifactId> </dependency>

Load application properties from Kubernetes -ConfigMaps and Secrets. -Reload application properties when a ConfigMap or +ConfigMaps and Secrets. +Reload application properties when a ConfigMap or Secret changes.

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-kubernetes-ribbon</artifactId>
-</dependency>

Ribbon client-side load balancer with +</dependency>

Ribbon client-side load balancer with server list obtained from Kubernetes Endpoints.

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-kubernetes-all</artifactId>
 </dependency>

All Spring Cloud Kubernetes features.

3. DiscoveryClient for Kubernetes

This project provides an implementation of Discovery Client -for Kubernetes. -This allows you to query Kubernetes endpoints (see services) by name. -A service is typically exposed by the Kubernetes API server as a collection of endpoints which represent http, https addresses that a client can +for Kubernetes. +This client lets you query Kubernetes endpoints (see services) by name. +A service is typically exposed by the Kubernetes API server as a collection of endpoints that represent http and https addresses and that a client can access from a Spring Boot application running as a pod. This discovery feature is also used by the Spring Cloud Kubernetes Ribbon project -to fetch the list of the endpoints defined for an application to be load balanced.

To enable loading of the DiscoveryClient, add @EnableDiscoveryClient to the according configuration or application class like this:

@SpringBootApplication
+to fetch the list of the endpoints defined for an application to be load balanced.

This is something that you get for free by adding the following dependency inside your project:

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-starter-kubernetes</artifactId>
+</dependency>

To enable loading of the DiscoveryClient, add @EnableDiscoveryClient to the according configuration or application class, as the following example shows:

@SpringBootApplication
 @EnableDiscoveryClient
 public class Application {
   public static void main(String[] args) {
     SpringApplication.run(Application.class, args);
   }
-}

Then you can inject the client in your code simply by:

@Autowired
-private DiscoveryClient discoveryClient;

If for any reason you need to disable the DiscoveryClient you can simply set the following property in application.properties:

spring.cloud.kubernetes.discovery.enabled=false

Some Spring Cloud components use the DiscoveryClient in order to obtain info about the local service instance. For -this to work you need to align the Kubernetes service name with the spring.application.name property.

4. Kubernetes native service discovery

Kubernetes itself is capable of (server side) service discovery (see: https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services). -Using native kubernetes service discovery ensures compatibility with additional tooling, like: istio https://istio.io (service mesh, capable of load balancing, ribbon, circuit breaker, failover and much more).

The caller service just needs to refer to names resolvable in particular kubernetes cluster then. Simplest implementation might use the spring RestTemplate referring to fully qualified domain name (FQDN) http://{service-name}.{namespace}.svc.{cluster}.local:{service-port}.

Additionally, hystrix can be used for:

  • circuit breaker implementation on the caller side, just by annotating the spring boot application class: @EnableCircuitBreaker
  • and for the fallback functionality, annotating the respective method via: @HystrixCommand(fallbackMethod= does the job.

5. Kubernetes PropertySource implementations

The most common approach to configure your Spring Boot application is to create an application.properties|yaml or -an application-profile.properties|yaml file containing key-value pairs providing customization values to your -application or Spring Boot starters. Users may override these properties by specifying system properties or environment -variables.

5.1 ConfigMap PropertySource

Kubernetes provides a resource named ConfigMap to externalize the -parameters to pass to your application in the form of key-value pairs or embedded application.properties|yaml files. -The Spring Cloud Kubernetes Config project makes Kubernetes `ConfigMap`s available +}

Then you can inject the client in your code simply by autowiring it, as the following example shows:

@Autowired
+private DiscoveryClient discoveryClient;

If, for any reason, you need to disable the DiscoveryClient, you can set the following property in application.properties:

spring.cloud.kubernetes.discovery.enabled=false

Some Spring Cloud components use the DiscoveryClient in order to obtain information about the local service instance. For +this to work, you need to align the Kubernetes service name with the spring.application.name property.

4. Kubernetes native service discovery

Kubernetes itself is capable of (server side) service discovery (see: https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services). +Using native kubernetes service discovery ensures compatibility with additional tooling, such as Istio (https://istio.io), a service mesh that is capable of load balancing, ribbon, circuit breaker, failover, and much more.

The caller service then need only refer to names resolvable in a particular Kubernetes cluster. A simple implementation might use a spring RestTemplate that refers to a fully qualified domain name (FQDN), such as https://{service-name}.{namespace}.svc.{cluster}.local:{service-port}.

Additionally, you can use Hystrix for:

  • Circuit breaker implementation on the caller side, by annotating the spring boot application class with @EnableCircuitBreaker
  • Fallback functionality, by annotating the respective method with @HystrixCommand(fallbackMethod=

5. Kubernetes PropertySource implementations

The most common approach to configuring your Spring Boot application is to create an application.properties or applicaiton.yaml or +an application-profile.properties or application-profile.yaml file that contains key-value pairs that provide customization values to your +application or Spring Boot starters. You can override these properties by specifying system properties or environment +variables.

5.1 Using a ConfigMap PropertySource

Kubernetes provides a resource named ConfigMap to externalize the +parameters to pass to your application in the form of key-value pairs or embedded application.properties or application.yaml files. +The Spring Cloud Kubernetes Config project makes Kubernetes ConfigMap instances available during application bootstrapping and triggers hot reloading of beans or Spring context when changes are detected on -observed `ConfigMap`s.

The default behavior is to create a ConfigMapPropertySource based on a Kubernetes ConfigMap which has metadata.name of either the name of +observed ConfigMap instances.

The default behavior is to create a ConfigMapPropertySource based on a Kubernetes ConfigMap that has a metadata.name value of either the name of your Spring application (as defined by its spring.application.name property) or a custom name defined within the -bootstrap.properties file under the following key spring.cloud.kubernetes.config.name.

However, more advanced configuration are possible where multiple ConfigMaps can be used -This is made possible by the spring.cloud.kubernetes.config.sources list. -For example one could define the following ConfigMaps

spring:
+bootstrap.properties file under the following key: spring.cloud.kubernetes.config.name.

However, more advanced configuration is possible where you can use multiple ConfigMap instances. +The spring.cloud.kubernetes.config.sources list makes this possible. +For example, you could define the following ConfigMap instances:

spring:
   application:
     name: cloud-k8s-app
   cloud:
@@ -54,25 +57,25 @@ For example one could define the following ConfigMaps

        name: default-name
         namespace: default-namespace
         sources:
-         # Spring Cloud Kubernetes will lookup a ConfigMap named c1 in namespace default-namespace
+         # Spring Cloud Kubernetes looks up a ConfigMap named c1 in namespace default-namespace
          - name: c1
-         # Spring Cloud Kubernetes will lookup a ConfigMap named default-name in whatever namespace n2
+         # Spring Cloud Kubernetes looks up a ConfigMap named default-name in whatever namespace n2
          - namespace: n2
-         # Spring Cloud Kubernetes will lookup a ConfigMap named c3 in namespace n3
+         # Spring Cloud Kubernetes looks up a ConfigMap named c3 in namespace n3
          - namespace: n3
-           name: c3

In the example above, it spring.cloud.kubernetes.config.namespace had not been set, -then the ConfigMap named c1 would be looked up in the namespace that the application runs

Any matching ConfigMap that is found, will be processed as follows:

  • apply individual configuration properties.
  • apply as yaml the content of any property named application.yaml
  • apply as properties file the content of any property named application.properties

The single exception to the aforementioned flow is when the ConfigMap contains a single key that indicates -the file is a YAML or Properties file. In that case the name of the key does NOT have to be application.yaml or -application.properties (it can be anything) and the value of the property will be treated correctly. -This features facilitates the use case where the ConfigMap was created using something like:

kubectl create configmap game-config --from-file=/path/to/app-config.yaml

Example:

Let’s assume that we have a Spring Boot application named demo that uses properties to read its thread pool -configuration.

  • pool.size.core
  • pool.size.maximum

This can be externalized to config map in yaml format:

kind: ConfigMap
+           name: c3

In the preceding example, if spring.cloud.kubernetes.config.namespace had not been set, +the ConfigMap named c1 would be looked up in the namespace that the application runs.

Any matching ConfigMap that is found is processed as follows:

  • Apply individual configuration properties.
  • Apply as yaml the content of any property named application.yaml.
  • Apply as a properties file the content of any property named application.properties.

The single exception to the aforementioned flow is when the ConfigMap contains a single key that indicates +the file is a YAML or properties file. In that case, the name of the key does NOT have to be application.yaml or +application.properties (it can be anything) and the value of the property is treated correctly. +This features facilitates the use case where the ConfigMap was created by using something like the following:

kubectl create configmap game-config --from-file=/path/to/app-config.yaml

Assume that we have a Spring Boot application named demo that uses the following properties to read its thread pool +configuration.

  • pool.size.core
  • pool.size.maximum

This can be externalized to config map in yaml format as follows:

kind: ConfigMap
 apiVersion: v1
 metadata:
   name: demo
 data:
   pool.size.core: 1
-  pool.size.max: 16

Individual properties work fine for most cases but sometimes embedded yaml is more convenient. In this case we will -use a single property named application.yaml to embed our yaml:

kind: ConfigMap
+  pool.size.max: 16

Individual properties work fine for most cases. However, sometimes, embedded yaml is more convenient. In this case, we +use a single property named application.yaml to embed our yaml, as follows:

kind: ConfigMap
 apiVersion: v1
 metadata:
   name: demo
@@ -81,7 +84,7 @@ use a single property named application.yaml to emb
     pool:
       size:
         core: 1
-        max:16

The following also works:

kind: ConfigMap
+        max:16

The following example also works:

kind: ConfigMap
 apiVersion: v1
 metadata:
   name: demo
@@ -90,10 +93,10 @@ use a single property named application.yaml to emb
     pool:
       size:
         core: 1
-        max:16

Spring Boot applications can also be configured differently depending on active profiles which will be merged together -when the ConfigMap is read. It is possible to provide different property values for different profiles using an -application.properties|yaml property, specifying profile-specific values each in their own document -(indicated by the --- sequence) as follows:

kind: ConfigMap
+        max:16

You can also configure Spring Boot applications differently depending on active profiles that are merged together +when the ConfigMap is read. You can provide different property values for different profiles by using an +application.properties or application.yaml property, specifying profile-specific values, each in their own document +(indicated by the --- sequence), as follows:

kind: ConfigMap
 apiVersion: v1
 metadata:
   name: demo
@@ -114,15 +117,15 @@ when the ConfigMap is read. It is possible to provide different property values
     spring:
       profiles: production
     greeting:
-      message: Say Hello to the Ops

In the above case, the configuration loaded into your Spring Application with the development profile will be:

  greeting:
+      message: Say Hello to the Ops

In the preceding case, the configuration loaded into your Spring Application with the development profile is as follows:

  greeting:
     message: Say Hello to the Developers
   farewell:
-    message: Say Goodbye to the Developers

whereas if the production profile is active, the configuration will be:

  greeting:
+    message: Say Goodbye to the Developers

However, if the production profile is active, the configuration becomes:

  greeting:
     message: Say Hello to the Ops
   farewell:
-    message: Say Goodbye

If both profiles are active, the property which appears last within the configmap will overwrite preceding values.

To tell to Spring Boot which profile should be enabled at bootstrap, a system property can be passed to the Java -command launching your Spring Boot application using an env variable that you will define with the OpenShift -DeploymentConfig or Kubernetes ReplicationConfig resource file as follows:

apiVersion: v1
+    message: Say Goodbye

If both profiles are active, the property that appears last within the ConfigMap overwrites any preceding values.

To tell Spring Boot which profile should be enabled at bootstrap, you can pass a system property to the Java +command. To do so, you can launch your Spring Boot application with an environment variable that you can define with the OpenShift +DeploymentConfig or Kubernetes ReplicationConfig resource file, as follows:

apiVersion: v1
 kind: DeploymentConfig
 spec:
   replicas: 1
@@ -133,20 +136,18 @@ command launching your Spring Boot application using an env variable that you wi
         - name: JAVA_APP_DIR
           value: /deployments
         - name: JAVA_OPTIONS
-          value: -Dspring.profiles.active=developer

Notes: -- check the security configuration section, to access config maps from inside a pod you need to have the correct -Kubernetes service accounts, roles and role bindings.

Another option for using ConfigMaps, is to mount them into the Pod running the Spring Cloud Kubernetes application -and have Spring Cloud Kubernetes read them from the file system. -This behavior is controlled by the spring.cloud.kubernetes.config.paths property and can be used in + value: -Dspring.profiles.active=developer

[Note]Note

You should check the security configuration section. To access config maps from inside a pod you need to have the correct +Kubernetes service accounts, roles and role bindings.

Another option for using ConfigMap instances is to mount them into the Pod by running the Spring Cloud Kubernetes application +and having Spring Cloud Kubernetes read them from the file system. +This behavior is controlled by the spring.cloud.kubernetes.config.paths property. You can use it in addition to or instead of the mechanism described earlier. -Multiple (exact) file paths can be specified in spring.cloud.kubernetes.config.paths by using the , delimiter

Notes: -You have to provide full exact path to each property file, because directories are not being recursively parsed.

Table 5.1. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.config.enableApi

Boolean

true

Enable/Disable consuming ConfigMaps via APIs

spring.cloud.kubernetes.config.enabled

Boolean

true

Enable Secrets PropertySource

spring.cloud.kubernetes.config.name

String

${spring.application.name}

Sets the name of ConfigMap to lookup

spring.cloud.kubernetes.config.namespace

String

Client namespace

Sets the Kubernetes namespace where to lookup

spring.cloud.kubernetes.config.paths

List

null

Sets the paths where ConfigMaps are mounted


5.2 Secrets PropertySource

Kubernetes has the notion of Secrets for storing -sensitive data such as password, OAuth tokens, etc. This project provides integration with Secrets to make secrets -accessible by Spring Boot applications. This feature can be explicitly enabled/disabled using the spring.cloud.kubernetes.secrets.enabled property.

The SecretsPropertySource when enabled will lookup Kubernetes for Secrets from the following sources:

  1. reading recursively from secrets mounts
  2. named after the application (as defined by spring.application.name)
  3. matching some labels

Please note that by default, consuming Secrets via API (points 2 and 3 above) is not enabled for security reasons -and it is recommended that containers share secrets via mounted volumes. -If you enable consuming Secrets via API, then it is recommended access to Secrets is limited by an -[authorization policy such as RBAC](https://kubernetes.io/docs/concepts/configuration/secret/#best-practices).

If the secrets are found their data is made available to the application.

Example:

Let’s assume that we have a spring boot application named demo that uses properties to read its database -configuration. We can create a Kubernetes secret using the following command:

oc create secret generic db-secret --from-literal=username=user --from-literal=password=p455w0rd

This would create the following secret (shown using oc get secrets db-secret -o yaml):

apiVersion: v1
+You can specify multiple (exact) file paths in spring.cloud.kubernetes.config.paths by using the , delimiter.

[Note]Note

You have to provide the full exact path to each property file, because directories are not being recursively parsed.

Table 5.1. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.config.enableApi

Boolean

true

Enable or disable consuming ConfigMap instances through APIs

spring.cloud.kubernetes.config.enabled

Boolean

true

Enable Secrets PropertySource

spring.cloud.kubernetes.config.name

String

${spring.application.name}

Sets the name of ConfigMap to look up

spring.cloud.kubernetes.config.namespace

String

Client namespace

Sets the Kubernetes namespace where to lookup

spring.cloud.kubernetes.config.paths

List

null

Sets the paths where ConfigMap instances are mounted


5.2 Secrets PropertySource

Kubernetes has the notion of Secrets for storing +sensitive data such as passwords, OAuth tokens, and so on. This project provides integration with Secrets to make secrets +accessible by Spring Boot applications. You can explicitly enable or disable This feature by setting the spring.cloud.kubernetes.secrets.enabled property.

When enabled, the SecretsPropertySource looks up Kubernetes for Secrets from the following sources:

  1. Reading recursively from secrets mounts
  2. Named after the application (as defined by spring.application.name)
  3. Matching some labels

Note that, by default, consuming Secrets through the API (points 2 and 3 above) is not enabled for security reasons. +Further, we recommend that containers share secrets through mounted volumes. +If you enable consuming Secrets through the API, we recommend that you limit access to Secrets by using an +[authorization policy, such as RBAC](https://kubernetes.io/docs/concepts/configuration/secret/#best-practices).

If the secrets are found, their data is made available to the application.

Assume that we have a spring boot application named demo that uses properties to read its database +configuration. We can create a Kubernetes secret by using the following command:

oc create secret generic db-secret --from-literal=username=user --from-literal=password=p455w0rd

The preceding command would create the following secret (which you can see by using oc get secrets db-secret -o yaml):

apiVersion: v1
 data:
   password: cDQ1NXcwcmQ=
   username: dXNlcg==
@@ -158,7 +159,7 @@ configuration. We can create a Kubernetes secret using the following command:

resourceVersion: "357496" selfLink: /api/v1/namespaces/default/secrets/db-secret uid: 63c89263-6099-11e7-b3da-76d6186905a8 -type: Opaque

Note that the data contains Base64-encoded versions of the literal provided by the create command.

This secret can then be used by your application for example by exporting the secret’s value as environment variables:

apiVersion: v1
+type: Opaque

Note that the data contains Base64-encoded versions of the literal provided by the create command.

Your application can then use this secret — for example, by exporting the secret’s value as environment variables:

apiVersion: v1
 kind: Deployment
 metadata:
   name: ${project.artifactId}
@@ -176,31 +177,30 @@ configuration. We can create a Kubernetes secret using the following command:

valueFrom: secretKeyRef: name: db-secret - key: password

You can select the Secrets to consume in a number of ways:

  1. By listing the directories where secrets are mapped:

    -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets/db-secret,etc/secrets/postgresql

    If you have all the secrets mapped to a common root, you can set them like:

    -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets
  2. By setting a named secret:

    -Dspring.cloud.kubernetes.secrets.name=db-secret
  3. By defining a list of labels:

    -Dspring.cloud.kubernetes.secrets.labels.broker=activemq
    --Dspring.cloud.kubernetes.secrets.labels.db=postgresql

Table 5.2. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.secrets.enableApi

Boolean

false

Enable/Disable consuming secrets via APIs (examples 2 and 3)

spring.cloud.kubernetes.secrets.enabled

Boolean

true

Enable Secrets PropertySource

spring.cloud.kubernetes.secrets.name

String

${spring.application.name}

Sets the name of the secret to lookup

spring.cloud.kubernetes.secrets.namespace

String

Client namespace

Sets the Kubernetes namespace where to lookup

spring.cloud.kubernetes.secrets.labels

Map

null

Sets the labels used to lookup secrets

spring.cloud.kubernetes.secrets.paths

List

null

Sets the paths where secrets are mounted (example 1)


Notes: -- The property spring.cloud.kubernetes.secrets.labels behaves as defined by + key: password

You can select the Secrets to consume in a number of ways:

  1. By listing the directories where secrets are mapped:

    -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets/db-secret,etc/secrets/postgresql

    If you have all the secrets mapped to a common root, you can set them like:

    -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets
  2. By setting a named secret:

    -Dspring.cloud.kubernetes.secrets.name=db-secret
  3. By defining a list of labels:

    -Dspring.cloud.kubernetes.secrets.labels.broker=activemq
    +-Dspring.cloud.kubernetes.secrets.labels.db=postgresql

Table 5.2. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.secrets.enableApi

Boolean

false

Enables or disables consuming secrets through APIs (examples 2 and 3)

spring.cloud.kubernetes.secrets.enabled

Boolean

true

Enable Secrets PropertySource

spring.cloud.kubernetes.secrets.name

String

${spring.application.name}

Sets the name of the secret to look up

spring.cloud.kubernetes.secrets.namespace

String

Client namespace

Sets the Kubernetes namespace where to look up

spring.cloud.kubernetes.secrets.labels

Map

null

Sets the labels used to lookup secrets

spring.cloud.kubernetes.secrets.paths

List

null

Sets the paths where secrets are mounted (example 1)


Notes: +* The spring.cloud.kubernetes.secrets.labels property behaves as defined by Map-based binding. -- The property spring.cloud.kubernetes.secrets.paths behaves as defined by +* The spring.cloud.kubernetes.secrets.paths property behaves as defined by Collection-based binding. -- Access to secrets via API may be restricted for security reasons, the preferred way is to mount secret to the POD.

Example of application using secrets (though it hasn’t been updated to use the new spring-cloud-kubernetes project): -spring-boot-camel-config

5.3 PropertySource Reload

Some applications may need to detect changes on external property sources and update their internal status to reflect the new configuration. +* Access to secrets through the API may be restricted for security reasons. The preferred way is to mount secrets to the Pod.

You can find an example of an application that uses secrets (though it has not been updated to use the new spring-cloud-kubernetes project) at +spring-boot-camel-config

5.3 PropertySource Reload

Some applications may need to detect changes on external property sources and update their internal status to reflect the new configuration. The reload feature of Spring Cloud Kubernetes is able to trigger an application reload when a related ConfigMap or -Secret changes.

This feature is disabled by default and can be enabled using the configuration property spring.cloud.kubernetes.reload.enabled=true - (eg. in the application.properties file).

The following levels of reload are supported (property spring.cloud.kubernetes.reload.strategy): -- refresh (default): only configuration beans annotated with @ConfigurationProperties or @RefreshScope are reloaded. +Secret changes.

By default, this feature is disabled. You can enable it by using the spring.cloud.kubernetes.reload.enabled=true configuration property (for example, in the application.properties file).

The following levels of reload are supported (by setting the spring.cloud.kubernetes.reload.strategy property): +* refresh (default): Only configuration beans annotated with @ConfigurationProperties or @RefreshScope are reloaded. This reload level leverages the refresh feature of Spring Cloud Context. -- restart_context: the whole Spring ApplicationContext is gracefully restarted. Beans are recreated with the new configuration. -- shutdown: the Spring ApplicationContext is shut down to activate a restart of the container. - When using this level, make sure that the lifecycle of all non-daemon threads is bound to the ApplicationContext - and that a replication controller or replica set is configured to restart the pod.

Example:

Assuming that the reload feature is enabled with default settings (refresh mode), the following bean will be refreshed when the config map changes:

@Configuration
-@ConfigurationProperties(prefix = "bean")
-public class MyConfig {
+* restart_context: the whole Spring ApplicationContext is gracefully restarted. Beans are recreated with the new configuration.
+* shutdown: the Spring ApplicationContext is shut down to activate a restart of the container.
+ When you use this level, make sure that the lifecycle of all non-daemon threads is bound to the ApplicationContext
+and that a replication controller or replica set is configured to restart the pod.

Assuming that the reload feature is enabled with default settings (refresh mode), the following bean is refreshed when the config map changes:

@Configuration
+@ConfigurationProperties(prefix = "bean")
+public class MyConfig {
 
-    private String message = "a message that can be changed live";
+    private String message = "a message that can be changed live";
 
-    // getter and setters
+    // getter and setters
 
-}

A way to see that changes effectively happen is creating another bean that prints the message periodically.

@Component
+}

To see that changes effectively happen, you can create another bean that prints the message periodically, as follows

@Component
 public class MyBean {
 
     @Autowired
@@ -210,60 +210,63 @@ This reload level leverages the refresh feature of Spring Cloud Context.
     public void hello() {
         System.out.println("The message is: " + config.getMessage());
     }
-}

The message printed by the application can be changed using a ConfigMap as follows:

apiVersion: v1
+}

You can change the message printed by the application by using a ConfigMap, as follows:

apiVersion: v1
 kind: ConfigMap
 metadata:
   name: reload-example
 data:
   application.properties: |-
-    bean.message=Hello World!

Any change to the property named bean.message in the ConfigMap associated to the pod will be reflected in the + bean.message=Hello World!

Any change to the property named bean.message in the ConfigMap associated with the pod is reflected in the output. More generally speaking, changes associated to properties prefixed with the value defined by the prefix -field of the @ConfigurationProperties annotation will be detected and reflected in the application. -[Associating a ConfigMap to a pod](#configmap-propertysource) is explained above.

The full example is available in [spring-cloud-kubernetes-reload-example](spring-cloud-kubernetes-examples/kubernetes-reload-example).

The reload feature supports two operating modes: -- event (default): watches for changes in config maps or secrets using the Kubernetes API (web socket). -Any event will produce a re-check on the configuration and a reload in case of changes. -The view role on the service account is required in order to listen for config map changes. A higher level role (eg. edit) is required for secrets -(secrets are not monitored by default). -- polling: re-creates the configuration periodically from config maps and secrets to see if it has changed. -The polling period can be configured using the property spring.cloud.kubernetes.reload.period and defaults to 15 seconds. +field of the @ConfigurationProperties annotation are detected and reflected in the application. +Associating a ConfigMap with a pod is explained earlier in this chapter.

The full example is available in spring-cloud-kubernetes-reload-example.

The reload feature supports two operating modes: +* Event (default): Watches for changes in config maps or secrets by using the Kubernetes API (web socket). +Any event produces a re-check on the configuration and, in case of changes, a reload. +The view role on the service account is required in order to listen for config map changes. A higher level role (such as edit) is required for secrets +(by default, secrets are not monitored). +* Polling: Oeriodically re-creates the configuration from config maps and secrets to see if it has changed. +You can configure the polling period by using the spring.cloud.kubernetes.reload.period property and defaults to 15 seconds. It requires the same role as the monitored property source. -This means, for example, that using polling on file mounted secret sources does not require particular privileges.

Table 5.3. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.reload.period

Duration

15s

The period for verifying changes when using the polling strategy

spring.cloud.kubernetes.reload.enabled

Boolean

false

Enables monitoring of property sources and configuration reload

spring.cloud.kubernetes.reload.monitoring-config-maps

Boolean

true

Allow monitoring changes in config maps

spring.cloud.kubernetes.reload.monitoring-secrets

Boolean

false

Allow monitoring changes in secrets

spring.cloud.kubernetes.reload.strategy

Enum

refresh

The strategy to use when firing a reload (refresh, restart_context, shutdown)

spring.cloud.kubernetes.reload.mode

Enum

event

Specifies how to listen for changes in property sources (event, polling)


Notes: -- Properties under spring.cloud.kubernetes.reload. should not be used in config maps or secrets: changing such properties at runtime may lead to unexpected results; -- Deleting a property or the whole config map does not restore the original state of the beans when using the refresh level.

6. Ribbon discovery in Kubernetes

Spring Cloud client applications calling a microservice should be interested on relying on a client load-balancing +This means, for example, that using polling on file-mounted secret sources does not require particular privileges.

Table 5.3. Properties:

NameTypeDefaultDescription

spring.cloud.kubernetes.reload.period

Duration

15s

The period for verifying changes when using the polling strategy

spring.cloud.kubernetes.reload.enabled

Boolean

false

Enables monitoring of property sources and configuration reload

spring.cloud.kubernetes.reload.monitoring-config-maps

Boolean

true

Allow monitoring changes in config maps

spring.cloud.kubernetes.reload.monitoring-secrets

Boolean

false

Allow monitoring changes in secrets

`spring.cloud.kubernetes.reload.strategy `

Enum

refresh

The strategy to use when firing a reload (refresh, restart_context, or shutdown)

spring.cloud.kubernetes.reload.mode

Enum

event

Specifies how to listen for changes in property sources (event or polling)


Notes: +* You should not use properties under spring.cloud.kubernetes.reload in config maps or secrets. Changing such properties at runtime may lead to unexpected results. +* Deleting a property or the whole config map does not restore the original state of the beans when you use the refresh level.

6. Ribbon Discovery in Kubernetes

Spring Cloud client applications that call a microservice should be interested on relying on a client load-balancing feature in order to automatically discover at which endpoint(s) it can reach a given service. This mechanism has been -implemented within the [spring-cloud-kubernetes-ribbon](spring-cloud-kubernetes-ribbon/pom.xml) project where a -Kubernetes client will populate a Ribbon ServerList containing information -about such endpoints.

When the list of the endpoints is populated, the Kubernetes client will search the registered endpoints living in -the current namespace/project matching the service name defined using the Ribbon Client annotation:

@RibbonClient(name = "name-service")

You can configure Ribbon’s behavior by providing properties in your application.properties (via your application’s -dedicated ConfigMap) using the following format: <name of your service>.ribbon.<Ribbon configuration key> where:

  • <name of your service> corresponds to the service name you’re accessing over Ribbon, as configured using the -@RibbonClient annotation (e.g. name-service in the example above)
  • <Ribbon configuration key> is one of the Ribbon configuration key defined by -Ribbon’s CommonClientConfigKey class

Additionally, the spring-cloud-kubernetes-ribbon project defines two additional configuration keys to further +implemented within the spring-cloud-kubernetes-ribbon project, where a +Kubernetes client populates a Ribbon ServerList that contains information +about such endpoints.

The implementation is part of the following starter that you can use by adding its dependency to your pom file:

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-starter-kubernetes-ribbon</artifactId>
+    <version>${latest.version}</version>
+</dependency>

When the list of the endpoints is populated, the Kubernetes client searches the registered endpoints that live in +the current namespace or project by matching the service name defined in the Ribbon Client annotation, as follows:

@RibbonClient(name = "name-service")

You can configure Ribbon’s behavior by providing properties in your application.properties (through your application’s +dedicated ConfigMap) by using the following format: <name of your service>.ribbon.<Ribbon configuration key>, where:

  • <name of your service> corresponds to the service name you access over Ribbon, as configured by using the +@RibbonClient annotation (such as name-service in the preceding example).
  • <Ribbon configuration key> is one of the Ribbon configuration keys defined by +Ribbon’s CommonClientConfigKey class.

Additionally, the spring-cloud-kubernetes-ribbon project defines two additional configuration keys to further control how Ribbon interacts with Kubernetes. In particular, if an endpoint defines multiple ports, the default -behavior is to use the first one found. To select more specifically which port to use, in a multi-port service, use -the PortName key. If you want to specify in which Kubernetes' namespace the target service should be looked up, use +behavior is to use the first one found. To select more specifically which port to use in a multi-port service, you can use +the PortName key. If you want to specify in which Kubernetes namespace the target service should be looked up, you can use the KubernetesNamespace key, remembering in both instances to prefix these keys with your service name and -ribbon prefix as specified above.

Examples that are using this module for ribbon discovery are:

Note: The Ribbon discovery client can be disabled by setting this key within the application properties file -spring.cloud.kubernetes.ribbon.enabled=false.

7. Kubernetes Ecosystem Awareness

All of the features described above will work equally well regardless of whether your application is running inside -Kubernetes or not. This is really helpful for development and troubleshooting. -From a development point of view, this is really helpful as you can start your Spring Boot application and debug one -of the modules part of this project. It is not required to deploy it in Kubernetes +ribbon prefix, as specified earlier.

The following examples use this module for ribbon discovery:

[Note]Note

You can disable the Ribbon discovery client by setting the spring.cloud.kubernetes.ribbon.enabled=false key within the application properties file.

7. Kubernetes Ecosystem Awareness

All of the features described earlier in this guide work equally well, regardless of whether your application is running inside +Kubernetes. This is really helpful for development and troubleshooting. +From a development point of view, this lets you start your Spring Boot application and debug one +of the modules that is part of this project. You need not deploy it in Kubernetes, as the code of the project relies on the -Fabric8 Kubernetes Java client which is a fluent DSL able to -communicate using http protocol to the REST API of Kubernetes Server.

7.1 Kubernetes Profile Autoconfiguration

When the application runs as a pod inside Kubernetes a Spring profile named kubernetes will automatically get activated. -This allows the developer to customize the configuration, to define beans that will be applied when the Spring Boot application is deployed -within the Kubernetes platform (e.g. different dev and prod configuration).

7.2 Istio Awareness

When including the spring-cloud-kubernetes-istio module into the application classpath a new profile will be added to the application, -if the application is running inside a Kubernetes Cluster with Istio installed. Then you can use -spring @Profile("istio") annotations into your Beans and @Configuration's.

The Istio awareness module uses the me.snowdrop:istio-client to interact with Istio APIs enabling us to discover traffic rules, circuit breakers, etc. -Making it easy for our Spring Boot applications to consume this data to dynamically configure themselves according the environment.

8. Pod Health Indicator

Spring Boot uses HealthIndicator to expose info about the health of an application. -That makes it really useful for exposing health related information to the user and are also a good fit for use as readiness probes.

The Kubernetes health indicator which is part of the core module exposes the following info:

  • pod name, ip address, namespace, service account, node name and its ip address
  • flag that indicates if the Spring Boot application is internal or external to Kubernetes

9. Leader Election

<TBD>

10. Security Configurations inside Kubernetes

10.1 Namespace

Most of the components provided in this project need to know the namespace. For Kubernetes (1.3+) the namespace is made available to pod as part of the service account secret and automatically detected by the client. -For earlier version it needs to be specified as an env var to the pod. A quick way to do this is:

env:
-- name: "KUBERNETES_NAMESPACE"
-  valueFrom:
-    fieldRef:
-      fieldPath: "metadata.namespace"

10.2 Service Account

For distros of Kubernetes that support more fine-grained role-based access within the cluster, you need to make sure a pod that runs with spring-cloud-kubernetes has access to the Kubernetes API. -For any service accounts you assign to a deployment/pod, you need to make sure it has the correct roles. For example, you can add cluster-reader permissions to your default service account depending on the project you’re in:

11. Examples

Spring Cloud Kubernetes tries to make it transparent for your applications to consume Kubernetes Native Services -following the Spring Cloud interfaces.

In your applications, you need to add the spring-cloud-kubernetes-discovery dependency to your classpath and remove any other dependency that contains a DiscoveryClient implementation (ie. Eureka Discovery Client). -The same applies for PropertySourceLocator, where you need to add to the classpath the spring-cloud-kubernetes-config and remove any other dependency that contains a PropertySourceLocator implementation (ie. Config Server Client).

The following projects highlight the usage of these dependencies and demonstrate how these libraries can be used from any Spring Boot application.

List of examples using these projects:

12. Other Resources

Here you can find other resources such as presentations(slides) and videos about Spring Cloud Kubernetes.

Please feel free to submit other resources via PR to this repository.

13. Building

13.1 Basic Compile and Test

To build the source you will need to install JDK 1.7.

Spring Cloud uses Maven for most build-related activities, and you +Fabric8 Kubernetes Java client, which is a fluent DSL that can +communicate by using http protocol to the REST API of the Kubernetes Server.

7.1 Kubernetes Profile Autoconfiguration

When the application runs as a pod inside Kubernetes, a Spring profile named kubernetes automatically gets activated. +This lets you customize the configuration, to define beans that are applied when the Spring Boot application is deployed +within the Kubernetes platform (for example, different development and production configuration).

7.2 Istio Awareness

When you include the spring-cloud-kubernetes-istio module in the application classpath, a new profile is added to the application, +provided the application is running inside a Kubernetes Cluster with Istio installed. You can then use +spring @Profile("istio") annotations in your Beans and @Configuration classes.

The Istio awareness module uses me.snowdrop:istio-client to interact with Istio APIs, letting us discover traffic rules, circuit breakers, and so on, +making it easy for our Spring Boot applications to consume this data to dynamically configure themselves according to the environment.

8. Pod Health Indicator

Spring Boot uses HealthIndicator to expose info about the health of an application. +That makes it really useful for exposing health-related information to the user and makes it a good fit for use as readiness probes.

The Kubernetes health indicator (which is part of the core module) exposes the following info:

  • Pod name, IP address, namespace, service account, node name, and its IP address
  • A flag that indicates whether the Spring Boot application is internal or external to Kubernetes

9. Leader Election

<TBD>

10. Security Configurations Inside Kubernetes

10.1 Namespace

Most of the components provided in this project need to know the namespace. For Kubernetes (1.3+), the namespace is made available to the pod as part of the service account secret and is automatically detected by the client. +For earlier versions, it needs to be specified as an environment variable to the pod. A quick way to do this is as follows:

      env:
+      - name: "KUBERNETES_NAMESPACE"
+        valueFrom:
+          fieldRef:
+            fieldPath: "metadata.namespace"

10.2 Service Account

For distributions of Kubernetes that support more fine-grained role-based access within the cluster, you need to make sure a pod that runs with spring-cloud-kubernetes has access to the Kubernetes API. +For any service accounts you assign to a deployment or pod, you need to make sure they have the correct roles. For example, you can add cluster-reader permissions to your default service account, depending on the project you’re in.

11. Examples

Spring Cloud Kubernetes tries to make it transparent for your applications to consume Kubernetes Native Services by +following the Spring Cloud interfaces.

In your applications, you need to add the spring-cloud-kubernetes-discovery dependency to your classpath and remove any other dependency that contains a DiscoveryClient implementation (that is, a Eureka discovery client). +The same applies for PropertySourceLocator, where you need to add to the classpath the spring-cloud-kubernetes-config and remove any other dependency that contains a PropertySourceLocator implementation (that is, a configuration server client).

The following projects highlight the usage of these dependencies and demonstrate how you can use these libraries from any Spring Boot application:

12. Other Resources

This section lists other resources, such as presentations (slides) and videos about Spring Cloud Kubernetes.

Please feel free to submit other resources through pull requests to this repository.

13. Building

13.1 Basic Compile and Test

To build the source you will need to install JDK 1.7.

Spring Cloud uses Maven for most build-related activities, and you should be able to get off the ground quite quickly by cloning the project you are interested in and typing

$ ./mvnw install
[Note]Note

You can also install Maven (>=3.3.3) yourself and run the mvn command in place of ./mvnw in the examples below. If you do that you also @@ -391,4 +394,4 @@ $ touch .springformat

4       └── Intellij_Spring_Boot_Java_Conventions.xml 5

-

3

Default Checkstyle rules

2

File header setup

1

Default suppression rules

4

Project defaults for Intellij that apply most of Checkstyle rules

5

Project style conventions for Intellij that apply most of Checkstyle rules

Figure 14.1. Code style

Code style

Go to FileSettingsEditorCode style. There click on the icon next to the Scheme section. There, click on the Import Scheme value and pick the Intellij IDEA code style XML option. Import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml file.

Figure 14.2. Inspection profiles

Code style

Go to FileSettingsEditorInspections. There click on the icon next to the Profile section. There, click on the Import Profile and import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml file.

Checkstyle. To have Intellij work with Checkstyle, you have to install the Checkstyle plugin. It’s advisable to also install the Assertions2Assertj to automatically convert the JUnit assertions

Checkstyle

Go to FileSettingsOther settingsCheckstyle. There click on the + icon in the Configuration file section. There, you’ll have to define where the checkstyle rules should be picked from. In the image above, we’ve picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build’s GitHub repository (e.g. for the checkstyle.xml : https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml). We need to provide the following variables:

[Important]Important

Remember to set the Scan Scope to All sources since we apply checkstyle rules for production and test sources.

\ No newline at end of file +

3

Default Checkstyle rules

2

File header setup

1

Default suppression rules

4

Project defaults for Intellij that apply most of Checkstyle rules

5

Project style conventions for Intellij that apply most of Checkstyle rules

Figure 14.1. Code style

Code style

Go to FileSettingsEditorCode style. There click on the icon next to the Scheme section. There, click on the Import Scheme value and pick the Intellij IDEA code style XML option. Import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml file.

Figure 14.2. Inspection profiles

Code style

Go to FileSettingsEditorInspections. There click on the icon next to the Profile section. There, click on the Import Profile and import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml file.

Checkstyle. To have Intellij work with Checkstyle, you have to install the Checkstyle plugin. It’s advisable to also install the Assertions2Assertj to automatically convert the JUnit assertions

Checkstyle

Go to FileSettingsOther settingsCheckstyle. There click on the + icon in the Configuration file section. There, you’ll have to define where the checkstyle rules should be picked from. In the image above, we’ve picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build’s GitHub repository (e.g. for the checkstyle.xml : https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml). We need to provide the following variables:

[Important]Important

Remember to set the Scan Scope to All sources since we apply checkstyle rules for production and test sources.

\ No newline at end of file diff --git a/spring-cloud-kubernetes.xml b/spring-cloud-kubernetes.xml index 1111ebd1..321dc75b 100644 --- a/spring-cloud-kubernetes.xml +++ b/spring-cloud-kubernetes.xml @@ -6,10 +6,14 @@ Spring Cloud Kubernetes 2019-02-28 + + +This reference guide covers how to use Spring Cloud Kubernetes. + Why do you need Spring Cloud Kubernetes? -Spring Cloud Kubernetes provide Spring Cloud common interfaces implementations to consume Kubernetes native services. -The main objective of the projects provided in this repository is to facilitate the integration of Spring Cloud/Spring Boot applications running inside Kubernetes. +Spring Cloud Kubernetes provide Spring Cloud common interface implementations that consume Kubernetes native services. +The main objective of the projects provided in this repository is to facilitate the integration of Spring Cloud and Spring Boot applications running inside Kubernetes. Starters @@ -41,8 +45,8 @@ resolves service names to Kubernetes Services. <artifactId>spring-cloud-starter-kubernetes-config</artifactId> </dependency> Load application properties from Kubernetes -ConfigMaps and Secrets. -Reload application properties when a ConfigMap or +ConfigMaps and Secrets. +Reload application properties when a ConfigMap or Secret changes. @@ -50,7 +54,7 @@ Secret changes. <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-kubernetes-ribbon</artifactId> </dependency> -Ribbon client-side load balancer with +Ribbon client-side load balancer with server list obtained from Kubernetes Endpoints. @@ -67,12 +71,20 @@ server list obtained from Kubernetes Endpoints. DiscoveryClient for Kubernetes This project provides an implementation of Discovery Client -for Kubernetes. -This allows you to query Kubernetes endpoints (see services) by name. -A service is typically exposed by the Kubernetes API server as a collection of endpoints which represent http, https addresses that a client can +for Kubernetes. +This client lets you query Kubernetes endpoints (see services) by name. +A service is typically exposed by the Kubernetes API server as a collection of endpoints that represent http and https addresses and that a client can access from a Spring Boot application running as a pod. This discovery feature is also used by the Spring Cloud Kubernetes Ribbon project to fetch the list of the endpoints defined for an application to be load balanced. -To enable loading of the DiscoveryClient, add @EnableDiscoveryClient to the according configuration or application class like this: +This is something that you get for free by adding the following dependency inside your project: + +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-kubernetes</artifactId> +</dependency> + +To enable loading of the DiscoveryClient, add @EnableDiscoveryClient to the according configuration or application class, as the following example shows: + @SpringBootApplication @EnableDiscoveryClient public class Application { @@ -80,48 +92,54 @@ public class Application { SpringApplication.run(Application.class, args); } } -Then you can inject the client in your code simply by: + +Then you can inject the client in your code simply by autowiring it, as the following example shows: + @Autowired private DiscoveryClient discoveryClient; -If for any reason you need to disable the DiscoveryClient you can simply set the following property in application.properties: + +If, for any reason, you need to disable the DiscoveryClient, you can set the following property in application.properties: + spring.cloud.kubernetes.discovery.enabled=false -Some Spring Cloud components use the DiscoveryClient in order to obtain info about the local service instance. For -this to work you need to align the Kubernetes service name with the spring.application.name property. + +Some Spring Cloud components use the DiscoveryClient in order to obtain information about the local service instance. For +this to work, you need to align the Kubernetes service name with the spring.application.name property. Kubernetes native service discovery Kubernetes itself is capable of (server side) service discovery (see: https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services). -Using native kubernetes service discovery ensures compatibility with additional tooling, like: istio https://istio.io (service mesh, capable of load balancing, ribbon, circuit breaker, failover and much more). -The caller service just needs to refer to names resolvable in particular kubernetes cluster then. Simplest implementation might use the spring RestTemplate referring to fully qualified domain name (FQDN) http://{service-name}.{namespace}.svc.{cluster}.local:{service-port}. -Additionally, hystrix can be used for: +Using native kubernetes service discovery ensures compatibility with additional tooling, such as Istio (https://istio.io), a service mesh that is capable of load balancing, ribbon, circuit breaker, failover, and much more. +The caller service then need only refer to names resolvable in a particular Kubernetes cluster. A simple implementation might use a spring RestTemplate that refers to a fully qualified domain name (FQDN), such as https://{service-name}.{namespace}.svc.{cluster}.local:{service-port}. +Additionally, you can use Hystrix for: -circuit breaker implementation on the caller side, just by annotating the spring boot application class: @EnableCircuitBreaker +Circuit breaker implementation on the caller side, by annotating the spring boot application class with @EnableCircuitBreaker -and for the fallback functionality, annotating the respective method via: @HystrixCommand(fallbackMethod= does the job. +Fallback functionality, by annotating the respective method with @HystrixCommand(fallbackMethod= Kubernetes PropertySource implementations -The most common approach to configure your Spring Boot application is to create an application.properties|yaml or -an application-profile.properties|yaml file containing key-value pairs providing customization values to your -application or Spring Boot starters. Users may override these properties by specifying system properties or environment +The most common approach to configuring your Spring Boot application is to create an application.properties or applicaiton.yaml or +an application-profile.properties or application-profile.yaml file that contains key-value pairs that provide customization values to your +application or Spring Boot starters. You can override these properties by specifying system properties or environment variables. -
-ConfigMap PropertySource -Kubernetes provides a resource named ConfigMap to externalize the -parameters to pass to your application in the form of key-value pairs or embedded application.properties|yaml files. -The Spring Cloud Kubernetes Config project makes Kubernetes `ConfigMap`s available +
+Using a <literal>ConfigMap</literal> <literal>PropertySource</literal> +Kubernetes provides a resource named ConfigMap to externalize the +parameters to pass to your application in the form of key-value pairs or embedded application.properties or application.yaml files. +The Spring Cloud Kubernetes Config project makes Kubernetes ConfigMap instances available during application bootstrapping and triggers hot reloading of beans or Spring context when changes are detected on -observed `ConfigMap`s. -The default behavior is to create a ConfigMapPropertySource based on a Kubernetes ConfigMap which has metadata.name of either the name of +observed ConfigMap instances. +The default behavior is to create a ConfigMapPropertySource based on a Kubernetes ConfigMap that has a metadata.name value of either the name of your Spring application (as defined by its spring.application.name property) or a custom name defined within the -bootstrap.properties file under the following key spring.cloud.kubernetes.config.name. -However, more advanced configuration are possible where multiple ConfigMaps can be used -This is made possible by the spring.cloud.kubernetes.config.sources list. -For example one could define the following ConfigMaps +bootstrap.properties file under the following key: spring.cloud.kubernetes.config.name. +However, more advanced configuration is possible where you can use multiple ConfigMap instances. +The spring.cloud.kubernetes.config.sources list makes this possible. +For example, you could define the following ConfigMap instances: + spring: application: name: cloud-k8s-app @@ -131,34 +149,36 @@ For example one could define the following ConfigMaps name: default-name namespace: default-namespace sources: - # Spring Cloud Kubernetes will lookup a ConfigMap named c1 in namespace default-namespace + # Spring Cloud Kubernetes looks up a ConfigMap named c1 in namespace default-namespace - name: c1 - # Spring Cloud Kubernetes will lookup a ConfigMap named default-name in whatever namespace n2 + # Spring Cloud Kubernetes looks up a ConfigMap named default-name in whatever namespace n2 - namespace: n2 - # Spring Cloud Kubernetes will lookup a ConfigMap named c3 in namespace n3 + # Spring Cloud Kubernetes looks up a ConfigMap named c3 in namespace n3 - namespace: n3 name: c3 -In the example above, it spring.cloud.kubernetes.config.namespace had not been set, -then the ConfigMap named c1 would be looked up in the namespace that the application runs -Any matching ConfigMap that is found, will be processed as follows: + +In the preceding example, if spring.cloud.kubernetes.config.namespace had not been set, +the ConfigMap named c1 would be looked up in the namespace that the application runs. +Any matching ConfigMap that is found is processed as follows: -apply individual configuration properties. +Apply individual configuration properties. -apply as yaml the content of any property named application.yaml +Apply as yaml the content of any property named application.yaml. -apply as properties file the content of any property named application.properties +Apply as a properties file the content of any property named application.properties. The single exception to the aforementioned flow is when the ConfigMap contains a single key that indicates -the file is a YAML or Properties file. In that case the name of the key does NOT have to be application.yaml or -application.properties (it can be anything) and the value of the property will be treated correctly. -This features facilitates the use case where the ConfigMap was created using something like: -kubectl create configmap game-config --from-file=/path/to/app-config.yaml -Example: -Let’s assume that we have a Spring Boot application named demo that uses properties to read its thread pool +the file is a YAML or properties file. In that case, the name of the key does NOT have to be application.yaml or +application.properties (it can be anything) and the value of the property is treated correctly. +This features facilitates the use case where the ConfigMap was created by using something like the following: + +kubectl create configmap game-config --from-file=/path/to/app-config.yaml + +Assume that we have a Spring Boot application named demo that uses the following properties to read its thread pool configuration. @@ -168,7 +188,8 @@ configuration. pool.size.maximum -This can be externalized to config map in yaml format: +This can be externalized to config map in yaml format as follows: + kind: ConfigMap apiVersion: v1 metadata: @@ -176,8 +197,10 @@ metadata: data: pool.size.core: 1 pool.size.max: 16 -Individual properties work fine for most cases but sometimes embedded yaml is more convenient. In this case we will -use a single property named application.yaml to embed our yaml: + +Individual properties work fine for most cases. However, sometimes, embedded yaml is more convenient. In this case, we +use a single property named application.yaml to embed our yaml, as follows: + kind: ConfigMap apiVersion: v1 metadata: @@ -188,7 +211,9 @@ data: size: core: 1 max:16 -The following also works: + +The following example also works: + kind: ConfigMap apiVersion: v1 metadata: @@ -199,10 +224,12 @@ data: size: core: 1 max:16 -Spring Boot applications can also be configured differently depending on active profiles which will be merged together -when the ConfigMap is read. It is possible to provide different property values for different profiles using an -application.properties|yaml property, specifying profile-specific values each in their own document -(indicated by the --- sequence) as follows: + +You can also configure Spring Boot applications differently depending on active profiles that are merged together +when the ConfigMap is read. You can provide different property values for different profiles by using an +application.properties or application.yaml property, specifying profile-specific values, each in their own document +(indicated by the --- sequence), as follows: + kind: ConfigMap apiVersion: v1 metadata: @@ -225,20 +252,26 @@ data: profiles: production greeting: message: Say Hello to the Ops -In the above case, the configuration loaded into your Spring Application with the development profile will be: + +In the preceding case, the configuration loaded into your Spring Application with the development profile is as follows: + greeting: message: Say Hello to the Developers farewell: message: Say Goodbye to the Developers -whereas if the production profile is active, the configuration will be: + +However, if the production profile is active, the configuration becomes: + greeting: message: Say Hello to the Ops farewell: message: Say Goodbye -If both profiles are active, the property which appears last within the configmap will overwrite preceding values. -To tell to Spring Boot which profile should be enabled at bootstrap, a system property can be passed to the Java -command launching your Spring Boot application using an env variable that you will define with the OpenShift -DeploymentConfig or Kubernetes ReplicationConfig resource file as follows: + +If both profiles are active, the property that appears last within the ConfigMap overwrites any preceding values. +To tell Spring Boot which profile should be enabled at bootstrap, you can pass a system property to the Java +command. To do so, you can launch your Spring Boot application with an environment variable that you can define with the OpenShift +DeploymentConfig or Kubernetes ReplicationConfig resource file, as follows: + apiVersion: v1 kind: DeploymentConfig spec: @@ -251,16 +284,19 @@ spec: value: /deployments - name: JAVA_OPTIONS value: -Dspring.profiles.active=developer -Notes: -- check the security configuration section, to access config maps from inside a pod you need to have the correct + + +You should check the security configuration section. To access config maps from inside a pod you need to have the correct Kubernetes service accounts, roles and role bindings. -Another option for using ConfigMaps, is to mount them into the Pod running the Spring Cloud Kubernetes application -and have Spring Cloud Kubernetes read them from the file system. -This behavior is controlled by the spring.cloud.kubernetes.config.paths property and can be used in + +Another option for using ConfigMap instances is to mount them into the Pod by running the Spring Cloud Kubernetes application +and having Spring Cloud Kubernetes read them from the file system. +This behavior is controlled by the spring.cloud.kubernetes.config.paths property. You can use it in addition to or instead of the mechanism described earlier. -Multiple (exact) file paths can be specified in spring.cloud.kubernetes.config.paths by using the , delimiter -Notes: -You have to provide full exact path to each property file, because directories are not being recursively parsed. +You can specify multiple (exact) file paths in spring.cloud.kubernetes.config.paths by using the , delimiter. + +You have to provide the full exact path to each property file, because directories are not being recursively parsed. + Properties: @@ -278,36 +314,36 @@ You have to provide full exact path to each property file, because directories a -spring.cloud.kubernetes.config.enabled -Boolean -true -Enable Secrets PropertySource +spring.cloud.kubernetes.config.enabled +Boolean +true +Enable Secrets PropertySource -spring.cloud.kubernetes.config.name -String -${spring.application.name} -Sets the name of ConfigMap to lookup +spring.cloud.kubernetes.config.name +String +${spring.application.name} +Sets the name of ConfigMap to look up -spring.cloud.kubernetes.config.namespace -String +spring.cloud.kubernetes.config.namespace +String Client namespace Sets the Kubernetes namespace where to lookup -spring.cloud.kubernetes.config.paths -List -null -Sets the paths where ConfigMaps are mounted +spring.cloud.kubernetes.config.paths +List +null +Sets the paths where ConfigMap instances are mounted -spring.cloud.kubernetes.config.enableApi -Boolean -true -Enable/Disable consuming ConfigMaps via APIs +spring.cloud.kubernetes.config.enableApi +Boolean +true +Enable or disable consuming ConfigMap instances through APIs @@ -316,30 +352,32 @@ You have to provide full exact path to each property file, because directories a
Secrets PropertySource Kubernetes has the notion of Secrets for storing -sensitive data such as password, OAuth tokens, etc. This project provides integration with Secrets to make secrets -accessible by Spring Boot applications. This feature can be explicitly enabled/disabled using the spring.cloud.kubernetes.secrets.enabled property. -The SecretsPropertySource when enabled will lookup Kubernetes for Secrets from the following sources: +sensitive data such as passwords, OAuth tokens, and so on. This project provides integration with Secrets to make secrets +accessible by Spring Boot applications. You can explicitly enable or disable This feature by setting the spring.cloud.kubernetes.secrets.enabled property. +When enabled, the SecretsPropertySource looks up Kubernetes for Secrets from the following sources: -reading recursively from secrets mounts +Reading recursively from secrets mounts -named after the application (as defined by spring.application.name) +Named after the application (as defined by spring.application.name) -matching some labels +Matching some labels -Please note that by default, consuming Secrets via API (points 2 and 3 above) is not enabled for security reasons -and it is recommended that containers share secrets via mounted volumes. -If you enable consuming Secrets via API, then it is recommended access to Secrets is limited by an -[authorization policy such as RBAC](https://kubernetes.io/docs/concepts/configuration/secret/#best-practices). -If the secrets are found their data is made available to the application. -Example: -Let’s assume that we have a spring boot application named demo that uses properties to read its database -configuration. We can create a Kubernetes secret using the following command: +Note that, by default, consuming Secrets through the API (points 2 and 3 above) is not enabled for security reasons. +Further, we recommend that containers share secrets through mounted volumes. +If you enable consuming Secrets through the API, we recommend that you limit access to Secrets by using an +[authorization policy, such as RBAC](https://kubernetes.io/docs/concepts/configuration/secret/#best-practices). +If the secrets are found, their data is made available to the application. +Assume that we have a spring boot application named demo that uses properties to read its database +configuration. We can create a Kubernetes secret by using the following command: + oc create secret generic db-secret --from-literal=username=user --from-literal=password=p455w0rd -This would create the following secret (shown using oc get secrets db-secret -o yaml): + +The preceding command would create the following secret (which you can see by using oc get secrets db-secret -o yaml): + apiVersion: v1 data: password: cDQ1NXcwcmQ= @@ -353,8 +391,10 @@ metadata: selfLink: /api/v1/namespaces/default/secrets/db-secret uid: 63c89263-6099-11e7-b3da-76d6186905a8 type: Opaque -Note that the data contains Base64-encoded versions of the literal provided by the create command. -This secret can then be used by your application for example by exporting the secret’s value as environment variables: + +Note that the data contains Base64-encoded versions of the literal provided by the create command. +Your application can then use this secret — for example, by exporting the secret’s value as environment variables: + apiVersion: v1 kind: Deployment metadata: @@ -374,22 +414,31 @@ spec: secretKeyRef: name: db-secret key: password + You can select the Secrets to consume in a number of ways: By listing the directories where secrets are mapped: --Dspring.cloud.kubernetes.secrets.paths=/etc/secrets/db-secret,etc/secrets/postgresql + +-Dspring.cloud.kubernetes.secrets.paths=/etc/secrets/db-secret,etc/secrets/postgresql + If you have all the secrets mapped to a common root, you can set them like: --Dspring.cloud.kubernetes.secrets.paths=/etc/secrets + +-Dspring.cloud.kubernetes.secrets.paths=/etc/secrets + By setting a named secret: --Dspring.cloud.kubernetes.secrets.name=db-secret + +-Dspring.cloud.kubernetes.secrets.name=db-secret + By defining a list of labels: --Dspring.cloud.kubernetes.secrets.labels.broker=activemq --Dspring.cloud.kubernetes.secrets.labels.db=postgresql + +-Dspring.cloud.kubernetes.secrets.labels.broker=activemq +-Dspring.cloud.kubernetes.secrets.labels.db=postgresql +
@@ -409,72 +458,71 @@ spec: -spring.cloud.kubernetes.secrets.enabled -Boolean -true -Enable Secrets PropertySource +spring.cloud.kubernetes.secrets.enabled +Boolean +true +Enable Secrets PropertySource -spring.cloud.kubernetes.secrets.name -String -${spring.application.name} -Sets the name of the secret to lookup +spring.cloud.kubernetes.secrets.name +String +${spring.application.name} +Sets the name of the secret to look up -spring.cloud.kubernetes.secrets.namespace -String +spring.cloud.kubernetes.secrets.namespace +String Client namespace -Sets the Kubernetes namespace where to lookup +Sets the Kubernetes namespace where to look up -spring.cloud.kubernetes.secrets.labels -Map -null +spring.cloud.kubernetes.secrets.labels +Map +null Sets the labels used to lookup secrets -spring.cloud.kubernetes.secrets.paths -List -null +spring.cloud.kubernetes.secrets.paths +List +null Sets the paths where secrets are mounted (example 1) -spring.cloud.kubernetes.secrets.enableApi -Boolean -false -Enable/Disable consuming secrets via APIs (examples 2 and 3) +spring.cloud.kubernetes.secrets.enableApi +Boolean +false +Enables or disables consuming secrets through APIs (examples 2 and 3)
-Notes: -- The property spring.cloud.kubernetes.secrets.labels behaves as defined by +Notes: +* The spring.cloud.kubernetes.secrets.labels property behaves as defined by Map-based binding. -- The property spring.cloud.kubernetes.secrets.paths behaves as defined by +* The spring.cloud.kubernetes.secrets.paths property behaves as defined by Collection-based binding. -- Access to secrets via API may be restricted for security reasons, the preferred way is to mount secret to the POD. -Example of application using secrets (though it hasn’t been updated to use the new spring-cloud-kubernetes project): +* Access to secrets through the API may be restricted for security reasons. The preferred way is to mount secrets to the Pod. +You can find an example of an application that uses secrets (though it has not been updated to use the new spring-cloud-kubernetes project) at spring-boot-camel-config
-PropertySource Reload +<literal>PropertySource</literal> Reload Some applications may need to detect changes on external property sources and update their internal status to reflect the new configuration. The reload feature of Spring Cloud Kubernetes is able to trigger an application reload when a related ConfigMap or Secret changes. -This feature is disabled by default and can be enabled using the configuration property spring.cloud.kubernetes.reload.enabled=true - (eg. in the application.properties file). -The following levels of reload are supported (property spring.cloud.kubernetes.reload.strategy): -- refresh (default): only configuration beans annotated with @ConfigurationProperties or @RefreshScope are reloaded. +By default, this feature is disabled. You can enable it by using the spring.cloud.kubernetes.reload.enabled=true configuration property (for example, in the application.properties file). +The following levels of reload are supported (by setting the spring.cloud.kubernetes.reload.strategy property): +* refresh (default): Only configuration beans annotated with @ConfigurationProperties or @RefreshScope are reloaded. This reload level leverages the refresh feature of Spring Cloud Context. -- restart_context: the whole Spring ApplicationContext is gracefully restarted. Beans are recreated with the new configuration. -- shutdown: the Spring ApplicationContext is shut down to activate a restart of the container. - When using this level, make sure that the lifecycle of all non-daemon threads is bound to the ApplicationContext - and that a replication controller or replica set is configured to restart the pod. -Example: -Assuming that the reload feature is enabled with default settings (refresh mode), the following bean will be refreshed when the config map changes: -@Configuration +* restart_context: the whole Spring ApplicationContext is gracefully restarted. Beans are recreated with the new configuration. +* shutdown: the Spring ApplicationContext is shut down to activate a restart of the container. + When you use this level, make sure that the lifecycle of all non-daemon threads is bound to the ApplicationContext +and that a replication controller or replica set is configured to restart the pod. +Assuming that the reload feature is enabled with default settings (refresh mode), the following bean is refreshed when the config map changes: + +@Configuration @ConfigurationProperties(prefix = "bean") public class MyConfig { @@ -482,8 +530,10 @@ public class MyConfig { // getter and setters -} -A way to see that changes effectively happen is creating another bean that prints the message periodically. +} + +To see that changes effectively happen, you can create another bean that prints the message periodically, as follows + @Component public class MyBean { @@ -495,7 +545,9 @@ public class MyBean { System.out.println("The message is: " + config.getMessage()); } } -The message printed by the application can be changed using a ConfigMap as follows: + +You can change the message printed by the application by using a ConfigMap, as follows: + apiVersion: v1 kind: ConfigMap metadata: @@ -503,20 +555,21 @@ metadata: data: application.properties: |- bean.message=Hello World! -Any change to the property named bean.message in the ConfigMap associated to the pod will be reflected in the + +Any change to the property named bean.message in the ConfigMap associated with the pod is reflected in the output. More generally speaking, changes associated to properties prefixed with the value defined by the prefix -field of the @ConfigurationProperties annotation will be detected and reflected in the application. -[Associating a ConfigMap to a pod](#configmap-propertysource) is explained above. -The full example is available in [spring-cloud-kubernetes-reload-example](spring-cloud-kubernetes-examples/kubernetes-reload-example). +field of the @ConfigurationProperties annotation are detected and reflected in the application. +Associating a ConfigMap with a pod is explained earlier in this chapter. +The full example is available in spring-cloud-kubernetes-reload-example. The reload feature supports two operating modes: -- event (default): watches for changes in config maps or secrets using the Kubernetes API (web socket). -Any event will produce a re-check on the configuration and a reload in case of changes. -The view role on the service account is required in order to listen for config map changes. A higher level role (eg. edit) is required for secrets -(secrets are not monitored by default). -- polling: re-creates the configuration periodically from config maps and secrets to see if it has changed. -The polling period can be configured using the property spring.cloud.kubernetes.reload.period and defaults to 15 seconds. +* Event (default): Watches for changes in config maps or secrets by using the Kubernetes API (web socket). +Any event produces a re-check on the configuration and, in case of changes, a reload. +The view role on the service account is required in order to listen for config map changes. A higher level role (such as edit) is required for secrets +(by default, secrets are not monitored). +* Polling: Oeriodically re-creates the configuration from config maps and secrets to see if it has changed. +You can configure the polling period by using the spring.cloud.kubernetes.reload.period property and defaults to 15 seconds. It requires the same role as the monitored property source. -This means, for example, that using polling on file mounted secret sources does not require particular privileges. +This means, for example, that using polling on file-mounted secret sources does not require particular privileges. Properties: @@ -534,80 +587,90 @@ This means, for example, that using polling on file mounted secret sources does -spring.cloud.kubernetes.reload.enabled -Boolean -false +spring.cloud.kubernetes.reload.enabled +Boolean +false Enables monitoring of property sources and configuration reload -spring.cloud.kubernetes.reload.monitoring-config-maps -Boolean -true +spring.cloud.kubernetes.reload.monitoring-config-maps +Boolean +true Allow monitoring changes in config maps -spring.cloud.kubernetes.reload.monitoring-secrets -Boolean -false +spring.cloud.kubernetes.reload.monitoring-secrets +Boolean +false Allow monitoring changes in secrets -spring.cloud.kubernetes.reload.strategy -Enum -refresh -The strategy to use when firing a reload (refresh, restart_context, shutdown) +`spring.cloud.kubernetes.reload.strategy ` +Enum +refresh +The strategy to use when firing a reload (refresh, restart_context, or shutdown) -spring.cloud.kubernetes.reload.mode -Enum -event -Specifies how to listen for changes in property sources (event, polling) +spring.cloud.kubernetes.reload.mode +Enum +event +Specifies how to listen for changes in property sources (event or polling) -spring.cloud.kubernetes.reload.period -Duration -15s -The period for verifying changes when using the polling strategy +spring.cloud.kubernetes.reload.period +Duration +15s +The period for verifying changes when using the polling strategy
-Notes: -- Properties under spring.cloud.kubernetes.reload. should not be used in config maps or secrets: changing such properties at runtime may lead to unexpected results; -- Deleting a property or the whole config map does not restore the original state of the beans when using the refresh level. +Notes: +* You should not use properties under spring.cloud.kubernetes.reload in config maps or secrets. Changing such properties at runtime may lead to unexpected results. +* Deleting a property or the whole config map does not restore the original state of the beans when you use the refresh level.
-Ribbon discovery in Kubernetes -Spring Cloud client applications calling a microservice should be interested on relying on a client load-balancing +Ribbon Discovery in Kubernetes +Spring Cloud client applications that call a microservice should be interested on relying on a client load-balancing feature in order to automatically discover at which endpoint(s) it can reach a given service. This mechanism has been -implemented within the [spring-cloud-kubernetes-ribbon](spring-cloud-kubernetes-ribbon/pom.xml) project where a -Kubernetes client will populate a Ribbon ServerList containing information +implemented within the spring-cloud-kubernetes-ribbon project, where a +Kubernetes client populates a Ribbon ServerList that contains information about such endpoints. -When the list of the endpoints is populated, the Kubernetes client will search the registered endpoints living in -the current namespace/project matching the service name defined using the Ribbon Client annotation: +The implementation is part of the following starter that you can use by adding its dependency to your pom file: + +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-kubernetes-ribbon</artifactId> + <version>${latest.version}</version> +</dependency> + +When the list of the endpoints is populated, the Kubernetes client searches the registered endpoints that live in +the current namespace or project by matching the service name defined in the Ribbon Client annotation, as follows: + @RibbonClient(name = "name-service") -You can configure Ribbon’s behavior by providing properties in your application.properties (via your application’s -dedicated ConfigMap) using the following format: <name of your service>.ribbon.<Ribbon configuration key> where: + +You can configure Ribbon’s behavior by providing properties in your application.properties (through your application’s +dedicated ConfigMap) by using the following format: <name of your service>.ribbon.<Ribbon configuration key>, where: -<name of your service> corresponds to the service name you’re accessing over Ribbon, as configured using the -@RibbonClient annotation (e.g. name-service in the example above) +<name of your service> corresponds to the service name you access over Ribbon, as configured by using the +@RibbonClient annotation (such as name-service in the preceding example). -<Ribbon configuration key> is one of the Ribbon configuration key defined by -Ribbon’s CommonClientConfigKey class +<Ribbon configuration key> is one of the Ribbon configuration keys defined by +Ribbon’s CommonClientConfigKey class. Additionally, the spring-cloud-kubernetes-ribbon project defines two additional configuration keys to further control how Ribbon interacts with Kubernetes. In particular, if an endpoint defines multiple ports, the default -behavior is to use the first one found. To select more specifically which port to use, in a multi-port service, use -the PortName key. If you want to specify in which Kubernetes' namespace the target service should be looked up, use +behavior is to use the first one found. To select more specifically which port to use in a multi-port service, you can use +the PortName key. If you want to specify in which Kubernetes namespace the target service should be looked up, you can use the KubernetesNamespace key, remembering in both instances to prefix these keys with your service name and -ribbon prefix as specified above. -Examples that are using this module for ribbon discovery are: +ribbon prefix, as specified earlier. +The following examples use this module for ribbon discovery: Spring Cloud Circuitbreaker and Ribbon @@ -619,44 +682,45 @@ the KubernetesNamespace key, remembering in both instances to Kubeflix - LoanBroker - Bank -Note: The Ribbon discovery client can be disabled by setting this key within the application properties file -spring.cloud.kubernetes.ribbon.enabled=false. + +You can disable the Ribbon discovery client by setting the spring.cloud.kubernetes.ribbon.enabled=false key within the application properties file. + Kubernetes Ecosystem Awareness -All of the features described above will work equally well regardless of whether your application is running inside -Kubernetes or not. This is really helpful for development and troubleshooting. -From a development point of view, this is really helpful as you can start your Spring Boot application and debug one -of the modules part of this project. It is not required to deploy it in Kubernetes +All of the features described earlier in this guide work equally well, regardless of whether your application is running inside +Kubernetes. This is really helpful for development and troubleshooting. +From a development point of view, this lets you start your Spring Boot application and debug one +of the modules that is part of this project. You need not deploy it in Kubernetes, as the code of the project relies on the -Fabric8 Kubernetes Java client which is a fluent DSL able to -communicate using http protocol to the REST API of Kubernetes Server. +Fabric8 Kubernetes Java client, which is a fluent DSL that can +communicate by using http protocol to the REST API of the Kubernetes Server.
Kubernetes Profile Autoconfiguration -When the application runs as a pod inside Kubernetes a Spring profile named kubernetes will automatically get activated. -This allows the developer to customize the configuration, to define beans that will be applied when the Spring Boot application is deployed -within the Kubernetes platform (e.g. different dev and prod configuration). +When the application runs as a pod inside Kubernetes, a Spring profile named kubernetes automatically gets activated. +This lets you customize the configuration, to define beans that are applied when the Spring Boot application is deployed +within the Kubernetes platform (for example, different development and production configuration).
Istio Awareness -When including the spring-cloud-kubernetes-istio module into the application classpath a new profile will be added to the application, -if the application is running inside a Kubernetes Cluster with Istio installed. Then you can use -spring @Profile("istio") annotations into your Beans and @Configuration's. -The Istio awareness module uses the me.snowdrop:istio-client to interact with Istio APIs enabling us to discover traffic rules, circuit breakers, etc. -Making it easy for our Spring Boot applications to consume this data to dynamically configure themselves according the environment. +When you include the spring-cloud-kubernetes-istio module in the application classpath, a new profile is added to the application, +provided the application is running inside a Kubernetes Cluster with Istio installed. You can then use +spring @Profile("istio") annotations in your Beans and @Configuration classes. +The Istio awareness module uses me.snowdrop:istio-client to interact with Istio APIs, letting us discover traffic rules, circuit breakers, and so on, +making it easy for our Spring Boot applications to consume this data to dynamically configure themselves according to the environment.
Pod Health Indicator -Spring Boot uses HealthIndicator to expose info about the health of an application. -That makes it really useful for exposing health related information to the user and are also a good fit for use as readiness probes. -The Kubernetes health indicator which is part of the core module exposes the following info: +Spring Boot uses HealthIndicator to expose info about the health of an application. +That makes it really useful for exposing health-related information to the user and makes it a good fit for use as readiness probes. +The Kubernetes health indicator (which is part of the core module) exposes the following info: -pod name, ip address, namespace, service account, node name and its ip address +Pod name, IP address, namespace, service account, node name, and its IP address -flag that indicates if the Spring Boot application is internal or external to Kubernetes +A flag that indicates whether the Spring Boot application is internal or external to Kubernetes @@ -665,44 +729,47 @@ That makes it really useful for exposing health related information to the user <TBD> -Security Configurations inside Kubernetes +Security Configurations Inside Kubernetes
Namespace -Most of the components provided in this project need to know the namespace. For Kubernetes (1.3+) the namespace is made available to pod as part of the service account secret and automatically detected by the client. -For earlier version it needs to be specified as an env var to the pod. A quick way to do this is: -env: -- name: "KUBERNETES_NAMESPACE" - valueFrom: - fieldRef: - fieldPath: "metadata.namespace" +Most of the components provided in this project need to know the namespace. For Kubernetes (1.3+), the namespace is made available to the pod as part of the service account secret and is automatically detected by the client. +For earlier versions, it needs to be specified as an environment variable to the pod. A quick way to do this is as follows: + + env: + - name: "KUBERNETES_NAMESPACE" + valueFrom: + fieldRef: + fieldPath: "metadata.namespace" +
Service Account -For distros of Kubernetes that support more fine-grained role-based access within the cluster, you need to make sure a pod that runs with spring-cloud-kubernetes has access to the Kubernetes API. -For any service accounts you assign to a deployment/pod, you need to make sure it has the correct roles. For example, you can add cluster-reader permissions to your default service account depending on the project you’re in: +For distributions of Kubernetes that support more fine-grained role-based access within the cluster, you need to make sure a pod that runs with spring-cloud-kubernetes has access to the Kubernetes API. +For any service accounts you assign to a deployment or pod, you need to make sure they have the correct roles. For example, you can add cluster-reader permissions to your default service account, depending on the project you’re in.
Examples -Spring Cloud Kubernetes tries to make it transparent for your applications to consume Kubernetes Native Services +Spring Cloud Kubernetes tries to make it transparent for your applications to consume Kubernetes Native Services by following the Spring Cloud interfaces. -In your applications, you need to add the spring-cloud-kubernetes-discovery dependency to your classpath and remove any other dependency that contains a DiscoveryClient implementation (ie. Eureka Discovery Client). -The same applies for PropertySourceLocator, where you need to add to the classpath the spring-cloud-kubernetes-config and remove any other dependency that contains a PropertySourceLocator implementation (ie. Config Server Client). -The following projects highlight the usage of these dependencies and demonstrate how these libraries can be used from any Spring Boot application. -List of examples using these projects: +In your applications, you need to add the spring-cloud-kubernetes-discovery dependency to your classpath and remove any other dependency that contains a DiscoveryClient implementation (that is, a Eureka discovery client). +The same applies for PropertySourceLocator, where you need to add to the classpath the spring-cloud-kubernetes-config and remove any other dependency that contains a PropertySourceLocator implementation (that is, a configuration server client). +The following projects highlight the usage of these dependencies and demonstrate how you can use these libraries from any Spring Boot application: Spring Cloud Kubernetes Examples: the ones located inside this repository. Spring Cloud Kubernetes Full Example: Minions and Boss - + Minion Boss + + Spring Cloud Kubernetes Full Example: SpringOne Platform Tickets Service @@ -716,7 +783,7 @@ The same applies for PropertySourceLocator, where you need to add to the classpa Other Resources -Here you can find other resources such as presentations(slides) and videos about Spring Cloud Kubernetes. +This section lists other resources, such as presentations (slides) and videos about Spring Cloud Kubernetes. S1P Spring Cloud on PKS @@ -725,7 +792,7 @@ The same applies for PropertySourceLocator, where you need to add to the classpa Spring Cloud, Docker, Kubernetes → London Java Community July 2018 -Please feel free to submit other resources via PR to this repository. +Please feel free to submit other resources through pull requests to this repository. Building