You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过docker-compose命令传递AWS服务敏感环境变量?

解决方案:通过docker-compose命令行传递容器环境变量

完全可行,下面给你两种常用的实现方式,都不会把敏感信息写入文件,避免提交到Git的风险:

方法一:只声明环境变量名,通过-e参数传递

先修改你的docker-compose.yml,在environment字段里只写环境变量的名称,不赋值:

example.server:
  image: ${DOCKER_REGISTRY-}exampleserver
  container_name: exampleserver
  build:
    context: ..
    dockerfile: src/Web/Example.Server/Dockerfile
    args:
      ARTIFACTORY_USERNAME: ARTIFACTORY_USERNAME
      ARTIFACTORY_PASSWORD: ARTIFACTORY_PASSWORD
  environment:
    - AWSKey
    - AWSBucketName
    - AWSSecretKey

之后执行docker-compose up或者run命令时,用-e参数直接传递变量值:

# 启动容器时传递
docker-compose --profile test up -d -e AWSKey="your-aws-key" -e AWSBucketName="your-bucket-name" -e AWSSecretKey="your-aws-secret"

# 或者直接运行容器实例时传递
docker-compose --profile test run -e AWSKey="your-aws-key" -e AWSBucketName="your-bucket-name" -e AWSSecretKey="your-aws-secret" example.server

方法二:使用环境变量占位符,临时设置系统环境变量后执行

修改docker-compose.yml,用占位符表示环境变量的值:

example.server:
  image: ${DOCKER_REGISTRY-}exampleserver
  container_name: exampleserver
  build:
    context: ..
    dockerfile: src/Web/Example.Server/Dockerfile
    args:
      ARTIFACTORY_USERNAME: ARTIFACTORY_USERNAME
      ARTIFACTORY_PASSWORD: ARTIFACTORY_PASSWORD
  environment:
    - AWSKey=${AWS_KEY}
    - AWSBucketName=${AWS_BUCKET_NAME}
    - AWSSecretKey=${AWS_SECRET_KEY}

然后在执行docker-compose命令前,临时设置系统环境变量(无需写入文件):

# 临时设置后直接执行
AWS_KEY="your-aws-key" AWS_BUCKET_NAME="your-bucket-name" AWS_SECRET_KEY="your-aws-secret" docker-compose --profile test up -d

# 或者先导出变量再执行(仅当前终端会话有效)
export AWS_KEY="your-aws-key"
export AWS_BUCKET_NAME="your-bucket-name"
export AWS_SECRET_KEY="your-aws-secret"
docker-compose --profile test up -d

注意事项

  • 这里的环境变量是容器运行时变量,和构建时用的--build-arg是不同的概念,不要混淆。
  • 两种方式都不会将敏感信息持久化到文件中,完全符合你避免Git提交敏感数据的需求。

内容的提问来源于stack exchange,提问作者Beardy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:22:32