Best practice for using certificates (.pem) files in a container

9/3/2020

i'm learning docker/k8s; I want to pass/store a .pem file to my boostrap container which runs on a k8s cluster. This container uses the .pem to create a k8s secret (kubectl create secrets ...) which will be used by the other apps running on k8s by mounting the kubernetes secrets.

I can think of the following options,

  • I can pass the .pem details as ENV to the container.
  • I can build the image with the .pem file.
  • I can store the .pem file in S3 and download it from within the container.

Wanted to understand which of these is the best practice/secure method to accomplish this task.

-- nevosial
certificate
docker
kubernetes

2 Answers

11/11/2021

(Although one could say that K8S Secrets are type of Config map). <br> I think that the better approach is to use K8S Secrets (over Config maps) like specified in here.

apiVersion: v1
kind: Secret
metadata:
  name: secret-tls
type: kubernetes.io/tls
data:
  # the data is abbreviated in this example
  tls.crt: |
        MIIC2DCCAcCgAwIBAgIBATANBgkqh ...
  tls.key: |
        MIIEpgIBAAKCAQEA7yn3bRHQ5FHMQ ...

Then you can create a pod that has access to the secret data through a Volume:

apiVersion: v1
kind: Pod
metadata:
  name: secret-test-pod
spec:
  containers:
    - name: test-container
      image: nginx
      volumeMounts:
        # name must match the volume name below
        - name: secret-volume
          mountPath: /etc/secret-dir
  # The secret data is exposed to Containers in the Pod through a Volume.
  volumes:
    - name: secret-volume
      secret:
        secretName: secret-tls

(*) In this specific example the tls.crt and tls.key will be created under /etc/secret-dir.

-- RtmY
Source: StackOverflow

9/3/2020

I have seen it done in multiple ways but I would suggest using a config map so that then the pem file lives inside your k8s cluster and you don't have to deal with encryption within s3 and such. Also this allows your devops team to handle the maintenance rather than the app developers if you include this within the docker code

Config Map Kubernetes Docs

1) Create the config map

   kubectl -n <namespace-for-config-map-optional> create configmap ca-pemstorefrom-file=my-cert.pem

2) Add new config to your pod yaml file

    apiVersion: v1 
    kind: Pod
    metadata:
      name: <some metadata name>
    spec:
        containers:
        - name: <container name>
          image: <container image>
          volumeMounts:
          - name: ca-pemstore
            mountPath: /etc/ssl/certs/my-cert.pem
            subPath: my-cert.pem
            readOnly: false
          ports:
          - containerPort: 80
          command: ...
          args: ...
        volumes:
        - name: ca-pemstore
          configMap:
            name: ca-pemstore
-- Edward Romero
Source: StackOverflow