Skip to content

Instantly share code, notes, and snippets.

@steakunderscore
Last active May 23, 2023 16:45
Show Gist options
  • Save steakunderscore/df41d2fe81383f09f19eb6139d11b211 to your computer and use it in GitHub Desktop.
Save steakunderscore/df41d2fe81383f09f19eb6139d11b211 to your computer and use it in GitHub Desktop.
Example of using an init container chown the data in a pvc as a pod starts.
# Example of using an init container chown the data in a pvc as a pod starts. Useful for migrating
# which user and group your containers run as.
# Works by having an init container mount your data, chmod it before it's consumed by your main container.
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql-statefull
spec:
podManagementPolicy: OrderedReady
replicas: 1
revisionHistoryLimit: 3
selector:
matchLabels:
app: mysql
serviceName: mysql
template:
metadata:
labels:
app: mysql
spec:
initContainers:
- name: chowner-mysql-vol-01
image: registry.hub.docker.com/library/alpine:3.12.0
# This is where the magic hapens, find files with old UID (1004) and chown with new UID (1005) and GID (2005)
command: ["find", "/mnt", "-user", "1004", "-group", "2004", "-exec", "chown", "1005:2005", "{}", "+"]
securityContext:
readOnlyRootFilesystem: true
capabilities:
drop: ["all"]
add: ["CHOWN"]
runAsUser: 0
runAsNonRoot: false
volumeMounts:
- name: mysql-vol-01
mountPath: /mnt
containers:
- name: mysql
env:
# Use secret in real usage
- name: MYSQL_ROOT_PASSWORD
value: password
image: registry.hub.docker.com/library/mysql:8.0.21
ports:
- containerPort: 3306
name: mysql
protocol: TCP
securityContext:
allowPrivilegeEscalation: false
volumeMounts:
- name: mysql-vol-01
mountPath: /var/lib/mysql
securityContext:
runAsUser: 1005
runAsGroup: 2005
runAsNonRoot: true
fsGroup: 3005
terminationGracePeriodSeconds: 10
volumeClaimTemplates:
- apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-vol-01
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 1Gi
volumeMode: Filesystem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment