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

  • Using COPY on dockerfile for apache build
  • Which OS for docker [closed]
  • Parsing Docker image tag into component parts [duplicate]
  • Docker image not exposing
  • Docker flask cant connect
  • log tag option ignored by docker daemon
  • 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!

  • Unable to autolaunch a dbus-daemon without a $DISPLAY for X11 in Docker container
  • Splitting up a Rails and React app into separate Docker containers?
  • Access Windows 2016 Server Container (Docker container) via GUI?
  • ADD command failing while building dockerfile using docker-build-step plugin in jenkins
  • ERROR: Build process returned exit code 137 during Docker build on Tutum
  • Previously working docker now having errors
  • 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.