# K8s 基本部署
[TOC]
---
## Service
----
### 什麼是 service
1. pods 的生命是有限的,其有一個生命週期。node當機時,上面的pod就都會不見。我們會設定ReplicaSet來規定一個cluster上pod的數量,讓這pods在其它node上重新建立以保證應用程式不會當機。
----
2. 舉例來說,如果有一個網頁是由三個replicas,前端程式不會管後端有幾個replicas,如果pod死了再被建立了,也沒有人知道。在k8s中所謂的service一個抽象層,用來定義pods和存取其規則。service讓pods鬆散的結合在一起。
3. service 也是用 `yaml` 來定義。雖然每個 pod 都有獨一的 ip,但我們的 service 會有一個共用 ip 及K8s internal domain 來代表這些 pods 組成的 service 的服務。
----
### Label Selector Matching

----
### 範例
#### 定義 Pod
```yaml!
# pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: foo
labels:
app: foo
type: demo
spec:
containers:
- name: foo
image: mikehsu0618/foo
ports:
- containerPort: 8080
```
----
#### 定義 Service
```yaml=
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
type: demo
type: LoadBalancer # LoadBalancer, ClusterIP, NodePort
ports:
- protocol: TCP
port: 8000
targetPort: 8080
```
----
#### Configuration
----
here are some important metadata explanation
1. **spec.type**: Defines the type of Service
- **ClusterIP**:
The default type, only reachable within the cluster
- **NodePort**:
exposes the Service on a static port on each Node's IP address.
- **LoadBalancer**:
expose the Service externally using a cloud provider’s load balancer.
----
2. **spec.ports**:
- **port**:
The port number on which the Service's Cluster IP is exposed.
- **nodePort**:
The port number on the Node object that maps to the `targetPort`. If not specified in the Service configuration, Kubernetes will select a port number randomly.
----
3. **spec.ports.protocol**: The protocol supported by the Service, which can be TCP, SCTP, or UDP, with TCP being the default.
4. **spec.selector**: The selector helps to filter and direct traffic to Pods with specific labels. In this example, traffic for the specified port number is directed to Pods labeled with `type=demo`.
----
#### Client Interaction
```bash!
kubectl get svc
kubectl describe svc [SERVICE_NAME]
# access the service via `localhost:[LOCAL_PORT]`
kubectl port-forward service/[SERVICE_NAME] [LOCAL_PORT]:[SERVICE_PORT]
kubectl proxy
# http://localhost:8001/api/v1/namespaces/<namespace>/services/<service-name>:http/proxy/
```
---
### Deployment
----
#### 基本概念
- **Deployment** 是 Kubernetes 的一個核心資源對象,提供了對 **Pod** 和 **ReplicaSet** 的聲明式管理。
- 官方建議通過 Deployment 進行 Pod 和 ReplicaSet 的佈署。
----
- 典型應用場景包括:
- 定義 Deployment 來創建 Pod 和 ReplicaSet。
- 實現滾動升級和回滾應用(不停機更新)。
- 進行擴容和縮容。
- 暫停和繼續 Deployment。
----
#### ReplicaSet 的作用
- **ReplicaSet** 確保在資源允許的前提下,指定數量的 Pod 與使用者期望的狀態一致。
- 官方建議將 ReplicaSet 與 Deployment 一起使用。
----
#### Kubernetes 中的對應關係
- Deployment, ReplicaSet, 和 Pod 在 Kubernetes 中的對應關係。

