## service
--pod-network-cidr=10.244.0.0/16 (pod网段)
--service-cidr=10.96.0.0/12 (service网段)
```
[root@master maintest]# cat pod.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
selector:
matchLabels:
run: my-nginx
replicas: 2
template:
metadata:
labels:
run: my-nginx
spec:
containers:
- name: my-nginx
image: nginx
ports:
- containerPort: 80
```
service 默认type类型为ClusterIP
```
[root@master maintest]# cat service.yaml
apiVersion: v1
kind: Service
metadata:
name: my-nginx
labels:
run: my-nginx
spec:
ports:
- port: 80
protocol: TCP
selector:
run: my-nginx
```
service 代理到对应的后端pod
### 映射到宿主机端口
**.service.spec.type**
**NodePort**
```
apiVersion: v1
kind: Service
metadata:
name: my-nginx
labels:
run: my-nginx
spec:
ports:
- port: 80
protocol: TCP
type: NodePort
selector:
run: my-nginx
```
```
[root@master maintest]# kubectl get svc -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 69d <none>
my-nginx NodePort 10.106.132.151 <none> 80:30994/TCP 21h run=my-nginx
```
**访问node节点的ip:30994---->service ip:80---->pod ip:80**
### 创建没有selector的service
```
[root@master maintest]# cat noselector.yaml
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
ports:
- port: 80
protocol: TCP
targetPort: 3306
```
endpoint.yaml
```
[root@master maintest]# cat endpoint.yaml
apiVersion: v1
kind: Endpoints
metadata:
name: my-service
subsets:
- addresses:
- ip: 1.2.3.4
ports:
- port: 3306
```
```
[root@master maintest]# kubectl describe svc my-service
Name: my-service
Namespace: default
Labels: <none>
Annotations: <none>
Selector: <none>
Type: ClusterIP
IP Families: <none>
IP: 10.104.205.156
IPs: <none>
Port: <unset> 80/TCP
TargetPort: 3306/TCP
Endpoints: 1.2.3.4:3306
Session Affinity: None
Events: <none>
```
### 创建type是ExternalName的service
```
[root@master maintest]# cat external.yaml
apiVersion: v1
kind: Service
metadata:
name: my-service
namespace: prod
spec:
type: ExternalName
externalName: my.database.example.com
```