おうちk8sに自作アプリを乗せる②(案の定k8sが上手くいかない #12)

スポンサーリンク
個人開発
スポンサーリンク

はじめに

自作アプリをk8sに乗せる際、frontend側で上手くいかなかったので、備忘の意味も含めて記載します。

frontend側ではvue.jsを使用していて、それに伴いnpmによるmodule管理をしています。

そんな中で一つのエラーに遭遇します。

以下のエラーと遭遇した時から始まりました。

Cannot find module @rollup/rollup-linux-arm-gnueabihf. npm has a bug related to optional dependencies

エラーの対応

Cannot find module @rollup/rollup-linux-arm-gnueabihf. npm has a bug related to optional dependencies

frontendでアプリケーションを起動しようとした時に発生したエラーです。

Error: Cannot find module @rollup/rollup-linux-arm-gnueabihf. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). Please try `npm i` again after removing both package-lock.json and node_modules directory.
    at requireWithFriendlyError (/app/node_modules/rollup/dist/native.js:64:9)
    at Object.<anonymous> (/app/node_modules/rollup/dist/native.js:73:76)
    ... 3 lines matching cause stack trace ...
    at Module._load (node:internal/modules/cjs/loader:1104:12)
    at cjsLoader (node:internal/modules/esm/translators:346:17)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:286:7)
    at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:473:24) {
  [cause]: Error: Cannot find module '@rollup/rollup-linux-arm-gnueabihf'
  Require stack:
  - /app/node_modules/rollup/dist/native.js
      at Module._resolveFilename (node:internal/modules/cjs/loader:1225:15)
      at Module._load (node:internal/modules/cjs/loader:1051:27)
      at Module.require (node:internal/modules/cjs/loader:1311:19)
      at require (node:internal/modules/helpers:179:18)
      at requireWithFriendlyError (/app/node_modules/rollup/dist/native.js:46:10)
      at Object.<anonymous> (/app/node_modules/rollup/dist/native.js:73:76)
      at Module._compile (node:internal/modules/cjs/loader:1469:14)
      at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)
      at Module.load (node:internal/modules/cjs/loader:1288:32)
      at Module._load (node:internal/modules/cjs/loader:1104:12) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [ '/app/node_modules/rollup/dist/native.js' ]
  }
}

ここで、以下を参考に、

Error: Cannot find module @rollup/rollup-linux-x64-gnu on Docker container · vitejs/vite · Discussion #15532
Describe the bug I researched and tried on the sites below and on many different platforms, but I could not find a solution. I am using node:lts and also I cann

worker nodeで設定をしてみる。

worker nodeのファイル群をマウントしているためです。

今回のエラーで無いと言われている「@rollup/rollup-linux-arm-gnueabihf」をマウントしているfrontendのディレクトリ(package.jsonがある階層)でインストールします。

# npm install @rollup/rollup-linux-arm-gnueabihf --save-optional

これでpackage.jsonが以下のようになっている

{
・・・【略】・・・
  "optionalDependencies": {
    "@rollup/rollup-linux-x64-gnu": "^4.29.0",
    "@rollup/rollup-linux-x64-gru": "4.9.5"
  }
}

でもこれでも解消しない。

master nodeで確認すると、以下のように引き続きエラーが発生してpodが落ちています。

$ kubectl get pod -n go-slim
NAME                                READY   STATUS    RESTARTS      AGE
go-slim-frontend-5cc6988b6f-pwj8x   0/1     Error     1 (20s ago)   30s

コンテナ内で設定しないといけないっぽいのかと、deployment.yamlを以下のように修正します。