----
#### Deployment 使用案例
1. 創建 Deployment
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: foo-deployment
labels:
type: demo
spec:
replicas: 1
selector:
matchLabels:
type: demo
template:
metadata:
labels:
type: demo
spec:
containers:
- name: foo
image: mikehsu0618/foo
ports:
- containerPort: 8080
```
----
#### Configuration
1. **metadata.labels**: Key-value pairs that are used to organize and categorize different Kubernetes objects, including Deployments.
2. **spec.replicas**: Specifies the number of desired replicas (instances) of the application.
3. **spec.selector.matchLabels**: Used for identifying the set of Pods that this Deployment is supposed to manage. It should match the labels of the Pods.
----
4. **spec.template.metadata.labels**: Defines the labels for the Pods being created under this Deployment. These labels should match the `spec.selector.matchLabels`.
5. Pod-Like Metadata
- **spec.template.spec.containers.name**
- **spec.template.spec.containers.image**
- **spec.template.spec.containers.ports.containerPort**
- **spec.template.spec.containers.env**
----
6. **spec.strategy**: (Optional) Defines the strategy used to replace old Pods by new ones. Commonly `RollingUpdate` or `Recreate`.

----
7. **spec.strategy.rollingUpdate.maxSurge** and **spec.strategy.rollingUpdate.maxUnavailable**: (Optional, applicable if strategy is `RollingUpdate`) Control how Pods are replaced.

----
#### 常見操作
- 更新 Deployment 期望水平擴展
```bash
kubectl scale deployment bar-deployment --replicas 3
```
- 查看更新歷史:
```bash
kubectl rollout history deployment foo-deployment
```
- 回滾到指定版本:
```bash
kubectl rollout undo deployment foo-deployment --to-revision=1 --record
```
---
### Ingress

----
#### Roles of Ingress
Ingress is primarily responsible for
1. **Routing Different Paths to Services**: Configured hostnames and pathnames allow access to corresponding Services and their Pods.
2. **Load Balancing Traffic**: Implements load balancing algorithms and backend weighting schemes.
----
3. **Supporting SSL Termination**: Handles the decryption for HTTPS traffic, facilitating unencrypted communication between Services and Pods.
4. **Virtual Hosting**: Ingress allows setting up virtual domains under the same IP, referred to as hostnames.
----
#### Installing Ingress
To install Ingress in a K8s cluster, run the following command:
```shell
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.2.1/deploy/static/provider/cloud/deploy.yaml
```
This command sets up an `ingress-nginx` namespace and related services in Kubernetes.
----
#### Simple Fanout and Virtual Hosting
Fanout in Ingress allows routing traffic from a single IP address to multiple Services based on the request URL.

----
```yaml!
// ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ingress
spec:
ingressClassName: nginx
rules:
- host: foo.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: foo-service
port:
number: 8000
- host: bar.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: bar-service
port:
number: 8000
```
----
#### Configuration
1. **metadata.annotations**: Optional field for including additional information and functionality using annotations. Commonly used for configuring Ingress controller behavior.
```yaml!
annotations:
# customize the behavior of an NGINX Ingress controller.
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/ssl-redirect: "false"
nginx.ingress.kubernetes.io/affinity: "cookie"
# specify resource limits for a pod
resources.limits.memory: "500Mi"
resources.limits.cpu: "1"
```
----
2. **spec.rules**: A list of host rules used to configure the Ingress.
- **spec.rules[ ].host**: The domain name
- **spec.rules[ ].http.paths**: A list of paths and associated backends.
- **path**: Defines the URL path for the backend service
- **pathType**: Specifies the path matching type (`Prefix`, `Exact`, etc.).
- **backend.service.name**: The name of the backend service.
- **backend.service.port.number**: The service port number or name.
----
3. **spec.defaultBackend**: Specifies the backend to use when no rule matches. It's optional but recommended for handling traffic that does not match any of the defined rules.
- **spec.defaultBackend.service.name**: The name of the default backend service.
- **spec.defaultBackend.service.port.number** or **.name**: The service port number or name for the default backend.
----
4. **spec.tls**: Optional configuration for TLS. It specifies the TLS certificate to use.
- **spec.tls[ ].hosts**: Array of hosts included in the TLS certificate.
- **spec.tls[ ].secretName**: The name of the K8s `secret` object used to terminate TLS traffic.
---
## Conclusion
In this session, we delved into the foundational aspects of Kubernetes (K8s) with a focus on Services, Deployments, and Ingress. Let's recap the key takeaways:
----
### Recap: Service
- **Service Lifecycle & Pods**: Services abstract pod lifecycle, ensuring continuous application availability even when nodes or pods fail.
- **Service Definitions & Access**: Defined using YAML, services provide a stable IP and domain within K8s for accessing a group of pods.
- **Label Selector Matching**: Services use selectors to identify and manage groups of pods.
----
### Recap: Deployment
- **Deployment as a K8s Core Object**: It provides declarative management of Pods and ReplicaSets.
- **Deployment Use Cases**: Ideal for rolling updates, scaling, and managing application versions.
- **ReplicaSet Integration**: Ensures a specified number of pod replicas run at any given time.
----
### Recap: Ingress
- **Ingress Functions**: Manages external access to services, load balancing, SSL termination, and virtual hosting.
- **Ingress Installation**: Typically installed in a K8s cluster through a command-line interface.
- **Routing and Virtual Hosting**: Utilizes a single IP for routing to multiple services and supports multiple virtual domains.
----
### Overall Benefits
- **Scalability**: Both Services and Deployments offer scalable solutions for managing applications in Kubernetes.
- **Reliability**: Ensures continuous operation through pod and node failures.
- **Flexibility**: Supports complex routing and scaling strategies for modern cloud-native applications.
---
**Thank you for participating!**
---
## Reference
- [x] 1. [Kubernetes 的組件
](https://ithelp.ithome.com.tw/articles/10287576)
- [x] 2. [實戰做一個 Pod](https://ithelp.ithome.com.tw/articles/10288199)
- [x] 3. [實戰做一個 Service](https://ithelp.ithome.com.tw/articles/10288389)
- [x] 4. [實戰做一個 Deployment](https://ithelp.ithome.com.tw/articles/10288602)
- [x] 5. [Ingress](https://ithelp.ithome.com.tw/articles/10288843)
- [x] 6. [部署策略](https://ithelp.ithome.com.tw/articles/10289496)
- [x] [Grayscale](https://ithelp.ithome.com.tw/articles/10290317)
- [x] [Canry](https://ithelp.ithome.com.tw/articles/10290852)
{"title":"K8s 第二週 [Deployment, Service, Ingress]","contributors":"[{\"id\":\"60f87ada-c8bc-4f5d-9b91-2a0d3103440d\",\"add\":14783,\"del\":4160}]","description":"servicepods的生命是有限的,其有一個生命週期。node當機時,上面的pod就都會不見。我們會設定ReplicaSet來規定一個cluster上pod的數量,讓這pods在其它node上重新建立以保證應用程式不會當機。"}