一、Hello World
使用镜像的代码为:
js
const http = require('http')
const os = require('os')
const hostname = os.hostname()
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(`Hello world from ${hostname}`)
})
server.listen(9000)
Dockerfile为:
FROM node:10-slim
EXPOSE 9000
COPY server.js .
CMD node server.js
1. 创建Deployment
sh
$ kubectl create deployment hello-node --image=syaning/hello-node:v1
然后查看Deployment:
sh
$ kubectl get deployments
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
hello-node 1 1 1 1 17s
查看Pod:
sh
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
hello-node-7c675c487d-cswr4 1/1 Running 0 20s
2. 创建Service
sh
$ kubectl expose deployment hello-node --type=LoadBalancer --port=9000
然后查看Service:
sh
$ kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
hello-node LoadBalancer 10.96.78.62 localhost 9000:32523/TCP 6s
此时访问 localhost:9000
即可看到结果。
3. 扩容
sh
$ kubectl scale --replicas=3 deployment.apps/hello-node
查看Pod:
sh
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
hello-node-7c675c487d-cswr4 1/1 Running 0 5m
hello-node-7c675c487d-jrc8b 1/1 Running 0 13s
hello-node-7c675c487d-sqhx8 1/1 Running 0 13s
查看Deployment:
sh
$ kubectl get deployments
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
hello-node 3 3 3 3 5m
此时多次访问 localhost:9000
,结果会发生改变,即响应是来自不同的Pod。
4. 更新
sh
$ kubectl set image deployment.apps/hello-node hello-node=syaning/hello-node:v2
再次访问 localhost:9000
,可以发现内容已经是新的了。
5. 删除
sh
$ kubectl delete service/hello-node
$ kubectl delete deployment.apps/hello-node
二、使用YAML
上面的例子是使用命令行来进行资源的管理,事实上更好的方式是使用YAML文件来描述资源。使用YAML文件可以描述更为复杂的对象和逻辑,更加容易操作和维护,并且使得变更可以进行版本管理。
1. 创建Deployment
定义deployment.yml
,内容如下:
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-node-deployment
labels:
app: hello-node
spec:
replicas: 3
selector:
matchLabels:
app: hello-node
template:
metadata:
labels:
app: hello-node
spec:
containers:
- name: hello-node
image: syaning/hello-node:v1
其中:
metadata
定义了Deployment本身的信息spec.replicas
定义了Pod的副本数spec.selector
指明了如何选择Podspec.template
定义了Pod的信息,如果当前运行的副本数不够,则会按照这个模板来进行创建
执行:
sh
$ kubectl create -f deployment.yml
2. 创建Service
定义service.yml
,内容如下:
yaml
apiVersion: v1
kind: Service
metadata:
name: hello-node-servcie
spec:
selector:
app: hello-node
ports:
- protocol: TCP
port: 9000
targetPort: 9000
type: LoadBalancer
然后执行:
sh
$ kubectl create -f service.yml
3. 扩容
将 deployment.yml
中 spec.replicas
调整为5,然后执行:
sh
$ kubectl apply -f deployment.yml
4. 更新
将 deployment.yml
最后一行改为 image: syaning/hello-node:v2
,然后执行:
sh
$ kubectl apply -f deployment.yml
5. 删除
sh
$ kubectl delete -f service.yml
$ kubectl delete -f deployment.yml