最近在嘗試使用 Beanstalk 跑 Node.js 遇到一點貧頸是 Beanstalk 預設只會使用 npm 如此對於安裝套件上有點麻煩,如果使用 Yarn 可以解決掉很多問題,所以就研究一下如何在 Beanstalk 使用 Yarn。
新增 prebuild 檔案
基本上要使用 Yarn 很簡單只需要新增一個腳本到 prebuild 資料夾下面就可以了,如果有其他想要在 prebuild 之前執行的也可以都把腳本塞塞進去。這邊範例是新增檔案 .platform/hooks/prebuild/yarn.sh
,檔案內容如下:
#!/bin/bash # install node curl --silent --location https://rpm.nodesource.com/setup_18.x | bash -; # install yarn curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | tee /etc/yum.repos.d/yarn.repo; yum -y install yarn; # install node_modules with yarn app="$(/opt/elasticbeanstalk/bin/get-config container -k app_staging_dir)"; cd "${app}"; echo "App: ${app}." yarn --production;
上面使用到一個 Beanstalk 的指令,在 Beanstalk 有很多指令可以用來取得參數它的指令樣子如下
$ /opt/elasticbeanstalk/bin/get-config command [ options ]
而因為我們要取得執行個體的值所以使用 /opt/elasticbeanstalk/bin/get-config container
再使用 –key (-k) 就可以取得特定的 key 值,這邊我們要取得 app_staging_dir
也就是 App 的資料夾所以使用 /opt/elasticbeanstalk/bin/get-config container -k app_staging_dir
檔案資料夾結構
整體完成後資料夾如下,打包後上傳就會發現 Beanstalk 使用 Yarn 來安裝套件了。
~/my-app/ |-- index.js `-- .platform/ `-- hooks/ # Application deployment hooks `-- prebuild/ `-- yarn.sh
參考資料
《AWS CDK 完全學習手冊:打造雲端基礎架構程式碼 IaC》
第 12 屆 iT 邦幫忙鐵人賽 DevOps 組冠的《用 CDK 定 義 AWS 架構》
第 11 屆 iT 邦幫忙鐵人賽《LINE bot 好好玩 30 天玩轉 LINE API》
一個熱愛分享的雲端工程師!