【问题标题】:How to set different ENV variable when building and deploying Docker Image to Cloud Run?构建 Docker Image 并将其部署到 Cloud Run 时如何设置不同的 ENV 变量?
【发布时间】:2021-03-20 02:11:12
【问题描述】:

我有一个后端服务需要部署到Google Cloud Run

Google's tutorial on Cloud Run,我们得到:

首先,您需要构建映像并将其发送到 Cloud Build

gcloud builds submit --tag gcr.io/PROJECT-ID/helloworld

只有这样才能将其部署到 Cloud Run:

gcloud run deploy --image gcr.io/PROJECT-ID/helloworld --platform managed

我得到了上面的序列。但我会将此服务部署到 2 个不同的环境:TESTPROD

所以我需要一个SERVER_ENV 变量,在我的生产环境中应该是"PROD",当然在我的测试环境中应该是"TEST"。这样我的服务器(将从容器运行的快速服务器)知道要连接到哪个数据库。

但问题是我只有一个Dockerfile

FROM node:12-slim

ENV SERVER_ENV=PROD

WORKDIR /

COPY ./package.json ./package.json
COPY ./distApp ./distApp
COPY ./distService ./distService
COPY ./public ./public

RUN npm install

ENTRYPOINT npm start

那么我如何在按照上面的构建和部署顺序设置不同的ENV 变量? gcloud builds submit 评论中是否有我可以覆盖某些内容的选项?或者使用不同的Dockerfile?有人有其他想法吗?

一个想法:

也许使用Cloud Build configuration file

cloudbuild.yaml

【问题讨论】:

  • 我认为使用构建参数可以实现您想要实现的目标:vsupalov.com/docker-env-vars。如果效果不佳,请提交常规答案

标签: docker dockerfile gcloud google-cloud-run google-cloud-build


【解决方案1】:

我认为使用 Dockerfile 中的 ARG 指令可以实现您想要实现的目标。

我会将它设置为test,然后根据您现在正在构建的环境使用arg参数。

更多文档:

【讨论】:

    【解决方案2】:

    如果没有cloudbuild.yaml 文件,您将无法实现此目的。命令gcloud builds submit --tag ... 不接受额外的 docker 参数。

    这里是一个配置示例

    FROM node:12-slim
    
    ARG SERVER_CONF=PROD
    ENV SERVER_ENV=$SERVER_CONF
    
    WORKDIR /
    
    COPY ./package.json ./package.json
    COPY ./distApp ./distApp
    COPY ./distService ./distService
    COPY ./public ./public
    
    RUN npm install
    
    ENTRYPOINT npm start
    

    我创建了一个构建参数SERVER_CONF。您的 ENV 将在构建时采用此值。默认值为PROD

    现在你的cloudbuild.yaml 文件

    step:
      - name: 'gcr.io/cloud-builders/docker'
        args: ['build', '--tag=gcr.io/PROJECT-ID/helloworld', '--build-arg="SERVER_CONF=$_SERVER_CONF"', '.']
      - name: 'gcr.io/cloud-builders/docker'
        args: ['push', 'gcr.io/PROJECT-ID/helloworld']
    substitutions:
      _SERVER_CONFPROD: PROD
    

    使用替换变量来改变环境。并不是说您也可以在这里设置一个默认值,它会覆盖您的 Dockerfile 值。照顾好这个!

    如果你愿意,你也可以将标签设置为替换变量

    最终,如何调用您的 Cloud Build

    # With default server conf (no substitution variables, the the file default)
    gcloud builds submit
    
    # With defined server conf
    gcloud builds submit --substitutions=_SERVER_CONF=TEST
    

    【讨论】:

    • 谢谢。仅使用gcloud CLI 真的不可能吗?我想我将不得不更深入地研究 Cloud Build 文档。您认为可以在本地构建映像并将其直接部署到 Cloud Run 吗?就像绕过 Cloud Build 步骤一样。
    • 是的,你可以在本地构建,但你需要在最后推送图像docker build --tag=gcr.io/PROJECT-ID/helloworld --build-arg=SERVER_CONF=TEST . && docker push gcr.io/PROJECT-ID/helloworld
    猜你喜欢
    • 2021-02-02
    • 2021-07-03
    • 2021-06-07
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-13
    • 2017-07-16
    相关资源
    最近更新 更多