参考链接:https://kubernetes.io/docs/tasks/run-application/run-single-instance-stateful-application/
一、创建service
apiVersion: v1
kind: Service
metadata:
name: mysql
labels:
app: mysql
namespace: admin-d2069c
spec:
ports:
- name: mysql
port: 3306
clusterIP: None
selector:
app: mysql
二、创建StatefulSet
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
name: mysql
namespace: admin-d2069c
spec:
serviceName: mysql
replicas: 1
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
namespace: admin-d2069c
spec:
containers:
- name: mysql
image: mysql:5.7
env:
- name: MYSQL_ROOT_PASSWORD
value: "123"
ports:
- name: mysql
containerPort: 3306
volumeMounts:
- name: lihaile
mountPath: /var/lib/mysql
subPath: mysql
- name: conf
mountPath: /etc/mysql/conf.d
resources:
requests:
cpu: 300m
memory: 200M
livenessProbe:
exec:
command: ["mysqladmin", "-h", "127.0.0.1", "-uroot", "-p123", "ping"]
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
readinessProbe:
exec:
# Check we can execute queries over TCP (skip-networking is off).
command: ["mysql", "-h", "127.0.0.1", "-uroot", "-p123", "-e", "SELECT 1"]
initialDelaySeconds: 5
periodSeconds: 2
timeoutSeconds: 1
volumes:
- name: conf
emptyDir: {}
- name: config-map
configMap:
name: mysql
volumeClaimTemplates:
- metadata:
name: lihaile
annotations:
volume.beta.kubernetes.io/storage-class: "managed-nfs-storage"
namespace: admin-d2069c
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 2Gi
三、创建访问Service
apiVersion: v1
kind: Service
metadata:
name: mysql-access
labels:
app: mysql
namespace: admin-d2069c
spec:
ports:
- name: mysql
port: 3306
selector:
app: mysql
查看Mysql
root@node4:~# kubectl -n admin-d2069c get pvc,pv,statefulset,pod,service |grep mysql
pvc/storage-mysql-0 Bound pvc-a6c63604-c2ee-11e8-b599-0050568eef9f 512M RWX managed-nfs-storage 18s
pv/pvc-a6c63604-c2ee-11e8-b599-0050568eef9f 512M RWX Delete Bound admin-d2069c/storage-mysql-0 managed-nfs-storage 18s
statefulsets/mysql 1 1 18s
po/mysql-0 1/1 Running 0 18s
svc/mysql ClusterIP None <none> 3306/TCP 18s
svc/mysql-access ClusterIP 10.68.31.80 <none> 3306/TCP 18s
ing/mysql-access jekens.com 80 18s
五、测试
1、查看集群详情和状态
root@node4:~# mysql -h 10.68.31.80 -p123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 124
Server version: 5.7.23 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
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> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
mysql>