1、使用如下yaml文件部署mysql服务
1.1、创建deployment
cat mysql-deplpy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
k8s.kuboard.cn/name: mysql
name: mysql
namespace: default
spec:
progressDeadlineSeconds: 600
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
k8s.kuboard.cn/name: mysql
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
labels:
k8s.kuboard.cn/name: mysql
spec:
containers:
- env:
- name: MYSQL_ROOT_PASSWORD
value: '123456'
image: 'mysql:5.7'
imagePullPolicy: IfNotPresent
name: mysql
lifecycle:
preStop: #优雅的停止服务
exec:
command:
[
"/bin/sh"
"-c"
"echo this pod is stopping. > /stop.log && sleep 30s" #优雅停止服务时间
]
ports:
- containerPort: 3306
name: mysql-port
protocol: TCP
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
terminationGracePeriodSeconds: 40 #优雅的停止服务,此值必须大于preStop的sleep值
1.2、创建service
cat mysql-svc.yaml
apiVersion: v1
kind: Service
metadata:
labels:
k8s.kuboard.cn/name: mysql
name: mysql
namespace: default
spec:
ports:
- name: mysql-port
nodePort: 30295
port: 3306
protocol: TCP
targetPort: 3306
selector:
k8s.kuboard.cn/name: mysql
type: NodePort
2、应用yaml文件创建服务
kubectl apply -f mysql-deplpy.yaml
kubectl apply -f mysql-svc.yaml
3、查看是否创建成功
[root@master ~]# kubectl get pod,svc
NAME READY STATUS RESTARTS AGE
pod/mysql-6c9b459c75-lk6dq 1/1 Running 0 1h
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/mysql NodePort 10.106.41.29 <none> 3306:30295/TCP 1h
4、进入容器
[root@master ~]# kubectl exec -it mysql-6c9b459c75-lk6dq bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@mysql-6c9b459c75-lk6dq:/#
root@mysql-6c9b459c75-lk6dq:/#
root@mysql-6c9b459c75-lk6dq:/#
root@mysql-6c9b459c75-lk6dq:/#
root@mysql-6c9b459c75-lk6dq:/# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 5.7.38 MySQL Community Server (GPL)
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sonar |
| sys |
+--------------------+
5 rows in set (0.00 sec)
5、mysql服务部署完成,可以使用集群内地址或者nodeport方式进行mysql数据库连接