![](/img/trans.png)
[英]Properly defining environment variables in Cloud Run for my React App
[英]REACT APP not access the google cloud run environment variables
我正在使用 GitLab ci 作為我的 CI/CD 工具。 我正在將 dockerized react 應用程序部署到雲運行,但我無法訪問在雲運行上聲明的環境變量。 謝謝!
Dockerfile
# build environment
FROM node:8-alpine as react-build
WORKDIR /app
COPY . ./
RUN npm install
RUN npm run build
# server environment
FROM nginx: alpine
COPY nginx.conf /etc/nginx/conf.d/configfile.template
COPY --from=react-build /app/build /usr/share/nginx/html
ENV PORT 8080
ENV HOST 0.0.0.0
EXPOSE 8080
CMD sh -c "envsubst '\$PORT' < /etc/nginx/conf.d/configfile.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
gitlab-ci.yml
default:
image: google/cloud-sdk:alpine
before_script:
- gcloud config set project PROJECTID
- gcloud auth activate-service-account --key-file $GCP_SERVICE_CREDS
stages:
- staging
- production
staging:
stage: staging
environment:
name: staging
only:
variables:
- $DEPLOY_ENV == "staging"
script:
- gcloud builds submit --tag gcr.io/PROJECTID/REPOSITORY
- gcloud run deploy REPOSITORY --image gcr.io/PROJECTID/REPOSITORY --platform managed --region us-central1 --allow-unauthenticated
production:
stage: production
environment:
name: production
only:
variables:
- $DEPLOY_ENV == "production"
script:
- gcloud builds submit --tag gcr.io/PROJECTID/REPOSITORY
- gcloud run deploy REPOSITORY --image gcr.io/PROJECTID/REPOSITORY --platform managed --region us-central1 --allow-unauthenticated --set-env-vars NODE_ENV=production
據我了解,您希望訪問在 GCP 上聲明的環境變量,例如 $GCP_SERVICE_CREDS、$PROJECTID、$REPOSITORY 和 Gitlab 管道上的其他變量。
為此,go 到 Gitlab 設置,然后單擊 CI/CD。 到達那里后,單擊變量前面的展開按鈕,然后添加各種 GCP 變量及其值。
歸功於 Guillaume Blaquiere,因為這個答案是基於他在這個線程中的帖子。
根據反應文檔:
環境變量是在構建時嵌入的。 由於 Create React App 生成一個 static HTML/CSS/JS 包,它不可能在運行時讀取它們。 要在運行時讀取它們,您需要將 HTML 加載到服務器上的 memory 並在運行時替換占位符。
最有可能發生的情況是您將 static 文件暴露給您的用戶,而用戶獲取文件並將其加載到瀏覽器中,如下所示:
console.log("REDIRECT", process.env.REACT_APP_API_END_POINT)
這將返回null
因為用戶的瀏覽器執行 Javascript 並讀取當前環境上的 env 變量:用戶的瀏覽器。 您應該有一個在 Cloud Run 上運行的執行以使用環境變量。 如果代碼在用戶端(在他們的瀏覽器中)運行,則不會出現環境變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.