title: Setting environment variables on docker before exec
body: <p>I'm running a <em>set</em> of commands on an ubuntu docker, and I need to set a couple of environment variables for my scripts to work.</p>
  <p>I have tried several alternatives but none of them seem to solve my problem.</p>
  <p><strong>Alternative 1: Using --env or --env-file</strong></p>
  <p>On my already running container, I run either:</p>
  <pre><code>docker exec -it --env TESTVAR=&quot;some_path&quot; ai_pipeline_new_image bash -c &quot;echo $TESTVAR&quot;
  docker exec -it --env-file env_vars ai_pipeline_new_image bash -c &quot;echo $TESTVAR&quot;
  </code></pre>
  <p>The content of env_vars:</p>
  <pre><code>TESTVAR=&quot;some_path&quot;
  </code></pre>
  <p>In both cases the output is empty.</p>
  <p><strong>Alternative 2: Using a dockerfile</strong></p>
  <p>I create my image using the following docker file</p>
  <pre><code>FROM ai_pipeline_yh
  ENV TESTVAR &quot;A_PATH&quot;
  </code></pre>
  <p>With this alternative the variable is set if I attach to the docker (aka if I run an interactive shell), but the output is blank if I run <code> docker exec -it ai_pipeline_new_image bash -c &quot;echo $TESTVAR&quot;</code> from the host.</p>
  <p>What is the clean way to do this?</p>
  <p><strong>EDIT</strong></p>
  <p>Turns out that if I check the state of the variables from a shell script, they are set, but not if check them directly in <code>bash -c &quot;echo $VAR&quot;</code>. I would really like to understand why this is so. I provide a minimal example:</p>
  <p><strong>Run docker</strong></p>
  <pre><code>docker run -it --name ubuntu_env_vars ubuntu
  </code></pre>
  <p><strong>Create a file that echoes a VAR (inside the container)</strong></p>
  <pre><code>root@afdc8c494e8a:/# echo &quot;echo \$VAR&quot; &gt; env_check.sh
  root@afdc8c494e8a:/# chmod +x env_check.sh
  </code></pre>
  <p><strong>From the host, run:</strong></p>
  <pre><code>docker exec -it -e VAR=BLA ubuntu_env_vars bash -c &quot;echo $VAR&quot;
  </code></pre>
  <p>(Blank output)</p>
  <p><strong>From the host, run:</strong></p>
  <pre><code>docker exec -it -e VAR=BLA ubuntu_env_vars bash -c &quot;/env_check.sh&quot;
  </code></pre>
  <p>output: BLA</p>
  <p>Why???????</p>