Set Filesystem and Volumes to Read-only

Run containers with a read-only filesystem using --read-only flag.

For example:

docker run --read-only alpine sh -c 'echo "whatever" > /tmp'

If an application inside a container has to save something temporarily, combine --read-only flag with --tmpfs using the following command:

docker run --read-only --tmpfs /tmp alpine sh -c 'echo "whatever" > /tmp/file'

Equivalent in the docker-compose file will be:

Copy
version: "3" 
services: 
  alpine: 
    image: alpine 
    read_only: true 

Equivalent in kubernetes in Security Context will be:

Copy
kind: ... 
apiVersion: ... 
metadata: 
  name: ... 
spec: 
...
  containers: 
  - name: ... 
    image: .... 
    securityContext: 
...
          readOnlyRootFilesystem: true 
...

In addition, if the volume is mounted only for reading mount them as a read-only. It can be done by appending :ro to -v:

docker run -v volume-name:/path/in/container:ro alpine

Or by using --mount option:

docker run --mount source=volume-name,destination=/path/in/container,readonly alpine