spring-cloud-kubernetes.md 94.6 KB
Newer Older
M
Mao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
Spring Cloud Kubernetes
==========


This reference guide covers how to use Spring Cloud Kubernetes.

[](#why-do-you-need-spring-cloud-kubernetes)[1. Why do you need Spring Cloud Kubernetes?](#why-do-you-need-spring-cloud-kubernetes)
----------

Spring Cloud Kubernetes provides implementations of well known Spring Cloud interfaces allowing developers to build and run Spring Cloud applications on Kubernetes. While this project may be useful to you when building a cloud native application, it is also not a requirement in order to deploy a Spring Boot app on Kubernetes. If you are just getting started in your journey to running your Spring Boot app on Kubernetes you can accomplish a lot with nothing more than a basic Spring Boot app and Kubernetes itself. To learn more, you can get started by reading the [Spring Boot reference documentation for deploying to Kubernetes ](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#cloud-deployment-kubernetes) and also working through the workshop material [Spring and Kubernetes](https://hackmd.io/@ryanjbaxter/spring-on-k8s-workshop).

[](#starters)[2. Starters](#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. Starters that begin with `spring-cloud-starter-kubernetes-fabric8`provide implementations using the [Fabric8 Kubernetes Java Client](https://github.com/fabric8io/kubernetes-client).
Starters that begin with`spring-cloud-starter-kubernetes-client` provide implementations using the [Kubernetes Java Client](https://github.com/kubernetes-client/java).

|                                                                                                                                                                                                                     Starter                                                                                                                                                                                                                     |                                                                                                        Features                                                                                                         |
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|       Fabric8 Dependency<br/><br/>```<br/><dependency><br/>    <groupId>org.springframework.cloud</groupId><br/>    <artifactId>spring-cloud-starter-kubernetes-fabric8</artifactId><br/></dependency><br/>```<br/><br/>Kubernetes Client Dependency<br/><br/>```<br/><dependency><br/>    <groupId>org.springframework.cloud</groupId><br/>    <artifactId>spring-cloud-starter-kubernetes-client</artifactId><br/></dependency><br/>```       |                                               [Discovery Client](#discoveryclient-for-kubernetes) implementation that<br/>resolves service names to Kubernetes Services.                                                |
|Fabric8 Dependency<br/><br/>```<br/><dependency><br/>    <groupId>org.springframework.cloud</groupId><br/>    <artifactId>spring-cloud-starter-kubernetes-fabric8-config</artifactId><br/></dependency><br/>```<br/><br/>Kubernetes Client Dependency<br/><br/>```<br/><dependency><br/>    <groupId>org.springframework.cloud</groupId><br/>    <artifactId>spring-cloud-starter-kubernetes-client-config</artifactId><br/></dependency><br/>```|Load application properties from Kubernetes[ConfigMaps](#configmap-propertysource) and [Secrets](#secrets-propertysource).[Reload](#propertysource-reload) application properties when a ConfigMap or<br/>Secret changes.|
|   Fabric8 Dependency<br/><br/>```<br/><dependency><br/>    <groupId>org.springframework.cloud</groupId><br/>    <artifactId>spring-cloud-starter-kubernetes-fabric8-all</artifactId><br/></dependency><br/>```<br/><br/>Kubernetes Client Dependency<br/><br/>```<br/><dependency><br/>    <groupId>org.springframework.cloud</groupId><br/>    <artifactId>spring-cloud-starter-kubernetes-client-all</artifactId><br/></dependency><br/>```   |                                                                                          All Spring Cloud Kubernetes features.                                                                                          |

[](#discoveryclient-for-kubernetes)[3. DiscoveryClient for Kubernetes](#discoveryclient-for-kubernetes)
----------

This project provides an implementation of [Discovery Client](https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/DiscoveryClient.java)for [Kubernetes](https://kubernetes.io).
This client lets you query Kubernetes endpoints (see [services](https://kubernetes.io/docs/user-guide/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 is something that you get for free by adding the following dependency inside your project:

HTTP Based `DiscoveryClient`

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

|   |`spring-cloud-starter-kubernetes-discoveryclient` is designed to be used with the[Spring Cloud Kubernetes DiscoveryServer](#spring-cloud-kubernetes-discoveryserver).|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Fabric8 Kubernetes Client

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

Kubernetes Java Client

```
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-kubernetes-client</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 autowiring it, as the following example shows:

```
@Autowired
private DiscoveryClient discoveryClient;
```

You can choose to enable `DiscoveryClient` from all namespaces by setting the following property in `application.properties`:

```
spring.cloud.kubernetes.discovery.all-namespaces=true
```

To discover service endpoint addresses that are not marked as "ready" by the kubernetes api server, you can set the following property in `application.properties` (default: false):

```
spring.cloud.kubernetes.discovery.include-not-ready-addresses=true
```

|   |This might be useful when discovering services for monitoring purposes, and would enable inspecting the `/health` endpoint of not-ready service instances.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------|

If your service exposes multiple ports, you will need to specify which port the `DiscoveryClient` should use.
The `DiscoveryClient` will choose the port using the following logic.

1. If the service has a label `primary-port-name` it will use the port with the name specified in the label’s value.

2. If no label is present, then the port name specified in `spring.cloud.kubernetes.discovery.primary-port-name` will be used.

3. If neither of the above are specified it will use the port named `https`.

4. If none of the above conditions are met it will use the port named `http`.

5. As a last resort it wil pick the first port in the list of ports.

|   |The last option may result in non-deterministic behaviour.<br/>Please make sure to configure your service and/or application accordingly.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------|

By default all of the ports and their names will be added to the metadata of the `ServiceInstance`.

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.

|   |`spring.application.name` has no effect as far as the name registered for the application within Kubernetes|
|---|-----------------------------------------------------------------------------------------------------------|

Spring Cloud Kubernetes can also watch the Kubernetes service catalog for changes and update the`DiscoveryClient` implementation accordingly. In order to enable this functionality you need to add`@EnableScheduling` on a configuration class in your application.

[](#kubernetes-native-service-discovery)[4. Kubernetes native service discovery](#kubernetes-native-service-discovery)
----------

Kubernetes itself is capable of (server side) service discovery (see: [kubernetes.io/docs/concepts/services-networking/service/#discovering-services](https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services)).
Using native kubernetes service discovery ensures compatibility with additional tooling, such as Istio ([istio.io](https://istio.io)), a service mesh that is capable of load balancing, 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 `[{service-name}.{namespace}.svc.{cluster}.local:{service-port}](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=`

[](#kubernetes-propertysource-implementations)[5. Kubernetes PropertySource implementations](#kubernetes-propertysource-implementations)
----------

The most common approach to configuring your Spring Boot application is to create an `application.properties` or `application.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)[5.1. Using a `ConfigMap` `PropertySource`](#configmap-propertysource) ###

Kubernetes provides a resource named [`ConfigMap`](https://kubernetes.io/docs/user-guide/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](https://github.com/spring-cloud/spring-cloud-kubernetes/tree/master/spring-cloud-kubernetes-fabric8-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` instances.

The default behavior is to create a `Fabric8ConfigMapPropertySource` 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 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:
    kubernetes:
      config:
        name: default-name
        namespace: default-namespace
        sources:
         # Spring Cloud Kubernetes looks up a ConfigMap named c1 in namespace default-namespace
         - name: c1
         # Spring Cloud Kubernetes looks up a ConfigMap named default-name in whatever namespace n2
         - namespace: n2
         # Spring Cloud Kubernetes looks up a ConfigMap named c3 in namespace n3
         - namespace: n3
           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.
See [Namespace resolution](#namespace-resolution) to get a better understanding of how the namespace
of the application is resolved.

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. 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
data:
  application.yaml: |-
    pool:
      size:
        core: 1
        max:16
```

The following example also works:

```
kind: ConfigMap
apiVersion: v1
metadata:
  name: demo
data:
  custom-name.yaml: |-
    pool:
      size:
        core: 1
        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
data:
  application.yml: |-
    greeting:
      message: Say Hello to the World
    farewell:
      message: Say Goodbye
    ---
    spring:
      profiles: development
    greeting:
      message: Say Hello to the Developers
    farewell:
      message: Say Goodbye to the Developers
    ---
    spring:
      profiles: production
    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
```

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 that appears last within the `ConfigMap` overwrites any preceding values.

Another option is to create a different config map per profile and spring boot will automatically fetch it based
on active profiles

```
kind: ConfigMap
apiVersion: v1
metadata:
  name: demo
data:
  application.yml: |-
    greeting:
      message: Say Hello to the World
    farewell:
      message: Say Goodbye
```

```
kind: ConfigMap
apiVersion: v1
metadata:
  name: demo-development
data:
  application.yml: |-
    spring:
      profiles: development
    greeting:
      message: Say Hello to the Developers
    farewell:
      message: Say Goodbye to the Developers
```

```
kind: ConfigMap
apiVersion: v1
metadata:
  name: demo-production
data:
  application.yml: |-
    spring:
      profiles: production
    greeting:
      message: Say Hello to the Ops
    farewell:
      message: Say Goodbye
```

To tell Spring Boot which `profile` should be enabled at bootstrap, you can pass `SPRING_PROFILES_ACTIVE` environment variable.
To do so, you can launch your Spring Boot application with an environment variable that you can define it in the PodSpec at the container specification.
Deployment resource file, as follows:

```
apiVersion: apps/v1
kind: Deployment
metadata:
  name: deployment-name
  labels:
    app: deployment-name
spec:
  replicas: 1
  selector:
    matchLabels:
      app: deployment-name
  template:
    metadata:
      labels:
        app: deployment-name
    spec:
        containers:
        - name: container-name
          image: your-image
          env:
          - name: SPRING_PROFILES_ACTIVE
            value: "development"
```

You could run into a situation where there are multiple configs maps that have the same property names. For example:

```
kind: ConfigMap
apiVersion: v1
metadata:
  name: config-map-one
data:
  application.yml: |-
    greeting:
      message: Say Hello from one
```

and

```
kind: ConfigMap
apiVersion: v1
metadata:
  name: config-map-two
data:
  application.yml: |-
    greeting:
      message: Say Hello from two
```

Depending on the order in which you place these in `bootstrap.yaml|properties`, you might end up with an un-expected result (the last config map wins). For example:

```
spring:
  application:
    name: cloud-k8s-app
  cloud:
    kubernetes:
      config:
        namespace: default-namespace
        sources:
         - name: config-map-two
         - name: config-map-one
```

will result in property `greetings.message` being `Say Hello from one`.

There is a way to change this default configuration by specifying `useNameAsPrefix`. For example:

```
spring:
  application:
    name: with-prefix
  cloud:
    kubernetes:
      config:
        useNameAsPrefix: true
        namespace: default-namespace
        sources:
          - name: config-map-one
            useNameAsPrefix: false
          - name: config-map-two
```

Such a configuration will result in two properties being generated:

* `greetings.message` equal to `Say Hello from one`.

* `config-map-two.greetings.message` equal to `Say Hello from two`

Notice that `spring.cloud.kubernetes.config.useNameAsPrefix` has a *lower* priority than `spring.cloud.kubernetes.config.sources.useNameAsPrefix`.
This allows you to set a "default" strategy for all sources, at the same time allowing to override only a few.

If using the config map name is not an option, you can specify a different strategy, called : `explicitPrefix`. Since this is an *explicit* prefix that
you select, it can only be supplied to the `sources` level. At the same time it has a higher priority than `useNameAsPrefix`. Let’s suppose we have a third config map with these entries:

```
kind: ConfigMap
apiVersion: v1
metadata:
  name: config-map-three
data:
  application.yml: |-
    greeting:
      message: Say Hello from three
```

A configuration like the one below:

```
spring:
  application:
    name: with-prefix
  cloud:
    kubernetes:
      config:
        useNameAsPrefix: true
        namespace: default-namespace
        sources:
          - name: config-map-one
            useNameAsPrefix: false
          - name: config-map-two
            explicitPrefix: two
          - name: config-map-three
```

will result in three properties being generated:

* `greetings.message` equal to `Say Hello from one`.

* `two.greetings.message` equal to `Say Hello from two`.

* `config-map-three.greetings.message` equal to `Say Hello from three`.

By default, besides reading the config map that is specified in the `sources` configuration, Spring will also try to read
all properties from "profile aware" sources. The easiest way to explain this is via an example. Let’s suppose your application
enables a profile called "dev" and you have a configuration like the one below:

```
spring:
  application:
    name: spring-k8s
  cloud:
    kubernetes:
      config:
        namespace: default-namespace
        sources:
          - name: config-map-one
```

Besides reading the `config-map-one`, Spring will also try to read `config-map-one-dev`; in this particular order. Each active profile
generates such a profile aware config map.

Though your application should not be impacted by such a config map, it can be disabled if needed:

```
spring:
  application:
    name: spring-k8s
  cloud:
    kubernetes:
      config:
        includeProfileSpecificSources: false
        namespace: default-namespace
        sources:
          - name: config-map-one
            includeProfileSpecificSources: false
```

Notice that just like before, there are two levels where you can specify this property: for all config maps or
for individual ones; the latter having a higher priority.

|   |You should check the security configuration section. To access config maps from inside a pod you need to have the correct<br/>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.
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.|
|---|--------------------------------------------------------------------------------------------------------------------|

|   |If you use `spring.cloud.kubernetes.config.paths` or `spring.cloud.kubernetes.secrets.path` the automatic reload<br/>functionality will not work. You will need to make a `POST` request to the `/actuator/refresh` endpoint or<br/>restart/redeploy the application.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

In some cases, your application may be unable to load some of your `ConfigMaps` using the Kubernetes API.
If you want your application to fail the start-up process in such cases, you can set`spring.cloud.kubernetes.config.fail-fast=true` to make the application start-up fail with an Exception.

You can also make your application retry loading `ConfigMap` property sources on a failure. First, you need to
set `spring.cloud.kubernetes.config.fail-fast=true`. Then you need to add `spring-retry`and `spring-boot-starter-aop` to your classpath. You can configure retry properties such as
the maximum number of attempts, backoff options like initial interval, multiplier, max interval by setting the`spring.cloud.kubernetes.config.retry.*` properties.

|   |If you already have `spring-retry` and `spring-boot-starter-aop` on the classpath for some reason<br/>and want to enable fail-fast, but do not want retry to be enabled; you can disable retry for `ConfigMap` `PropertySources`by setting `spring.cloud.kubernetes.config.retry.enabled=false`.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|                         Name                          |  Type   |          Default           |                                             Description                                             |
|-------------------------------------------------------|---------|----------------------------|-----------------------------------------------------------------------------------------------------|
|       `spring.cloud.kubernetes.config.enabled`        |`Boolean`|           `true`           |                                 Enable ConfigMaps `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                        |
|      `spring.cloud.kubernetes.config.enableApi`       |`Boolean`|           `true`           |                   Enable or disable consuming `ConfigMap` instances through APIs                    |
|      `spring.cloud.kubernetes.config.fail-fast`       |`Boolean`|          `false`           |Enable or disable failing the application start-up when an error occurred while loading a `ConfigMap`|
|    `spring.cloud.kubernetes.config.retry.enabled`     |`Boolean`|           `true`           |                                   Enable or disable config retry.                                   |
|`spring.cloud.kubernetes.config.retry.initial-interval`| `Long`  |           `1000`           |                               Initial retry interval in milliseconds.                               |
|  `spring.cloud.kubernetes.config.retry.max-attempts`  |`Integer`|            `6`             |                                     Maximum number of attempts.                                     |
|  `spring.cloud.kubernetes.config.retry.max-interval`  | `Long`  |           `2000`           |                                    Maximum interval for backoff.                                    |
|   `spring.cloud.kubernetes.config.retry.multiplier`   |`Double` |           `1.1`            |                                    Multiplier for next interval.                                    |

### [](#secrets-propertysource)[5.2. Secrets PropertySource](#secrets-propertysource) ###

Kubernetes has the notion of [Secrets](https://kubernetes.io/docs/concepts/configuration/secret/) 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 `Fabric8SecretsPropertySource` 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:**

By default, consuming Secrets through the API (points 2 and 3 above) **is not enabled** for security reasons. The permission 'list' on secrets allows clients to inspect secrets values in the specified namespace.
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.
For more information about risks and best practices when consuming Secrets through the API refer to [this doc](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:

```
kubectl 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 `kubectl get secrets db-secret -o yaml`):

```
apiVersion: v1
data:
  password: cDQ1NXcwcmQ=
  username: dXNlcg==
kind: Secret
metadata:
  creationTimestamp: 2017-07-04T09:15:57Z
  name: db-secret
  namespace: default
  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.

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}
spec:
   template:
     spec:
       containers:
         - env:
            - name: DB_USERNAME
              valueFrom:
                 secretKeyRef:
                   name: db-secret
                   key: username
            - name: DB_PASSWORD
              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
   ```

As the case with `ConfigMap`, more advanced configuration is also possible where you can use multiple `Secret`instances. The `spring.cloud.kubernetes.secrets.sources` list makes this possible.
For example, you could define the following `Secret` instances:

```
spring:
  application:
    name: cloud-k8s-app
  cloud:
    kubernetes:
      secrets:
        name: default-name
        namespace: default-namespace
        sources:
         # Spring Cloud Kubernetes looks up a Secret named s1 in namespace default-namespace
         - name: s1
         # Spring Cloud Kubernetes looks up a Secret named default-name in namespace n2
         - namespace: n2
         # Spring Cloud Kubernetes looks up a Secret named s3 in namespace n3
         - namespace: n3
           name: s3
```

In the preceding example, if `spring.cloud.kubernetes.secrets.namespace` had not been set,
the `Secret` named `s1` would be looked up in the namespace that the application runs.
See [namespace-resolution](#namespace-resolution) to get a better understanding of how the namespace
of the application is resolved.

[Similar to the `ConfigMaps`](#config-map-fail-fast); if you want your application to fail to start
when it is unable to load `Secrets` property sources, you can set `spring.cloud.kubernetes.secrets.fail-fast=true`.

It is also possible to enable retry for `Secret` property sources [like the `ConfigMaps`](#config-map-retry).
As with the `ConfigMap` property sources, first you need to set `spring.cloud.kubernetes.secrets.fail-fast=true`.
Then you need to add `spring-retry` and `spring-boot-starter-aop` to your classpath.
Retry behavior of the `Secret` property sources can be configured by setting the `spring.cloud.kubernetes.secrets.retry.*`properties.

|   |If you already have `spring-retry` and `spring-boot-starter-aop` on the classpath for some reason<br/>and want to enable fail-fast, but do not want retry to be enabled; you can disable retry for `Secrets` `PropertySources`by setting `spring.cloud.kubernetes.secrets.retry.enabled=false`.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|                          Name                          |  Type   |          Default           |                                           Description                                            |
|--------------------------------------------------------|---------|----------------------------|--------------------------------------------------------------------------------------------------|
|       `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)                       |
|      `spring.cloud.kubernetes.secrets.enableApi`       |`Boolean`|          `false`           |              Enables or disables consuming secrets through APIs (examples 2 and 3)               |
|      `spring.cloud.kubernetes.secrets.fail-fast`       |`Boolean`|          `false`           |Enable or disable failing the application start-up when an error occurred while loading a `Secret`|
|    `spring.cloud.kubernetes.secrets.retry.enabled`     |`Boolean`|           `true`           |                                 Enable or disable secrets retry.                                 |
|`spring.cloud.kubernetes.secrets.retry.initial-interval`| `Long`  |           `1000`           |                             Initial retry interval in milliseconds.                              |
|  `spring.cloud.kubernetes.secrets.retry.max-attempts`  |`Integer`|            `6`             |                                   Maximum number of attempts.                                    |
|  `spring.cloud.kubernetes.secrets.retry.max-interval`  | `Long`  |           `2000`           |                                  Maximum interval for backoff.                                   |
|   `spring.cloud.kubernetes.secrets.retry.multiplier`   |`Double` |           `1.1`            |                                  Multiplier for next interval.                                   |

Notes:

* The `spring.cloud.kubernetes.secrets.labels` property behaves as defined by[Map-based binding](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding#map-based-binding).

* The `spring.cloud.kubernetes.secrets.paths` property behaves as defined by[Collection-based binding](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding#collection-based-binding).

* 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](https://github.com/fabric8-quickstarts/spring-boot-camel-config)

### [](#namespace-resolution)[5.3. Namespace resolution](#namespace-resolution) ###

Finding an application namespace happens on a best-effort basis. There are some steps that we iterate in order
to find it. The easiest and most common one, is to specify it in the proper configuration, for example:

```
spring:
  application:
    name: app
  cloud:
    kubernetes:
      secrets:
        name: secret
        namespace: default
        sources:
         # Spring Cloud Kubernetes looks up a Secret named 'a' in namespace 'default'
         - name: a
         # Spring Cloud Kubernetes looks up a Secret named 'secret' in namespace 'b'
         - namespace: b
         # Spring Cloud Kubernetes looks up a Secret named 'd' in namespace 'c'
         - namespace: c
           name: d
```

Remember that the same can be done for config maps. If such a namespace is not specified, it will be read (in this order):

1. from property `spring.cloud.kubernetes.client.namespace`

2. from a String residing in a file denoted by `spring.cloud.kubernetes.client.serviceAccountNamespacePath` property

3. from a String residing in `/var/run/secrets/kubernetes.io/serviceaccount/namespace` file
   (kubernetes default namespace path)

4. from a designated client method call (for example fabric8’s : `KubernetesClient::getNamespace`), if the client provides
   such a method. This, in turn, could be configured via environment properties. For example fabric8 client can be configured via
   "KUBERNETES\_NAMESPACE" property; consult the client documentation for exact details.

Failure to find a namespace from the above steps will result in an Exception being raised.

### [](#propertysource-reload)[5.4. `PropertySource` Reload](#propertysource-reload) ###

|   |This functionality has been deprecated in the 2020.0 release. Please see<br/>the [Spring Cloud Kubernetes Configuration Watcher](#spring-cloud-kubernetes-configuration-watcher) controller for an alternative way<br/>to achieve the same functionality.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

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.

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.
  In order for the restart context functionality to work properly you must enable and expose the restart actuator endpoint

```
management:
  endpoint:
    restart:
      enabled: true
  endpoints:
    web:
      exposure:
        include: restart
```

* `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";

    // getter and setters

}
```

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

```
@Component
public class MyBean {

    @Autowired
    private MyConfig config;

    @Scheduled(fixedDelay = 5000)
    public void hello() {
        System.out.println("The message is: " + config.getMessage());
    }
}
```

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 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 are detected and reflected in the application.[Associating a `ConfigMap` with a pod](#configmap-propertysource) is explained earlier in this chapter.

The full example is available in [`spring-cloud-kubernetes-reload-example`](https://github.com/spring-cloud/spring-cloud-kubernetes/tree/main/spring-cloud-kubernetes-examples/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: Periodically 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.

|                         Name                          |   Type   | Default |                                     Description                                      |
|-------------------------------------------------------|----------|---------|--------------------------------------------------------------------------------------|
|       `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`)    |
|        `spring.cloud.kubernetes.reload.period`        |`Duration`|  `15s`  |          The period for verifying changes when using the `polling` strategy          |

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.

[](#kubernetes-ecosystem-awareness)[6. Kubernetes Ecosystem Awareness](#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](https://github.com/fabric8io/kubernetes-client), which is a fluent DSL that can
communicate by using `http` protocol to the REST API of the Kubernetes Server.

To disable the integration with Kubernetes you can set `spring.cloud.kubernetes.enabled` to `false`. Please be aware that when `spring-cloud-kubernetes-config` is on the classpath,`spring.cloud.kubernetes.enabled` should be set in `bootstrap.{properties|yml}` (or the profile specific one), otherwise it should be in `application.{properties|yml}` (or the profile specific one).
Because of the way we set up a specific `EnvironmentPostProcessor` in `spring-cloud-kubernetes-config`, you also need to disable that processor via a system property (or an environment variable), for example you could start
your application via `-DSPRING_CLOUD_KUBERNETES_ENABLED=false` (any form of relaxed binding will work too).
Also note that these properties: `spring.cloud.kubernetes.config.enabled` and `spring.cloud.kubernetes.secrets.enabled` only take effect when set in `bootstrap.{properties|yml}`

### [](#kubernetes-profile-autoconfiguration)[6.1. Kubernetes Profile Autoconfiguration](#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).

### [](#istio-awareness)[6.2. Istio Awareness](#istio-awareness) ###

When you include the `spring-cloud-kubernetes-fabric8-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](https://istio.io) 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)[7. Pod Health Indicator](#pod-health-indicator)
----------

Spring Boot uses [`HealthIndicator`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpoint.java) 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](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-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

You can disable this `HealthContributor` by setting `management.health.kubernetes.enabled`to `false` in `application.[properties | yaml]`.

[](#info-contributor)[8. Info Contributor](#info-contributor)
----------

Spring Cloud Kubernetes includes an `InfoContributor` which adds Pod information to
Spring Boot’s `/info` Acturator endpoint.

You can disable this `InfoContributor` by setting `management.info.kubernetes.enabled`to `false` in `application.[properties | yaml]`.

[](#leader-election)[9. Leader Election](#leader-election)
----------

The Spring Cloud Kubernetes leader election mechanism implements the leader election API of Spring Integration using a Kubernetes ConfigMap.

Multiple application instances compete for leadership, but leadership will only be granted to one.
When granted leadership, a leader application receives an `OnGrantedEvent` application event with leadership `Context`.
Applications periodically attempt to gain leadership, with leadership granted to the first caller.
A leader will remain a leader until either it is removed from the cluster, or it yields its leadership.
When leadership removal occurs, the previous leader receives `OnRevokedEvent` application event.
After removal, any instances in the cluster may become the new leader, including the old leader.

To include it in your project, add the following dependency.

Fabric8 Leader Implementation

```
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-kubernetes-fabric8-leader</artifactId>
</dependency>
```

To specify the name of the configmap used for leader election use the following property.

```
spring.cloud.kubernetes.leader.config-map-name=leader
```

[](#loadbalancer-for-kubernetes)[10. LoadBalancer for Kubernetes](#loadbalancer-for-kubernetes)
----------

This project includes Spring Cloud Load Balancer for load balancing based on Kubernetes Endpoints and provides implementation of load balancer based on Kubernetes Service.
To include it to your project add the following dependency.

Fabric8 Implementation

```
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-kubernetes-fabric8-loadbalancer</artifactId>
</dependency>
```

Kubernetes Java Client Implementation

```
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-kubernetes-client-loadbalancer</artifactId>
</dependency>
```

To enable load balancing based on Kubernetes Service name use the following property. Then load balancer would try to call application using address, for example `service-a.default.svc.cluster.local`

```
spring.cloud.kubernetes.loadbalancer.mode=SERVICE
```

To enabled load balancing across all namespaces use the following property. Property from `spring-cloud-kubernetes-discovery` module is respected.

```
spring.cloud.kubernetes.discovery.all-namespaces=true
```

If a service needs to be accessed over HTTPS you need to add a label or annotation to your service definition with the name `secured` and the value `true` and the load balancer will then use HTTPS to make requests to the service.

[](#security-configurations-inside-kubernetes)[11. Security Configurations Inside Kubernetes](#security-configurations-inside-kubernetes)
----------

### [](#namespace)[11.1. Namespace](#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)[11.2. Service Account](#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.

Depending on the requirements, you’ll need `get`, `list` and `watch` permission on the following resources:

|                  Dependency                  |        Resources        |
|----------------------------------------------|-------------------------|
|   spring-cloud-starter-kubernetes-fabric8    |pods, services, endpoints|
|spring-cloud-starter-kubernetes-fabric8-config|   configmaps, secrets   |
|    spring-cloud-starter-kubernetes-client    |pods, services, endpoints|
|spring-cloud-starter-kubernetes-client-config |   configmaps, secrets   |

For development purposes, you can add `cluster-reader` permissions to your `default` service account. On a production system you’ll likely want to provide more granular permissions.

The following Role and RoleBinding are an example for namespaced permissions for the `default` account:

```
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: YOUR-NAME-SPACE
  name: namespace-reader
rules:
  - apiGroups: [""]
    resources: ["configmaps", "pods", "services", "endpoints", "secrets"]
    verbs: ["get", "list", "watch"]

---

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: namespace-reader-binding
  namespace: YOUR-NAME-SPACE
subjects:
- kind: ServiceAccount
  name: default
  apiGroup: ""
roleRef:
  kind: Role
  name: namespace-reader
  apiGroup: ""
```

[](#service-registry-implementation)[12. Service Registry Implementation](#service-registry-implementation)
----------

In Kubernetes service registration is controlled by the platform, the application itself does not control
registration as it may do in other platforms. For this reason using `spring.cloud.service-registry.auto-registration.enabled`or setting `@EnableDiscoveryClient(autoRegister=false)` will have no effect in Spring Cloud Kubernetes.

[](#spring-cloud-kubernetes-configuration-watcher)[13. Spring Cloud Kubernetes Configuration Watcher](#spring-cloud-kubernetes-configuration-watcher)
----------

Kubernetes provides the ability to [mount a ConfigMap or Secret as a volume](https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#add-configmap-data-to-a-volume)in the container of your application. When the contents of the ConfigMap or Secret changes, the [mounted volume will be updated with those changes](https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#mounted-configmaps-are-updated-automatically).

However, Spring Boot will not automatically update those changes unless you restart the application. Spring Cloud
provides the ability refresh the application context without restarting the application by either hitting the
actuator endpoint `/refresh` or via publishing a `RefreshRemoteApplicationEvent` using Spring Cloud Bus.

To achieve this configuration refresh of a Spring Cloud app running on Kubernetes, you can deploy the Spring Cloud
Kubernetes Configuration Watcher controller into your Kubernetes cluster.

The application is published as a container and is available on [Docker Hub](https://hub.docker.com/r/springcloud/spring-cloud-kubernetes-configuration-watcher).

Spring Cloud Kubernetes Configuration Watcher can send refresh notifications to applications in two ways.

1. Over HTTP in which case the application being notified must of the `/refresh` actuator endpoint exposed and accessible from within the cluster

2. Using Spring Cloud Bus, in which case you will need a message broker deployed to your custer for the application to use.

### [](#deployment-yaml)[13.1. Deployment YAML](#deployment-yaml) ###

Below is a sample deployment YAML you can use to deploy the Kubernetes Configuration Watcher to Kubernetes.

```
---
apiVersion: v1
kind: List
items:
  - apiVersion: v1
    kind: Service
    metadata:
      labels:
        app: spring-cloud-kubernetes-configuration-watcher
      name: spring-cloud-kubernetes-configuration-watcher
    spec:
      ports:
        - name: http
          port: 8888
          targetPort: 8888
      selector:
        app: spring-cloud-kubernetes-configuration-watcher
      type: ClusterIP
  - apiVersion: v1
    kind: ServiceAccount
    metadata:
      labels:
        app: spring-cloud-kubernetes-configuration-watcher
      name: spring-cloud-kubernetes-configuration-watcher
  - apiVersion: rbac.authorization.k8s.io/v1
    kind: RoleBinding
    metadata:
      labels:
        app: spring-cloud-kubernetes-configuration-watcher
      name: spring-cloud-kubernetes-configuration-watcher:view
    roleRef:
      kind: Role
      apiGroup: rbac.authorization.k8s.io
      name: namespace-reader
    subjects:
      - kind: ServiceAccount
        name: spring-cloud-kubernetes-configuration-watcher
  - apiVersion: rbac.authorization.k8s.io/v1
    kind: Role
    metadata:
      namespace: default
      name: namespace-reader
    rules:
      - apiGroups: ["", "extensions", "apps"]
        resources: ["configmaps", "pods", "services", "endpoints", "secrets"]
        verbs: ["get", "list", "watch"]
  - apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: spring-cloud-kubernetes-configuration-watcher-deployment
    spec:
      selector:
        matchLabels:
          app: spring-cloud-kubernetes-configuration-watcher
      template:
        metadata:
          labels:
            app: spring-cloud-kubernetes-configuration-watcher
        spec:
          serviceAccount: spring-cloud-kubernetes-configuration-watcher
          containers:
          - name: spring-cloud-kubernetes-configuration-watcher
            image: springcloud/spring-cloud-kubernetes-configuration-watcher:2.0.1-SNAPSHOT
            imagePullPolicy: IfNotPresent
            readinessProbe:
              httpGet:
                port: 8888
                path: /actuator/health/readiness
            livenessProbe:
              httpGet:
                port: 8888
                path: /actuator/health/liveness
            ports:
            - containerPort: 8888
```

The Service Account and associated Role Binding is important for Spring Cloud Kubernetes Configuration to work properly.
The controller needs access to read data about ConfigMaps, Pods, Services, Endpoints and Secrets in the Kubernetes cluster.

### [](#monitoring-configmaps-and-secrets)[13.2. Monitoring ConfigMaps and Secrets](#monitoring-configmaps-and-secrets) ###

Spring Cloud Kubernetes Configuration Watcher will react to changes in ConfigMaps with a label of `spring.cloud.kubernetes.config` with the value `true`or any Secret with a label of `spring.cloud.kubernetes.secret` with the value `true`. If the ConfigMap or Secret does not have either of those labels
or the values of those labels is not `true` then any changes will be ignored.

The labels Spring Cloud Kubernetes Configuration Watcher looks for on ConfigMaps and Secrets can be changed by setting`spring.cloud.kubernetes.configuration.watcher.configLabel` and `spring.cloud.kubernetes.configuration.watcher.secretLabel` respectively.

If a change is made to a ConfigMap or Secret with valid labels then Spring Cloud Kubernetes Configuration Watcher will take the name of the ConfigMap or Secret
and send a notification to the application with that name.

### [](#http-implementation)[13.3. HTTP Implementation](#http-implementation) ###

The HTTP implementation is what is used by default. When this implementation is used Spring Cloud Kubernetes Configuration Watcher and a
change to a ConfigMap or Secret occurs then the HTTP implementation will use the Spring Cloud Kubernetes Discovery Client to fetch all
instances of the application which match the name of the ConfigMap or Secret and send an HTTP POST request to the application’s actuator`/refresh` endpoint. By default it will send the post request to `/actuator/refresh` using the port registered in the discovery client.

#### [](#non-default-management-port-and-actuator-path)[13.3.1. Non-Default Management Port and Actuator Path](#non-default-management-port-and-actuator-path) ####

If the application is using a non-default actuator path and/or using a different port for the management endpoints, the Kubernetes service for the application
can add an annotation called `boot.spring.io/actuator` and set its value to the path and port used by the application. For example

```
apiVersion: v1
kind: Service
metadata:
  labels:
    app: config-map-demo
  name: config-map-demo
  annotations:
    boot.spring.io/actuator: http://:9090/myactuator/home
spec:
  ports:
    - name: http
      port: 8080
      targetPort: 8080
  selector:
    app: config-map-demo
```

Another way you can choose to configure the actuator path and/or management port is by setting`spring.cloud.kubernetes.configuration.watcher.actuatorPath` and `spring.cloud.kubernetes.configuration.watcher.actuatorPort`.

### [](#messaging-implementation)[13.4. Messaging Implementation](#messaging-implementation) ###

The messaging implementation can be enabled by setting profile to either `bus-amqp` (RabbitMQ) or `bus-kafka` (Kafka) when the Spring Cloud Kubernetes Configuration Watcher
application is deployed to Kubernetes.

### [](#configuring-rabbitmq)[13.5. Configuring RabbitMQ](#configuring-rabbitmq) ###

When the `bus-amqp` profile is enabled you will need to configure Spring RabbitMQ to point it to the location of the RabbitMQ
instance you would like to use as well as any credentials necessary to authenticate. This can be done
by setting the standard Spring RabbitMQ properties, for example

```
spring:
  rabbitmq:
    username: user
    password: password
    host: rabbitmq
```

### [](#configuring-kafka)[13.6. Configuring Kafka](#configuring-kafka) ###

When the `bus-kafka` profile is enabled you will need to configure Spring Kafka to point it to the location of the Kafka Broker
instance you would like to use. This can be done by setting the standard Spring Kafka properties, for example

```
spring:
  kafka:
    producer:
      bootstrap-servers: localhost:9092
```

[](#spring-cloud-kubernetes-configserver)[14. Spring Cloud Kubernetes Config Server](#spring-cloud-kubernetes-configserver)
----------

The Spring Cloud Kubernetes Config Server, is based on [Spring Cloud Config Server](https://spring.io/projects/spring-cloud-config) and adds an [environment repository](https://docs.spring.io/spring-cloud-config/docs/current/reference/html/#_environment_repository) for Kubernetes[Config Maps](https://kubernetes.io/docs/concepts/configuration/configmap/) and [Secrets](https://kubernetes.io/docs/concepts/configuration/secret/).

This is component is completely optional. However, it allows you to continue to leverage configuration
you may have stored in existing environment repositories (Git, SVN, Vault, etc) with applications that you are running on Kubernetes.

A default image is located on [Docker Hub](https://hub.docker.com/r/springcloud/spring-cloud-kubernetes-configserver) which will allow you to easily get a Config Server deployed on Kubernetes without building
the code and image yourself. However, if you need to customize the config server behavior you can easily build your own
image from the source code on GitHub and use that.

### [](#configuration)[14.1. Configuration](#configuration) ###

#### [](#enabling-the-kubernetes-environment-repository)[14.1.1. Enabling The Kubernetes Environment Repository](#enabling-the-kubernetes-environment-repository) ####

To enable the Kubernetes environment repository the `kubernetes` profile must be included in the list of active profiles.
You may activate other profiles as well to use other environment repository implementations.

#### [](#config-map-and-secret-propertysources)[14.1.2. Config Map and Secret PropertySources](#config-map-and-secret-propertysources) ####

By default, only Config Map data will be fetched. To enable Secrets as well you will need to set `spring.cloud.kubernetes.secrets.enableApi=true`.
You can disable the Config Map `PropertySource` by setting `spring.cloud.kubernetes.config.enableApi=false`.

#### [](#fetching-config-map-and-secret-data-from-additional-namespaces)[14.1.3. Fetching Config Map and Secret Data From Additional Namespaces](#fetching-config-map-and-secret-data-from-additional-namespaces) ####

By default, the Kubernetes environment repository will only fetch Config Map and Secrets from the namespace in which it is deployed.
If you want to include data from other namespaces you can set `spring.cloud.kubernetes.configserver.config-map-namespaces` and/or `spring.cloud.kubernetes.configserver.secrets-namespaces` to a comma separated
list of namespace values.

|   |If you set `spring.cloud.kubernetes.configserver.config-map-namespaces` and/or `spring.cloud.kubernetes.configserver.secrets-namespaces`you will need to include the namespace in which the Config Server is deployed in order to continue to fetch Config Map and Secret data from that namespace.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#kubernetes-access-controls)[14.1.4. Kubernetes Access Controls](#kubernetes-access-controls) ####

The Kubernetes Config Server uses the Kubernetes API server to fetch Config Map and Secret data. In order for it to do that
it needs ability to `get` and `list` Config Map and Secrets (depending on what you enable/disable).

### [](#deployment-yaml-2)[14.2. Deployment Yaml](#deployment-yaml-2) ###

Below is a sample deployment, service and permissions configuration you can use to deploy a basic Config Server to Kubernetes.

```
---
apiVersion: v1
kind: List
items:
  - apiVersion: v1
    kind: Service
    metadata:
      labels:
        app: spring-cloud-kubernetes-configserver
      name: spring-cloud-kubernetes-configserver
    spec:
      ports:
        - name: http
          port: 8888
          targetPort: 8888
      selector:
        app: spring-cloud-kubernetes-configserver
      type: ClusterIP
  - apiVersion: v1
    kind: ServiceAccount
    metadata:
      labels:
        app: spring-cloud-kubernetes-configserver
      name: spring-cloud-kubernetes-configserver
  - apiVersion: rbac.authorization.k8s.io/v1
    kind: RoleBinding
    metadata:
      labels:
        app: spring-cloud-kubernetes-configserver
      name: spring-cloud-kubernetes-configserver:view
    roleRef:
      kind: Role
      apiGroup: rbac.authorization.k8s.io
      name: namespace-reader
    subjects:
      - kind: ServiceAccount
        name: spring-cloud-kubernetes-configserver
  - apiVersion: rbac.authorization.k8s.io/v1
    kind: Role
    metadata:
      namespace: default
      name: namespace-reader
    rules:
      - apiGroups: ["", "extensions", "apps"]
        resources: ["configmaps", "secrets"]
        verbs: ["get", "list"]
  - apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: spring-cloud-kubernetes-configserver-deployment
    spec:
      selector:
        matchLabels:
          app: spring-cloud-kubernetes-configserver
      template:
        metadata:
          labels:
            app: spring-cloud-kubernetes-configserver
        spec:
          serviceAccount: spring-cloud-kubernetes-configserver
          containers:
          - name: spring-cloud-kubernetes-configserver
            image: springcloud/spring-cloud-kubernetes-configserver
            imagePullPolicy: IfNotPresent
            env:
                - name: SPRING_PROFILES_INCLUDE
                  value: "kubernetes"
            readinessProbe:
              httpGet:
                port: 8888
                path: /actuator/health/readiness
            livenessProbe:
              httpGet:
                port: 8888
                path: /actuator/health/liveness
            ports:
            - containerPort: 8888
```

[](#spring-cloud-kubernetes-discoveryserver)[15. Spring Cloud Kubernetes Discovery Server](#spring-cloud-kubernetes-discoveryserver)
----------

The Spring Cloud Kubernetes Discovery Server provides HTTP endpoints apps can use to gather information
about services available within a Kubernetes cluster. The Spring Cloud Kubernetes Discovery Server
can be used by apps using the `spring-cloud-starter-kubernetes-discoveryclient` to provide data to
the `DiscoveryClient` implementation provided by that starter.

### [](#permissions)[15.1. Permissions](#permissions) ###

The Spring Cloud Discovery server uses
the Kubernetes API server to get data about Service and Endpoint resrouces so it needs list, watch, and
get permissions to use those endpoints. See the below sample Kubernetes deployment YAML for an
examlpe of how to configure the Service Account on Kubernetes.

### [](#endpoints)[15.2. Endpoints](#endpoints) ###

There are three endpoints exposed by the server.

#### [](#apps)[15.2.1. `/apps`](#apps) ####

A `GET` request sent to `/apps` will return a JSON array of available services. Each item contains
the name of the Kubernetes service and service instance information. Below is a sample response.

```
[
   {
      "name":"spring-cloud-kubernetes-discoveryserver",
      "serviceInstances":[
         {
            "instanceId":"836a2f25-daee-4af2-a1be-aab9ce2b938f",
            "serviceId":"spring-cloud-kubernetes-discoveryserver",
            "host":"10.244.1.6",
            "port":8761,
            "uri":"http://10.244.1.6:8761",
            "secure":false,
            "metadata":{
               "app":"spring-cloud-kubernetes-discoveryserver",
               "kubectl.kubernetes.io/last-applied-configuration":"{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{},\"labels\":{\"app\":\"spring-cloud-kubernetes-discoveryserver\"},\"name\":\"spring-cloud-kubernetes-discoveryserver\",\"namespace\":\"default\"},\"spec\":{\"ports\":[{\"name\":\"http\",\"port\":80,\"targetPort\":8761}],\"selector\":{\"app\":\"spring-cloud-kubernetes-discoveryserver\"},\"type\":\"ClusterIP\"}}\n",
               "http":"8761"
            },
            "namespace":"default",
            "scheme":"http"
         }
      ]
   },
   {
      "name":"kubernetes",
      "serviceInstances":[
         {
            "instanceId":"1234",
            "serviceId":"kubernetes",
            "host":"172.18.0.3",
            "port":6443,
            "uri":"http://172.18.0.3:6443",
            "secure":false,
            "metadata":{
               "provider":"kubernetes",
               "component":"apiserver",
               "https":"6443"
            },
            "namespace":"default",
            "scheme":"http"
         }
      ]
   }
]
```

#### [](#appname)[15.2.2. `/app/{name}`](#appname) ####

A `GET` request to `/app/{name}` can be used to get instance data for all instances of a given
service. Below is a sample response when a `GET` request is made to `/app/kubernetes`.

```
[
     {
        "instanceId":"1234",
        "serviceId":"kubernetes",
        "host":"172.18.0.3",
        "port":6443,
        "uri":"http://172.18.0.3:6443",
        "secure":false,
        "metadata":{
           "provider":"kubernetes",
           "component":"apiserver",
           "https":"6443"
        },
        "namespace":"default",
        "scheme":"http"
     }
]
```

#### [](#appnameinstanceid)[15.2.3. `/app/{name}/{instanceid}`](#appnameinstanceid) ####

A `GET` request made to `/app/{name}/{instanceid}` will return the instance data for a specific
instance of a given service. Below is a sample response when a `GET` request is made to `/app/kubernetes/1234`.

```
 {
    "instanceId":"1234",
    "serviceId":"kubernetes",
    "host":"172.18.0.3",
    "port":6443,
    "uri":"http://172.18.0.3:6443",
    "secure":false,
    "metadata":{
       "provider":"kubernetes",
       "component":"apiserver",
       "https":"6443"
    },
    "namespace":"default",
    "scheme":"http"
 }
```

### [](#deployment-yaml-3)[15.3. Deployment YAML](#deployment-yaml-3) ###

An image of the Spring Cloud Discovery Server is hosted on [Docker Hub](https://hub.docker.com/r/springcloud/spring-cloud-kubernetes-discoveryserver).

Below is a sample deployment YAML you can use to deploy the Kubernetes Configuration Watcher to Kubernetes.

```
---
apiVersion: v1
kind: List
items:
  - apiVersion: v1
    kind: Service
    metadata:
      labels:
        app: spring-cloud-kubernetes-discoveryserver
      name: spring-cloud-kubernetes-discoveryserver
    spec:
      ports:
        - name: http
          port: 80
          targetPort: 8761
      selector:
        app: spring-cloud-kubernetes-discoveryserver
      type: ClusterIP
  - apiVersion: v1
    kind: ServiceAccount
    metadata:
      labels:
        app: spring-cloud-kubernetes-discoveryserver
      name: spring-cloud-kubernetes-discoveryserver
  - apiVersion: rbac.authorization.k8s.io/v1
    kind: RoleBinding
    metadata:
      labels:
        app: spring-cloud-kubernetes-discoveryserver
      name: spring-cloud-kubernetes-discoveryserver:view
    roleRef:
      kind: Role
      apiGroup: rbac.authorization.k8s.io
      name: namespace-reader
    subjects:
      - kind: ServiceAccount
        name: spring-cloud-kubernetes-discoveryserver
  - apiVersion: rbac.authorization.k8s.io/v1
    kind: Role
    metadata:
      namespace: default
      name: namespace-reader
    rules:
      - apiGroups: ["", "extensions", "apps"]
        resources: ["services", "endpoints"]
        verbs: ["get", "list", "watch"]
  - apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: spring-cloud-kubernetes-discoveryserver-deployment
    spec:
      selector:
        matchLabels:
          app: spring-cloud-kubernetes-discoveryserver
      template:
        metadata:
          labels:
            app: spring-cloud-kubernetes-discoveryserver
        spec:
          serviceAccount: spring-cloud-kubernetes-discoveryserver
          containers:
          - name: spring-cloud-kubernetes-discoveryserver
            image: springcloud/spring-cloud-kubernetes-discoveryserver:2.1.0-SNAPSHOT
            imagePullPolicy: IfNotPresent
            readinessProbe:
              httpGet:
                port: 8761
                path: /actuator/health/readiness
            livenessProbe:
              httpGet:
                port: 8761
                path: /actuator/health/liveness
            ports:
            - containerPort: 8761
```

[](#examples)[16. Examples](#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:

* [Spring Cloud Kubernetes Examples](https://github.com/spring-cloud/spring-cloud-kubernetes/tree/master/spring-cloud-kubernetes-examples): the ones located inside this repository.

* Spring Cloud Kubernetes Full Example: Minions and Boss

  * [Minion](https://github.com/salaboy/spring-cloud-k8s-minion)

  * [Boss](https://github.com/salaboy/spring-cloud-k8s-boss)

* Spring Cloud Kubernetes Full Example: [SpringOne Platform Tickets Service](https://github.com/salaboy/s1p_docs)

* [Spring Cloud Gateway with Spring Cloud Kubernetes Discovery and Config](https://github.com/salaboy/s1p_gateway)

* [Spring Boot Admin with Spring Cloud Kubernetes Discovery and Config](https://github.com/salaboy/showcase-admin-tool)

[](#other-resources)[17. Other Resources](#other-resources)
----------

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

* [S1P Spring Cloud on PKS](https://salaboy.com/2018/09/27/the-s1p-experience/)

* [Spring Cloud, Docker, Kubernetes → London Java Community July 2018](https://salaboy.com/2018/07/18/ljc-july-18-spring-cloud-docker-k8s/)

Please feel free to submit other resources through pull requests to [this repository](https://github.com/spring-cloud/spring-cloud-kubernetes).

[](#configuration-properties)[18. Configuration properties](#configuration-properties)
----------

To see the list of all Kubernetes related configuration properties please check [the Appendix page](appendix.html).

[](#building)[19. Building](#building)
----------

### [](#basic-compile-and-test)[19.1. Basic Compile and Test](#basic-compile-and-test) ###

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

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
```

|   |You can also install Maven (\>=3.3.3) yourself and run the `mvn` command<br/>in place of `./mvnw` in the examples below. If you do that you also<br/>might need to add `-P spring` if your local Maven settings do not<br/>contain repository declarations for spring pre-release artifacts.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |Be aware that you might need to increase the amount of memory<br/>available to Maven by setting a `MAVEN_OPTS` environment variable with<br/>a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in<br/>the `.mvn` configuration, so if you find you have to do it to make a<br/>build succeed, please raise a ticket to get the settings added to<br/>source control.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The projects that require middleware (i.e. Redis) for testing generally
require that a local instance of [Docker]([www.docker.com/get-started](https://www.docker.com/get-started)) is installed and running.

### [](#documentation)[19.2. Documentation](#documentation) ###

The spring-cloud-build module has a "docs" profile, and if you switch
that on it will try to build asciidoc sources from`src/main/asciidoc`. As part of that process it will look for a`README.adoc` and process it by loading all the includes, but not
parsing or rendering it, just copying it to `${main.basedir}`(defaults to `$/tmp/releaser-1645122597379-0/spring-cloud-kubernetes/docs`, i.e. the root of the project). If there are
any changes in the README it will then show up after a Maven build as
a modified file in the correct place. Just commit it and push the change.

### [](#working-with-the-code)[19.3. Working with the code](#working-with-the-code) ###

If you don’t have an IDE preference we would recommend that you use[Spring Tools Suite](https://www.springsource.com/developer/sts) or[Eclipse](https://eclipse.org) when working with the code. We use the[m2eclipse](https://eclipse.org/m2e/) eclipse plugin for maven support. Other IDEs and tools
should also work without issue as long as they use Maven 3.3.3 or better.

#### [](#activate-the-spring-maven-profile)[19.3.1. Activate the Spring Maven profile](#activate-the-spring-maven-profile) ####

Spring Cloud projects require the 'spring' Maven profile to be activated to resolve
the spring milestone and snapshot repositories. Use your preferred IDE to set this
profile to be active, or you may experience build errors.

#### [](#importing-into-eclipse-with-m2eclipse)[19.3.2. Importing into eclipse with m2eclipse](#importing-into-eclipse-with-m2eclipse) ####

We recommend the [m2eclipse](https://eclipse.org/m2e/) eclipse plugin when working with
eclipse. If you don’t already have m2eclipse installed it is available from the "eclipse
marketplace".

|   |Older versions of m2e do not support Maven 3.3, so once the<br/>projects are imported into Eclipse you will also need to tell<br/>m2eclipse to use the right profile for the projects. If you<br/>see many different errors related to the POMs in the projects, check<br/>that you have an up to date installation. If you can’t upgrade m2e,<br/>add the "spring" profile to your `settings.xml`. Alternatively you can<br/>copy the repository settings from the "spring" profile of the parent<br/>pom into your `settings.xml`.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#importing-into-eclipse-without-m2eclipse)[19.3.3. Importing into eclipse without m2eclipse](#importing-into-eclipse-without-m2eclipse) ####

If you prefer not to use m2eclipse you can generate eclipse project metadata using the
following command:

```
$ ./mvnw eclipse:eclipse
```

The generated eclipse projects can be imported by selecting `import existing projects`from the `file` menu.

[](#contributing)[20. Contributing](#contributing)
----------

Spring Cloud is released under the non-restrictive Apache 2.0 license,
and follows a very standard Github development process, using Github
tracker for issues and merging pull requests into master. If you want
to contribute even something trivial please do not hesitate, but
follow the guidelines below.

### [](#sign-the-contributor-license-agreement)[20.1. Sign the Contributor License Agreement](#sign-the-contributor-license-agreement) ###

Before we accept a non-trivial patch or pull request we will need you to sign the[Contributor License Agreement](https://cla.pivotal.io/sign/spring).
Signing the contributor’s agreement does not grant anyone commit rights to the main
repository, but it does mean that we can accept your contributions, and you will get an
author credit if we do. Active contributors might be asked to join the core team, and
given the ability to merge pull requests.

### [](#code-of-conduct)[20.2. Code of Conduct](#code-of-conduct) ###

This project adheres to the Contributor Covenant [code of
conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report
unacceptable behavior to [[email protected]](/cdn-cgi/l/email-protection#473437352e29206a242823226a28216a2428292332243307372e312833262b692e28).

### [](#code-conventions-and-housekeeping)[20.3. Code Conventions and Housekeeping](#code-conventions-and-housekeeping) ###

None of these is essential for a pull request, but they will all help. They can also be
added after the original pull request but before a merge.

* Use the Spring Framework code format conventions. If you use Eclipse
  you can import formatter settings using the`eclipse-code-formatter.xml` file from the[Spring
  Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the[Eclipse Code Formatter
  Plugin](https://plugins.jetbrains.com/plugin/6546) to import the same file.

* Make sure all new `.java` files to have a simple Javadoc class comment with at least an`@author` tag identifying you, and preferably at least a paragraph on what the class is
  for.

* Add the ASF license header comment to all new `.java` files (copy from existing files
  in the project)

* Add yourself as an `@author` to the .java files that you modify substantially (more
  than cosmetic changes).

* Add some Javadocs and, if you change the namespace, some XSD doc elements.

* A few unit tests would help a lot as well — someone has to do it.

* If no-one else is using your branch, please rebase it against the current master (or
  other target branch in the main project).

* When writing a commit message please follow [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html),
  if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
  message (where XXXX is the issue number).

### [](#checkstyle)[20.4. Checkstyle](#checkstyle) ###

Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are:

spring-cloud-build-tools/

```
└── src
    ├── checkstyle
    │   └── checkstyle-suppressions.xml (3)
    └── main
        └── resources
            ├── checkstyle-header.txt (2)
            └── checkstyle.xml (1)
```

|**1**|Default Checkstyle rules |
|-----|-------------------------|
|**2**|    File header setup    |
|**3**|Default suppression rules|

#### [](#checkstyle-configuration)[20.4.1. Checkstyle configuration](#checkstyle-configuration) ####

Checkstyle rules are **disabled by default**. To add checkstyle to your project just define the following properties and plugins.

pom.xml

```
<properties>
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError> (1)
        <maven-checkstyle-plugin.failsOnViolation>true
        </maven-checkstyle-plugin.failsOnViolation> (2)
        <maven-checkstyle-plugin.includeTestSourceDirectory>true
        </maven-checkstyle-plugin.includeTestSourceDirectory> (3)
</properties>

<build>
        <plugins>
            <plugin> (4)
                <groupId>io.spring.javaformat</groupId>
                <artifactId>spring-javaformat-maven-plugin</artifactId>
            </plugin>
            <plugin> (5)
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
            </plugin>
        </plugins>

    <reporting>
        <plugins>
            <plugin> (5)
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
            </plugin>
        </plugins>
    </reporting>
</build>
```

|**1**|                                    Fails the build upon Checkstyle errors                                    |
|-----|--------------------------------------------------------------------------------------------------------------|
|**2**|                                  Fails the build upon Checkstyle violations                                  |
|**3**|                                  Checkstyle analyzes also the test sources                                   |
|**4**|Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules|
|**5**|                           Add checkstyle plugin to your build and reporting phases                           |

If you need to suppress some rules (e.g. line length needs to be longer), then it’s enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example:

projectRoot/src/checkstyle/checkstyle-suppresions.xml

```
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
        "-//Puppy Crawl//DTD Suppressions 1.1//EN"
        "https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
    <suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
    <suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
</suppressions>
```

It’s advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script:

```
$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig
$ touch .springformat
```

### [](#ide-setup)[20.5. IDE setup](#ide-setup) ###

#### [](#intellij-idea)[20.5.1. Intellij IDEA](#intellij-idea) ####

In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin.
The following files can be found in the [Spring Cloud Build](https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools) project.

spring-cloud-build-tools/

```
└── src
    ├── checkstyle
    │   └── checkstyle-suppressions.xml (3)
    └── main
        └── resources
            ├── checkstyle-header.txt (2)
            ├── checkstyle.xml (1)
            └── intellij
                ├── Intellij_Project_Defaults.xml (4)
                └── Intellij_Spring_Boot_Java_Conventions.xml (5)
```

|**1**|                         Default Checkstyle rules                         |
|-----|--------------------------------------------------------------------------|
|**2**|                            File header setup                             |
|**3**|                        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|

![Code style](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/images/intellij-code-style.png)

Figure 1. Code style

Go to `File` → `Settings` → `Editor` → `Code 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.

![Code style](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/images/intellij-inspections.png)

Figure 2. Inspection profiles

Go to `File` → `Settings` → `Editor` → `Inspections`. 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](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/images/intellij-checkstyle.png)

Go to `File` → `Settings` → `Other settings` → `Checkstyle`. 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` : `[raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/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:

* `checkstyle.header.file` - please point it to the Spring Cloud Build’s, `spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` file either in your cloned repo or via the `[raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt)` URL.

* `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build’s, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `[raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml)` URL.

* `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you’re working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.

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

### [](#duplicate-finder)[20.6. Duplicate Finder](#duplicate-finder) ###

Spring Cloud Build brings along the `basepom:duplicate-finder-maven-plugin`, that enables flagging duplicate and conflicting classes and resources on the java classpath.

#### [](#duplicate-finder-configuration)[20.6.1. Duplicate Finder configuration](#duplicate-finder-configuration) ####

Duplicate finder is **enabled by default** and will run in the `verify` phase of your Maven build, but it will only take effect in your project if you add the `duplicate-finder-maven-plugin` to the `build` section of the projecst’s `pom.xml`.

pom.xml

```
<build>
    <plugins>
        <plugin>
            <groupId>org.basepom.maven</groupId>
            <artifactId>duplicate-finder-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
```

For other properties, we have set defaults as listed in the [plugin documentation](https://github.com/basepom/duplicate-finder-maven-plugin/wiki).

You can easily override them but setting the value of the selected property prefixed with `duplicate-finder-maven-plugin`. For example, set `duplicate-finder-maven-plugin.skip` to `true` in order to skip duplicates check in your build.

If you need to add `ignoredClassPatterns` or `ignoredResourcePatterns` to your setup, make sure to add them in the plugin configuration section of your project:

```
<build>
    <plugins>
        <plugin>
            <groupId>org.basepom.maven</groupId>
            <artifactId>duplicate-finder-maven-plugin</artifactId>
            <configuration>
                <ignoredClassPatterns>
                    <ignoredClassPattern>org.joda.time.base.BaseDateTime</ignoredClassPattern>
                    <ignoredClassPattern>.*module-info</ignoredClassPattern>
                </ignoredClassPatterns>
                <ignoredResourcePatterns>
                    <ignoredResourcePattern>changelog.txt</ignoredResourcePattern>
                </ignoredResourcePatterns>
            </configuration>
        </plugin>
    </plugins>
</build>
```