docker 如何在容器构建时和运行时提供环境变量?

How to make environment variables available at container build-time & runtime in docker?

我正在开发一个 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 中访问这些环境变量,比如

...
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)$/'
...

我能够在本地构建和 运行 我的容器。但是它在上面的 gitlab ci 管道阶段失败了 Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) 我认为这与无法加载这些环境变量有关。

我该如何解决这个问题?甚至需要在 docker-compose 文件中将变量作为 args 和环境传递两次(我这样做是因为我发现只有在将它们作为 args 和环境传递时才能在本地构建我的容器)。

这是我第一次使用 ci/cd 和 docker,对我的代码的任何更正或优化它的建议都非常感谢ci。谢谢你的时间。

编辑:修复超链接错误

在您发布的 Dockerfile 中声明了 args,但是,您不会在构建时使用 --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