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

  • Symlink to volume in Docker container
  • Strategy for versioning Docker images linked to other contains via docker compose
  • Expose and publish a port with specified host port number inside Dockerfile
  • How do I run kurento in a docker container, with kurento hello world example on host machine
  • Error connecting to python server running in boot2docker (centos container | Windows 7.1 host)
  • Docker container based on microsoft/aspnet can't load Kestrel
  • 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!

  • Installing SQL alongside a new ASP.Net Core project in Docker
  • How do I set rack and datacenter name for scylladb using docker?
  • docker-compose can not retrieve variables from SOME.env files
  • When running Docker on Raspberry Pi starting containers fails from time to time
  • docker os container vs app container
  • boot2docker shellinit command ended up in error “Error requesting socket: exit status 255”
  • 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.