Picking environment variables passed to docker container in Runlevel Scripts in Ubuntu

975 Views Asked by At

I know how to pass environment variables to docker container. like

sudo docker run  -e ENV1='ENV1_VALUE' -e ENV2='ENV2_VALUE1' ....

I am able to successfully pick these variables if I run script from shell inside the docker container. But the runlevel scripts of docker instance, are not able to see environment variables passed to docker container. Eventually all services/daemon are starting with default configuration which I don't want.

Please suggest some solution for it.

3

There are 3 best solutions below

1
NEERAJ SWARNKAR On BEST ANSWER
You can manage your run level services to pick environment variables passed to 
Docker instance.

For example here is my docker file(Dockerfile):

....
....
# Adding my_service into docker file system and enabling it.
ADD my_service /etc/init.d/my_service
RUN update-rc.d my_service defaults
RUN update-rc.d my_service enable
# Adding entrypoint script
COPY ./entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

# Set environment variables.
ENV HOME /root
# Define default command.
CMD ["bash"]


....


Entrypoint file can save the environment variables to a file,from which
you service(started from Entrypoint script) can source the variables.

entrypoint.sh contains:
#!/bin/bash -x
set -e
printenv | sed 's/^\(.*\)$/export \1/g' > /root/project_env.sh
service my_service start
exec /bin/bash

Inside my_service, I am sourcing the variables from /root/project_env.sh like:
#!/bin/bash
set -e
. /root/project_env.sh



I hope it solve your problem. This way you need NOT to depend on external file system, provide your are passing variables to your docker instance at the time of running it.
0
asdf On

In your Dockerfile you have the option to specify environment variables before runtime.

Dockerfile

FROM ubuntu:16.04
ENV foo=bar
ENV eggs=spam
RUN <some runtime command>
CMD <entrypoint>

Look at the docker environment replacement docs for more info.

0
Andy On

Runlevel scripts won't be able to read the environment variables, which I think it's a good thing.

You can try put the environment variables in a file on the host, mount it to a file in your docker container (e.g. under /etc/init.d/). And change the docker image's init script to source the mounted file before running your script.