Inject code/files directly into a container in Kubernetes on Google Cloud Engine

It is possible to use ConfigMaps to achieve that goal:

The following example mounts a mariadb configuration file into a mariadb POD:

ConfigMap

apiVersion: v1
data:
  charset.cnf: |
    [client]
    # Default is Latin1, if you need UTF-8 set this (also in server section)
    default-character-set = utf8 

    [mysqld]
    #
    # * Character sets
    #
    # Default is Latin1, if you need UTF-8 set all this (also in client section)
    #
    character-set-server  = utf8 
    collation-server      = utf8_unicode_ci 

kind: ConfigMap
metadata:
  name: mariadb-configmap

MariaDB deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: mariadb
  labels:
    app: mariadb  
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: mariadb
        version: 10.1.16
    spec:
      containers:
      - name: mariadb
        image: mariadb:10.1.16
        ports:
        - containerPort: 3306
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mariadb
              key: rootpassword
        volumeMounts:
        - name: mariadb-data
          mountPath: /var/lib/mysql
        - name: mariadb-config-file
          mountPath: /etc/mysql/conf.d   
      volumes:
      - name: mariadb-data
        hostPath: 
          path: /var/lib/data/mariadb
      - name: mariadb-config-file
        configMap:
          name: mariadb-configmap

It is also possible to use subPath feature that is available in kubernetes from version 1.3, as stated here.


I'm not sure you can do that exactly. Kubernetes does things quite differently than docker, and isn't really ideal for interacting with the 'host' you are probably used to with docker.

A few alternative possibilities come to mind. First, and probably least ideal but closest to what you are asking, would be to add the file after the container is running, either by adding commands or args to the pod spec, or using kubectl exec and echo'ing the contents into the file. Second would be to create a volume where that file already exists, e.g. create a GCE or EBS disk, add that file, and then mount the file location (read-only) in the container's spec. Third, would be to create a new docker image where that file or other code already exists.

For the first option, the kubectl exec would be for one-off jobs, it isn't very scalable/repeatable. Any creation/fetching at runtime adds that much overhead to the start time for the container, so I normally go with the third option, building a new docker image whenever the file or code changes. The more you change it, the more you'll probably want a CI system (like drone) to help automate the process.

Add a comment if I should expand any of these options with more details.