问题描述
我有一个后端服务,需要将其部署到 Google Cloud Run
.
I have a backend service that I'll need to deploy to Google Cloud Run
.
来自 Google的Cloud Run教程,我们得到了:
首先,您需要构建映像并将其发送到 Cloud Build .
First you need to build your image and send it to Cloud Build.
gcloud builds submit --tag gcr.io/PROJECT-ID/helloworld
然后将其部署到Cloud Run:
Only then you deploy it to Cloud Run:
gcloud run deploy --image gcr.io/PROJECT-ID/helloworld --platform managed
我得到上面的序列.但我会将这项服务部署到2个不同的环境中: TEST
和 PROD
.
I get the sequence above. But I'll be deploying this service to 2 different environments: TEST
and PROD
.
因此,我需要一个 SERVER_ENV
变量,该变量在我的生产环境中应为"PROD"
,并且当然应为"TEST"
在我的测试环境中.这样一来,我的服务器(将通过容器运行的Express服务器)便知道要连接到哪个数据库.
So I need an SERVER_ENV
variable, that should be "PROD"
on my production environment, and of course it should be "TEST"
on my test environment. This is so my server (express server that will be run from the container) knows which database to connect to.
但是问题是我只有一个 Dockerfile
:
But the problem is that I only have a single 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构建提交
注释中是否有一个选项可以替代某些内容?还是使用其他 Dockerfile
?还有其他想法吗?
So how can I set different ENV
variables while following the build & deploy sequence above? Is there an option in the gcloud builds submit
comment that I can maybe override something? Or use a different Dockerfile
? Anybody got other ideas?
想法:
也许使用 Cloud Build配置文件?
cloudbuild.yaml
推荐答案
如果没有 cloudbuild.yaml
文件,您将无法实现这一目标.命令 gcloud builds commit --tag ...
不接受额外的docker参数.
You can't achieve this without a cloudbuild.yaml
file. The command gcloud builds submit --tag ...
doesn't accept extra docker parameter.
以下是配置示例
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
I created a build argument SERVER_CONF
. Your ENV
will take this value at build time. The default value is 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
Eventually, how to call your 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
这篇关于在将Docker映像构建和部署到Cloud Run时如何设置不同的ENV变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!