我正在做一个nextjs docker项目,试图传递我的环境变量,以便在容器构建时和运行时访问。我基本上引用了Nextjs's template Dockerfile,并在我的docker-compose.yml中传递了所需的环境变量作为构建参数和环境变量
version: "3.7"
services:
app:
container_name: frontend
build:
context: .
args:
- API_URL=http://path-to-my-external-api-url
- NEXT_PUBLIC_CLIENT_API_URL=http://path-to-my-external-api-url
environment:
- NODE_ENV=production
- API_URL=http://path-to-my-external-api-url
- NEXT_PUBLIC_CLIENT_API_URL=http://path-to-my-external-api-url
ports:
- "3000:3000"
nginx:
depends_on:
- app
container_name: frontend-nginx
build: ./nginx
ports:
- "8080:8080"然后在我的Dockerfile中访问这些env变量,如下所示
...
FROM node:14-alpine AS builder
WORKDIR /app
COPY ./app .
COPY --from=deps /app/node_modules ./node_modules
ARG API_URL
ARG NEXT_PUBLIC_CLIENT_API_URL
ENV API_URL=${API_URL}
ENV NEXT_PUBLIC_CLIENT_API_URL=${NEXT_PUBLIC_CLIENT_API_URL}
RUN npm run build
...然后在gitlab管道中构建应用程序,该管道在下面定义的构建阶段失败
...
Build and Push App:
image: docker:19.03.5
services:
- docker:19.03.5-dind
stage: Build and Push
script:
- apk add python3
- pip3 install awscli
- docker build --compress -t $ECR_REPO:$CI_COMMIT_SHORT_SHA .
- $(aws ecr get-login --no-include-email --region ap-south-1)
- docker push $ECR_REPO:$CI_COMMIT_SHORT_SHA
- docker tag $ECR_REPO:$CI_COMMIT_SHORT_SHA $ECR_REPO:latest
- docker push $ECR_REPO:latest
rules:
- if: '$CI_COMMIT_BRANCH =~ /^(main|production)$/'
...我能够在本地构建和运行我的容器。但在上面使用Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)的gitlab ci管道阶段,它失败了,我认为这与无法加载这些环境变量有关。
我该如何解决这个问题?甚至需要在docker-compose文件中将变量作为args和environment传递两次(我这样做是因为我发现只有在将它们都作为args传递时,环境才能在本地构建我的容器)。
这是我第一次使用ci/cd和docker,对我的代码的任何修改或优化建议都是非常感谢的。感谢您的宝贵时间。
编辑:修复超链接错误
发布于 2021-11-11 20:37:33
在您发布的Dockerfile中声明了参数,但是,在构建时,您不能在带有--build-arg标志的docker build命令上加载它们,也不能在类似如下的命令上加载它们:
docker build --compress -t $ECR_REPO:$CI_COMMIT_SHORT_SHA --build-arg API_URL=<url> NEXT_PUBLIC_CLIENT_API_URL=<url> . 参考:https://docs.docker.com/engine/reference/commandline/build/#options
https://stackoverflow.com/questions/69930040
复制相似问题