简体   繁体   中英

How to read system environment variables inside docker container

I am very new to docker. I have a requirement where docker container should read the system environment variable like AWS_INSTANCE_ID which is an instance-id in aws. Normally on bootup, I used to add these environment variables using a shell script as follows

    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:'`"

Current Dockerfile

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

How can I read these system variables in the Docker container?

Create a shell script in your project

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:'`"

Modify your dockerfile to below

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"]

Now when the image starts it will automatically have the environment variables

环境变量可以在运行时使用docker run环境选项或通过docker run--env-file 选项添加到容器中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM