如何读取docker容器内的系统环境变量

时间:2017-09-27 10:16:17

标签: amazon-web-services docker amazon-ecs

我是码头工人的新手。我有一个要求,其中docker容器应该读取系统环境变量,如AWS_INSTANCE_ID,它是aws中的instance-id。通常在启动时,我曾经使用shell脚本添加这些环境变量,如下所示

    EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
test -n "$EC2_INSTANCE_ID" || die 'cannot obtain instance-id'
export EC2_INSTANCE_ID=$EC2_INSTANCE_ID
EC2_AVAIL_ZONE="`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone || die \"wget availability-zone has failed: $?\"`"
test -n "$EC2_AVAIL_ZONE" || die 'cannot obtain availability-zone'
export EC2_AVAIL_ZONE=$EC2_AVAIL_ZONE
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"

当前Dockerfile

    FROM node:boron
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json .
RUN npm install
# Bundle app source
COPY . .
CMD [ "npm", "start" ]

如何在Docker容器中读取这些系统变量?

2 个答案:

答案 0 :(得分:1)

在项目中创建一个shell脚本

<强> env.sh

EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
test -n "$EC2_INSTANCE_ID" || die 'cannot obtain instance-id'
export EC2_INSTANCE_ID=$EC2_INSTANCE_ID
EC2_AVAIL_ZONE="`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone || die \"wget availability-zone has failed: $?\"`"
test -n "$EC2_AVAIL_ZONE" || die 'cannot obtain availability-zone'
export EC2_AVAIL_ZONE=$EC2_AVAIL_ZONE
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"

将您的dockerfile修改为

FROM node:boron
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json .
RUN npm install
# Bundle app source
COPY . .
COPY env.sh /etc/profile.d/awsenv.sh
ENTRYPOINT ["/bin/sh", "-lc"]
CMD ["env && exec npm start"]

现在,当图像开始时,它将自动拥有环境变量

答案 1 :(得分:0)

使用environment option to docker run或通过--env-file option到docker run运行时,可以将环境变量添加到容器中。