Kubernetes实战-从零开始搭建微服务
准备写一个Kubernetes实战系列教程,毕竟cnblogs做为国内最先的技术博客如今都已经开始迁移到Kubernetes了,此处要有掌声给博客园
。系列会更加偏向于实战,对于理论只在须要时讲解。javascript
Docker hub 上我我的觉着有两个奇葩的镜像imagejava
不少人对k8s的学习都是从minikube开始,可是,可是,可是,当你亲身对比kind和minikube的时候,会发现kind至少速度快三倍(在我这台mac老本上)。node
须要提早安装好linux
brew install kind
curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.8.1/kind-$(uname)-amd64 chmod +x ./kind mv ./kind /some-dir-in-your-PATH/kind
试试运行 kind --version
确保kind的安装正确。git
须要大概2~3分钟, kind create cluster
github
会建立一个cluster 名字为kind-kinddocker
kubectl cluster-info
了解下cluster 情况shell
Kubernetes master is running at https://127.0.0.1:51842 KubeDNS is running at https://127.0.0.1:51842/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
其中的连接即便你的k8s control planeexpress
若是再运行docker ps
, 至少会有一个kind-control-plane 的container 在运行。npm
能够再试试如下命令:
kind get clusters
获取全部clusterkubectl config get-contexts
kubectl get nodes -o wide
kubectl get svc
截止目前,一个单节点的k8s集群就在本地的docker环境里搭建好了。?
建立如下文件,并保存。
const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => res.send('Hello World! running on kubernetes')) app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
package.json
, package-lock.json
整个项目文件,请访问github repo
FROM node:14.2.0-alpine EXPOSE 3000 WORKDIR /anode ADD package.json . ADD package-lock.json . RUN npm ci ADD . . CMD ["node", "index.js"]
克隆全部须要的代码和配置文件。 在push镜像以前,不要忘了docker login
。
docker build -t {your dockerhub name}/a-node:v1 . docker push {your dockerhub name}/a-node:v1
apiVersion: apps/v1 kind: Deployment metadata: name: a-node-deployment labels: app: node spec: replicas: 1 selector: matchLabels: app: a-node template: metadata: labels: app: a-node spec: containers: - name: a-node-container image: tim010/a-node:v1 # or your own image ports: - containerPort: 3000
apiVersion: v1 kind: Service metadata: name: a-node-service spec: ports: - targetPort: 3000 protocol: TCP port: 80 selector: app: a-node-service type: NodePort
kubectl apply -f deployment.yaml
deployment.apps/a-node-deployment created
kubectl apply -f service.yaml
service/a-node-service created
为了确保发布成功,运行
kubectl get pods
应该会输出如图的结果,不要忘了复制你的pod名。
kubectl get service
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE a-node-service NodePort 10.111.52.71 <none> 80:32709/TCP 7h25m kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 8h
等等,即便发布成功了,个人app在哪呢?
http://10.111.52.71:3000
? localhost:3000
你须要端口转发
kubectl port-forward {your port name for deployment 你的pod名} 3000:3000
kubectl delete -f deployment.yml kubectl delete -f service.yml
kind delete cluster
至此,你的本地k8s 集群生命终结。
动手去作永远都会比只学习理论要快得多,但愿这第一个教程可让你们都快速上手,不被K8s复杂的概念吓到。系列后续会写一些更多关于Kubernetes 高可用性 和架构的。