使用k8s部署Nginx服务,Nginx对外提供服务只希望部署在其中一台主机,该主机不提供其他服务
一.设置标签及污点
为了保证nginx之能分配到nginx服务器需要设置标签和污点,设置标签可以让Pod选择该服务器部署,设置污点可以使其他服务Pod无法部署在该服务器
本次部署nginx服务器IP为192.168.1.232
设置标签
#设置标签 key为typevalue为nginx kubectl label node 192.168.1.232 type=nginx #查看标签 kubectl get node 192.168.1.232 --show-labels NAME STATUS ROLES AGE VERSION LABELS 192.168.1.232 Ready <none> 30h v1.17.4 kubernetes.io/arch=amd64,kubernetes.io/hostname=192.168.1.232,kubernetes.io/os=linux,type=nginx
设置污点
#给node192.168.1.232设置污点key为key值为nginx effec为NoSchedule永不调度 #除非在Pod里设置了对应的tolerations参数 kubectl taint node 192.168.1.232 key=nginx:NoSchedule
查看污点
kubectl describe node 192.168.1.232
二.设置Nginx-deployment的yaml文件
# cat nginx-deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: labels: app: nginx name: nginx-deployment spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - image: nginx:1.14.0 name: nginx #标签选择器 nodeSelector: type: nginx #设置污点可以调度到对应服务器 tolerations: - key: "key" operator: "Equal" value: "nginx" effect: "NoSchedule"
应用启动
kubectl apply -f nginx-deployment.yaml
查看已经调度到对应的服务器
# kubectl get pod -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES nginx-deployment-57f94c46b4-5whb5 1/1 Running 0 6h30m 172.17.97.3 192.168.1.232 <none> <none>
三.设置Nginx配置文件和程序根目录挂载
启动的Nginx使用默认的配置文件和默认的网站根目录,需要使用volume挂载
# cat nginx-deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: labels: app: nginx name: nginx-deployment spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - image: nginx:1.14.0 name: nginx volumeMounts: - name: conf mountPath: /etc/nginx - name: opt mountPath: /opt #标签选择器 nodeSelector: type: nginx #设置污点可以调度到对应服务器 tolerations: - key: "key" operator: "Equal" value: "nginx" effect: "NoSchedule" volumes: - name: conf hostPath: path: /etc/nginx type: Directory - name: opt hostPath: path: /opt type: Directory
本次使用了本机挂载hostPath挂载配置文件及根目录,生产环境最好使用pvc挂载
四.设置Service对外提供服务
# cat nginx-service.yaml apiVersion: v1 kind: Service metadata: labels: app: nginx name: nginx-deployment spec: ports: - port: 80 name: nginx-service80 protocol: TCP targetPort: 80 nodePort: 80 - port: 81 name: nginx-service81 protocol: TCP targetPort: 81 nodePort: 81 selector: app: nginx type: NodePort
PS:使用NodePort启用端口对外提供服务,如果对外映射多个端口需要在port参数下加参数name定义名称,单个端口无需设置参数name
k8s默认使用NodePort对外映射端口为30000-50000如需要映射其他端口需要修改配置文件/opt/kubernetes/cfg/kube-apiserver,修改端口范围