Ans: To disable write permissions in a Kubernetes pod, you can use several methods depending on the level of control you need. Here are the most common approaches:
- Using ReadOnlyRootFilesystem
- Setting Volume Mounts to Read-Only
- Using SecurityContext to Restrict Write Permissions
- Using PodSecurityPolicy (PSP)
1. Using ReadOnlyRootFilesystem:
You can set the securityContext
of the container to make the root filesystem read-only. This prevents the container from writing to any part of the filesystem that is not explicitly made writable.
apiVersion: v1
kind: Pod
metadata:
name: node-app
spec:
containers:
- name: node-app
image: node-app:v1.0
securityContext:
readOnlyRootFilesystem: true
volumeMounts:
- name: config-volume
mountPath: /etc/config
readOnly: true
volumes:
- name: config-volume
configMap:
name: myapp-config
In the above file
readOnlyRootFilesystem: true
ensures that the entire root filesystem is read-only.- Specific volumes (like the
config-volume
mounted at/etc/config
) are also set toreadOnly: true
.
2. Setting Volume Mounts to Read-Only
If you want to make specific volumes read-only, you can set the readOnly
flag in the volumeMounts
section of the container spec.
apiVersion: v1
kind: Pod
metadata:
name: node-app
spec:
containers:
- name: node-app
image: node-app:v1.0
volumeMounts:
- name: data-volume
mountPath: /data
readOnly: true
volumes:
- name: data-volume
persistentVolumeClaim:
claimName: myapp-data
In the above file the data-volume
mounted at /data
is read-only.
3. Using SecurityContext to Restrict Write Permissions
Ans: You can further restrict write permissions using the securityContext
by setting fsGroup
and runAsUser
. This ensures the container runs as a non-root user and the filesystem group ownership is managed.
apiVersion: v1
kind: Pod
metadata:
name: node-app
spec:
securityContext:
fsGroup: 2000
containers:
- name: node-app
image: node-app:v1.0
securityContext:
runAsUser: 1000
readOnlyRootFilesystem: true
volumeMounts:
- name: config-volume
mountPath: /etc/config
readOnly: true
volumes:
- name: config-volume
configMap:
name: myapp-config
In the above file:
- The container runs as a non-root user (
runAsUser: 1000
). - The filesystem group ownership is set (
fsGroup: 2000
). - The root filesystem is read-only.
Summary:
- ReadOnlyRootFilesystem: Set
securityContext.readOnlyRootFilesystem: true
to make the entire filesystem read-only. - Read-Only Volume Mounts: Use
volumeMounts.readOnly: true
to make specific volumes read-only. - SecurityContext: Use
securityContext
to run the container as a non-root user and set filesystem group ownership.