> For the complete documentation index, see [llms.txt](https://bohans.gitbook.io/devops/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bohans.gitbook.io/devops/kubernetes/ji-chu-zhi-shi/service/chuang-jian-service.md).

# 创建Service

## kubectl expose命令

Kubernetes提供了一种快速的方法，即通过kubectl expose命令来创建Service：

```properties
$ kubectl get rc webapp
NAME     DESIRED   CURRENT   READY   AGE
webapp   2         2         2       8m18s

$ kubectl expose rc webapp
service/webapp exposed

$ kubectl get svc webapp
NAME     TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
webapp   ClusterIP   10.107.208.89   <none>        8080/TCP   27s
```

注意：上述方式在使用前已经存在了一个名为webapp的ReplicationController，该rc创建了两个后端pod：

```properties
$ kubectl get rc webapp
NAME     DESIRED   CURRENT   READY   AGE
webapp   2         2         2       12m
```

## 使用yaml文件

<details>

<summary>webapp-svc.yaml</summary>

```yaml
apiVersion: v1
kind: Service
metadata:
  name: webapp-yaml
spec:
  selector:
    app: webapp
  ports:
  - port: 8081
    targetPort: 8080
```

</details>

使用kubectl create命令创建Service：

```properties
$ kubectl create -f webapp-svc.yaml 
service/webapp-yaml created
```

查看service的相关信息：

```properties
$ kubectl get svc webapp-yaml
NAME          TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
webapp-yaml   ClusterIP   10.103.141.105   <none>        8081/TCP   100s
```
