I wanted to create some mysql users and databases while creating mysql deployment in kubernetes.
means when mysql deployment is being created its shouldalso create some users as well as database in the mysql.
Below is the deployment config i have created for mysql. let me know is it possible to add here some data which will create the user and database.
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
ports:
- port: 3306
selector:
app: mysql
clusterIP: None
---
apiVersion: v1
kind: Service
metadata:
name: phpmyadmin
spec:
ports:
- port: 80
protocol: TCP
nodePort: 30081
selector:
app: mysql
type: NodePort
---
apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
name: mysql
spec:
selector:
matchLabels:
app: mysql
strategy:
type: Recreate
template:
metadata:
labels:
app: mysql
spec:
containers:
- image: mysql:5.6
name: mysql
env:
- name: MYSQL_ROOT_PASSWORD
valueFrom:
configMapKeyRef:
name: mysql-config
key: mysql_root_password
ports:
- containerPort: 3306
name: mysql
volumeMounts:
- name: mysql-persistent-storage
mountPath: /var/lib/mysql
- image: phpmyadmin:5
name: phpmyadmin
env:
- name: MYSQL_ROOT_PASSWORD
value: password
- name: PMA_HOST
value: mysql
ports:
- containerPort: 80
volumes:
- name: mysql-persistent-storage
persistentVolumeClaim:
claimName: mysql-pv-claim
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: mysql-pv-volume
labels:
type: local
spec:
storageClassName: manual
capacity:
storage: 20Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-pv-claim
spec:
storageClassName: manual
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi
2
Answers
You can do it using
postStart
of Container Lifecycle Hooks. It makes you run additional SQL or script after starting your mysql container.For instance, if you create your own script
create_user.sh
that is executed some DDL likeCREATE USER IF NOT EXISTS 'user'@'localhost' IDENTIFIED BY 'password';
throughmysql
command, then you can configure it as follows.Refer Attach Handlers to Container Lifecycle Events for more configuration details.
In the mysql docker image (under "Initializing a fresh instance"): you can use the
/docker-entrypoint-initdb.d
as a point to which to volume mount scripts and SQL files for database initialization.