-1

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?

Naveen Kerati
  • 951
  • 3
  • 13
  • 29

2 Answers2

1

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

Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
0

Environment variables can be added to a container when running using either the environment option to docker run or through an --env-file option to docker run.

yamenk
  • 46,736
  • 10
  • 93
  • 87