I just transitioned from Docker Swarm to Kubernetes and had the same question. The solution I settled on makes use of init containers (https://kubernetes.io/docs/concepts/workloads/pods/init-containers/).
The general idea is that init containers allow you to copy the node_modules
directory from your image into an empty volume, then mount that volume in your application's pod.
kind: Deployment
apiVersion: apps/v1
metadata:
...
spec:
...
template:
...
spec:
initContainers:
- name: frontend-clone
image: YOUR_REGISTRY/YOUR_IMAGE
command:
- cp
- -a
- /app/node_modules/.
- /node_modules/
volumeMounts:
- name: node-modules-volume
mountPath: /node_modules
containers:
- name: frontend
image: YOUR_REGISTRY/YOUR_IMAGE
volumeMounts:
- name: source-volume
mountPath: /app
- name: node-modules-volume
mountPath: /app/node_modules
volumes:
- name: source-volume
hostPath:
path: /YOUR_HOST_CODE_DIRECTORY/frontend
- name: node-modules-volume
emptyDir: {}
Note that the command to copy the node_modules
directory is cp -a /SOURCE/. /DEST/
and not the more common cp -r /SOURCE/* /DEST/
. The asterisk in the latter command would be interpreted as a literal *
instead of a logical *
and it wouldn't match every file/directory as intended.
You can do whatever you want with an init container, even create the node_modules
directory from a script at initialization (though it'd add a significant delay).