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

  • Best practice to make root environmental variables visible to Apache under supervisord?
  • Expose my docker container to my external IP on GCP
  • Framework auto-scale container docker on AWS
  • Nginx reverse proxy on docker and unloaded assets
  • Cannot remove all containers in a row
  • running tcpreplay with docker and boot2docker
  • 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!

  • Do you have any resource explaining how to use Firebase Test lab with GitLab pipeline?
  • run /usr/sbin/sshd in a Dockerfile does not work
  • Docker Compose 3 controlling resources (memory, cpu)
  • Tag a Docker image in Google Container Registry with additional tag via command line
  • Can we create volumes inside docker container
  • Unable to pull docker image with concourse - Verifying Checksum error
  • 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.