apiVersion: apps/v1
kind: Deployment
metadata:
・・・【略】・・・
spec:
・・・【略】・・・
    spec:
      containers:
      - image: appare99/go-slim-frontend
        name: go-slim-frontend-container
        ports:
        - containerPort: 443  # HTTPSポート
          name: https
        - containerPort: 5173
          name: vite
        volumeMounts:
        - name: go-slim-frontend-persistent-storage
          mountPath: /app
        workingDir: /app
        command: [
          "sh", 
          "-c", 
          "npm install @rollup/rollup-linux-arm-gnueabihf --save-optional && npm run dev"
        ]
      imagePullSecrets: 
      - name: regcred
      volumes:
      - name: go-slim-frontend-persistent-storage
        persistentVolumeClaim:
          claimName: go-slim-frontend-pvc

動いた。

$ kubectl get pod -n go-slim
NAME                                READY   STATUS    RESTARTS   AGE
go-slim-frontend-564b78ccd7-bl47m   1/1     Running   0          46s
go-slim-frontend-564b78ccd7-qdzz8   1/1     Running   0          46s

podのログを見ても問題なさそう。

$ kubectl logs go-slim-frontend-564b78ccd7-bl47m -n go-slim

up to date, audited 58 packages in 17s

13 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

> go-slim@0.0.0 dev
> vite


  VITE v6.0.5  ready in 896 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: http://10.244.2.17:5173/

でもこの後、なぜかpodが上手く立ち上がらなくなる事象が発生。。。

worker node側で直にnpm runをすると、動くことを確認

root@k8s-worker2:/mnt/go_slim_frontend/go-slim# npm run dev

> go-slim@0.0.0 dev
> vite

Re-optimizing dependencies because lockfile has changed

  VITE v6.0.5  ready in 1378 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: http://192.168.3.11:5173/
  ➜  Network: http://10.244.2.0:5173/
  ➜  Network: http://10.244.2.1:5173/
  ➜  press h + enter to show help

deployment.ymlのpodの起動時のコマンドで以下を設定してみる。

        command: [
          "sh", 
          "-c", 
          "npm install vite -save-dev && npm install @rollup/rollup-linux-arm-gnueabihf --save-optional && npm run dev"
        ]

でもダメ。

さらに、ここで、「/bin/sh: 1: vite: not found」が発生するようになる。

ローカルでインストールしたのであるはずなのに。。

以下の記事を参考に、node_modulesを名前付きボリュームで別管理することに。

dockerでvueの環境構築するときにnode_modulesディレクトリで躓いた話 - Qiita
諸注意まだまだ勉強不足、理解不足故保証はできません。直接関係なさそうな部分は省略しています。結論とか学んだこととかnode_modulesディレクトリはホストからコンテナにコピーするのは難し…

You installed esbuild for another platform than the one you’re currently using. ~~~

viteがpodで動いたものの、次は、以下のようなエラーが発生。

# npm run dev

> go-slim@0.0.0 dev
> vite

failed to load config from /app/vite.config.js
error when starting dev server:
Error:
You installed esbuild for another platform than the one you're currently using.
This won't work because esbuild is written with native code and needs to
install a platform-specific binary executable.

Specifically the "@esbuild/linux-arm64" package is present but this platform
needs the "@esbuild/linux-arm" package instead. People often get into this
situation by installing esbuild on Windows or macOS and copying "node_modules"
into a Docker image that runs Linux, or by copying "node_modules" between
Windows and WSL environments.

If you are installing with npm, you can try not copying the "node_modules"
directory when you copy the files over, and running "npm ci" or "npm install"
on the destination platform after the copy. Or you could consider using yarn
instead of npm which has built-in support for installing a package on multiple
platforms simultaneously.

If you are installing with yarn, you can try listing both this platform and the
other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
Keep in mind that this means multiple copies of esbuild will be present.

