<p>In docker-compose I was used to create volumes in this way:</p>

<pre><code>volumes:
  - ./server:/home/app
  - /home/app/node_modules
</code></pre>

<p>in order to solve the problem of <code>node_modules</code>.</p>

<p>How could I approach the problem in kubernetes?</p>

<p>I've created the following config</p>

<pre><code>  spec:
    containers:
    - env: []
      image: "image"
      volumeMounts:
      - mountPath: /home/app
        name: vol-app
      - mountPath: /home/app/node_modules
        name: vol-node-modules
      name: demo
    volumes:
    - name: vol-app
      hostPath:
        path: /Users/me/server
    - name: vol-node-modules
      emptyDir: {}
</code></pre>

<p>but it doesn't work. the node_modules is empty</p>

<p>I just transitioned from Docker Swarm to Kubernetes and had the same question. The solution I settled on makes use of init containers (<a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/workloads/pods/init-containers/</a>).</p>

<p>The general idea is that init containers allow you to copy the <code>node_modules</code> directory from your image into an empty volume, then mount that volume in your application's pod.</p>

<pre><code>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: {}
</code></pre>

<p>Note that the command to copy the <code>node_modules</code> directory is <code>cp -a /SOURCE/. /DEST/</code> and not the more common <code>cp -r /SOURCE/* /DEST/</code>. The asterisk in the latter command would be interpreted as a literal <code>*</code> instead of a logical <code>*</code> and it wouldn't match every file/directory as intended.</p>

<p>You can do whatever you want with an init container, even create the <code>node_modules</code> directory from a script at initialization (though it'd add a significant delay).</p>
