K8S app source code and runtime separate in pod

In a k8s environment, it is a good choice to have the application runtime and source code build packages separated in separate containers

Smallest source code build image

use a smallest base image to build docker image store source code build result package

1FROM alpine:latest
2WORKDIR /var/www
3COPY app /var/www/app

Use different images of the runtime environment according to different programming languages

1FROM python:3.6.15-slim
2
3RUN pip install boto3

Build app image and runtime image

1# build the app image
2docker build . -t local.dev/py-app:v1
3# build the runtime image
4docker build . -t local.dev/python-3.6:latest

Use kubernetes pod initContainers to share app package to runtime container.

when pod launching the initContainer copy app all package content to shared data volume

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  # Unique key of the Deployment instance
 5  name: deployment-py-app
 6spec:
 7  # 3 Pods should exist at all times.
 8  replicas: 3
 9  selector:
10    matchLabels:
11      app: py-app
12  template:
13    metadata:
14      labels:
15        # Apply this label to pods and default
16        # the Deployment label selector to this value
17        app: py-app
18    spec:
19      initContainers:
20      - name: py-app-source-code
21        image: local.dev/py-app:v1
22        # init container and app runtime use emtpyvolume shared data
23        command: ["sh", "-c", "cp -r /var/www/app/* /var/shared/data/"]
24        imagePullPolicy: IfNotPresent        
25        volumeMounts:
26        - name: app-data
27          mountPath: /var/shared/data
28      containers:      
29      - name: app-runtime
30        # Run this image
31        image: local.dev/python-3.6:latest
32        command: ["python3", "/var/app/hello.py"]
33        imagePullPolicy: IfNotPresent
34        ports:
35        - name: http
36          containerPort: 8000
37          protocol: TCP
38        volumeMounts:
39        - name: app-data
40          mountPath: /var/app
41      volumes:
42      - name: app-data
43        emptyDir: {}