Another alternative is to use the "esbuild-wasm" package instead, which works
the same way on all platforms. But it comes with a heavy performance cost and
can sometimes be 10x slower than the "esbuild" package, so you may also not
want to do that.

    at generateBinPath (/app/node_modules/esbuild/lib/main.js:1742:17)
    at esbuildCommandAndArgs (/app/node_modules/esbuild/lib/main.js:1823:33)
    at ensureServiceIsRunning (/app/node_modules/esbuild/lib/main.js:1980:25)
    at build (/app/node_modules/esbuild/lib/main.js:1879:26)
    at bundleConfigFile (file:///app/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:53724:24)
    at async loadConfigFromFile (file:///app/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:53693:21)
    at async resolveConfig (file:///app/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:53217:24)
    at async _createServer (file:///app/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:43534:18)
    at async CAC.<anonymous> (file:///app/node_modules/vite/dist/node/cli.js:745:20)

以下の記事を参考に、EnptyDir(無名ボリューム)を設定して、pod内でviteを入れてみる事にする。

You installed esbuild for another platform than the one you're cur...
root@go-slim-frontend-74856b74f5-rs7bn:/app# npm install vite –save-dev
npm error arg Argument starts with non-ascii dash, this is probably invalid: –save-dev
npm error code EINVALIDTAGNAME
npm error Invalid tag name "–save-dev" of package "–save-dev": Tags may not have any characters that encodeURIComponent encodes.
npm error A complete log of this run can be found in: /root/.npm/_logs/2024-12-27T15_18_51_516Z-debug-0.log

viteをpod内で入れて、起動しようとすると、「vite: not found」

root@go-slim-frontend-74856b74f5-rs7bn:/app# npm i @vitejs/plugin-vue --save-dev

changed 1 package, and audited 48 packages in 22s

12 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
root@go-slim-frontend-74856b74f5-rs7bn:/app# npm run dev

> go-slim@0.0.0 dev
> vite

sh: 1: vite: not found

もう、ええて(cf.ナダル氏)

Cannot find package ‘vite’ imported from ~~~

viteをグローバルで入れてみる。(-gをつけてインストールしてみる)

root@go-slim-frontend-74856b74f5-wx7qb:/app# npm install -g vite

added 10 packages in 5s

3 packages are looking for funding
  run `npm fund` for details
root@go-slim-frontend-74856b74f5-wx7qb:/app# vite --version
vite/6.0.6 linux-arm node-v20.18.1
root@go-slim-frontend-74856b74f5-wx7qb:/app# npm run dev

> go-slim@0.0.0 dev
> vite

failed to load config from /app/vite.config.js
error when starting dev server:
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from /app/node_modules/.vite-temp/vite.config.js.timestamp-1735344381358-0b9c5a0d30814.mjs
    at packageResolve (node:internal/modules/esm/resolve:854:9)
    at moduleResolve (node:internal/modules/esm/resolve:927:18)
    at defaultResolve (node:internal/modules/esm/resolve:1169:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:542:12)
    at ModuleLoader.resolve (node:internal/modules/esm/loader:510:25)
    at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:239:38)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:96:40)
    at link (node:internal/modules/esm/module_job:95:36)

もう、ええて(2回目)

いったん整理

worker側でviteをインストールしておく→「/bin/sh: 1: vite: not found」

一旦、整理すると、worke側でinstallしたらviteが追加されるが、これだと「/bin/sh: 1: vite: not found」が発生する

root@k8s-worker2:/mnt/go_slim_frontend/go-slim# npm install

added 8 packages, changed 1 package, and audited 57 packages in 3s

13 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
root@k8s-worker2:/mnt/go_slim_frontend/go-slim#
root@k8s-worker2:/mnt/go_slim_frontend/go-slim# ls node_modules/
@babel        @rollup  asynckit         defu            estree-walker     mime-db     proxy-from-env  vue
@esbuild      @types   axios            delayed-stream  follow-redirects  mime-types  rollup          zhead
@fortawesome  @unhead  bootstrap        entities        form-data         nanoid      source-map-js
@jridgewell   @vitejs  combined-stream  esbuild         hookable          picocolors  unhead
@popperjs     @vue     csstype          esbuild-wasm    magic-string      postcss     vite
root@k8s-worker2:/mnt/go_slim_frontend/go-slim# ls node_modules/.bin/
esbuild  nanoid  parser  rollup  vite

これだと「/bin/sh: 1: vite: not found」が発生する。

k8sのpod内でnpm installする→「You installed esbuild~~」が出る

k8s上でpod内でviteをinstallしたら以下が出てしまう。

# npm run dev

> go-slim@0.0.0 dev
> vite

failed to load config from /app/vite.config.js
error when starting dev server:
Error:
You installed esbuild for another platform than the one you're currently using.
This won't work because esbuild is written with native code and needs to
install a platform-specific binary executable.

Specifically the "@esbuild/linux-arm64" package is present but this platform
needs the "@esbuild/linux-arm" package instead. People often get into this
situation by installing esbuild on Windows or macOS and copying "node_modules"
into a Docker image that runs Linux, or by copying "node_modules" between
Windows and WSL environments.

If you are installing with npm, you can try not copying the "node_modules"
directory when you copy the files over, and running "npm ci" or "npm install"
on the destination platform after the copy. Or you could consider using yarn
instead of npm which has built-in support for installing a package on multiple
platforms simultaneously.

If you are installing with yarn, you can try listing both this platform and the
other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
Keep in mind that this means multiple copies of esbuild will be present.

Another alternative is to use the "esbuild-wasm" package instead, which works
the same way on all platforms. But it comes with a heavy performance cost and
can sometimes be 10x slower than the "esbuild" package, so you may also not
want to do that.

    at generateBinPath (/app/node_modules/esbuild/lib/main.js:1742:17)
    at esbuildCommandAndArgs (/app/node_modules/esbuild/lib/main.js:1823:33)
    at ensureServiceIsRunning (/app/node_modules/esbuild/lib/main.js:1980:25)
    at build (/app/node_modules/esbuild/lib/main.js:1879:26)
    at bundleConfigFile (file:///app/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:53724:24)
    at async loadConfigFromFile (file:///app/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:53693:21)
    at async resolveConfig (file:///app/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:53217:24)
    at async _createServer (file:///app/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:43534:18)
    at async CAC.<anonymous> (file:///app/node_modules/vite/dist/node/cli.js:745:20)

つまり、ラズパイのローカルでnpm installはできないことになり、k8sのpod内でnpm installしなければならないが、上記にもあるように、npm installをしてもエラーでアプリケーションが動かせない。

結果、viteが入れらなくて詰んだ。

で、最終的に以下記事を見つけて、

Vite not found in vite.config.ts cannot run vite apps
npm create vite@latest error: Cannot find package 'vite' imported from .../vite.config.ts.timestamp-....mjs An update while writing my problem: I concluded that
npm install --include=dev

をpod内ですると解決。

結果的なdeployment.ymlは以下のようになりました。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-slim-frontend
  labels:
    app: go-slim-frontend
  namespace: go-slim
spec:
  replicas: 2
  selector:
    matchLabels:
      app: go-slim-frontend
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: go-slim-frontend
    spec:
      containers:
      - image: appare99/go-slim-frontend
        name: go-slim-frontend-container
        ports:
        - containerPort: 5173
          name: vite
        volumeMounts:
        - name: go-slim-frontend-app
          mountPath: /app
        - name: go-slim-frontend-nodemodules
          mountPath: /app/node_modules ## ★node_modulesは別管理する
        workingDir: /app
        command: [
          "sh", 
          "-c", 
          "npm install --include=dev && npm run dev" ## ★--include=devを設定する
        ]
        env:
        - name: NODE_ENV
          value: "production" # 環境変数の値を指定
      imagePullSecrets: 
      - name: regcred
      volumes:
      - name: go-slim-frontend-app
        persistentVolumeClaim:
          claimName: go-slim-frontend-pvc-app
      - name: go-slim-frontend-nodemodules
        emptyDir: {} ## ★EnptyDir(無名ボリューム)を設定する
タイトルとURLをコピーしました