dockerrunlevel

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


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.


Solution

  • 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.