Setting environment variables when running docker in detached mode

If I include the following line in /root/.bashrc:

export $A = "AAA"

then when I run the docker container in interactive mode (docker run -i), the $A variable keeps its value. However if I run the container in detached mode I cannot access the variable. Even if I run the container explicitly sourcing the .bashrc like

  • Deploying Java application in tomcat docker container
  • Docker container port issue
  • docker-compose error when I run bundle
  • How to edit files in docker for scrapinghub portia
  • application performance decrease a lot in docker
  • How to run Python Flask within a Docker container [duplicate]
  • docker run -d my_image /bin/bash -c "cd /root && source .bashrc && echo $A"

    such line produces an empty output.

    So, why is this happening? And how can I set the environment variables defined in the .bashrc file?

    Any help would be very much appreciated!

  • Docker Plugin for Jenkins error: Scripts not permitted to use method
  • Consul is unable to find the cluster leader
  • Jenkins - Pipeline (Amazon EC2 Container Service Plugin)
  • Testing connection to docker daemon
  • How to call 'docker swarm unlock' non-interactively?
  • Symfony server:run in php Docker container
  • One Solution collect form web for “Setting environment variables when running docker in detached mode”

    The first problem is that the command you are running has $A being interpreted by your hosts shell (not the container shell). On your host, $A is likely black, so your effectively command becomes:

    docker run -i my_image /bin/bash -c "cd /root && source .bashrc && echo "

    Which does exactly as it says. We can escape the variable so it is sent to the container and properly evaluated there:

    docker run -i my_image /bin/bash -c "echo \$A"

    But this will also be blank because, although the container is, the shell is not in interactive mode. But we can force it to be:

    docker run -i my_image /bin/bash -i -c "echo \$A"

    Woohoo, we finally got our desired result. But with an added error from bash because there is no TTY. So, instead of interactive mode, we can just set a psuedo-TTY:

    docker run -t my_image /bin/bash -i -c "echo \$A"
    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.