I have the following docker-compose.yml
:
version: "3.9" services: compute: build: . ports: - "27030:27030" environment: - COMPUTE_HOST=$COMPUTE_HOST - COMPUTE_PORT=$COMPUTE_PORT
In my .env
file I have the following:
COMPUTE_HOST="0.0.0.0" COMPUTE_PORT=27030
This is to start up a flask api, but what I get when I run the container with:
docker compose --env-file .env up --build
or
docker-compose --env-file .env up --build
is this:
apv_compute-compute-1 | APV server starting on port None ... apv_compute-compute-1 | * Serving Flask app 'api' (lazy loading) apv_compute-compute-1 | * Environment: production apv_compute-compute-1 | WARNING: This is a development server. Do not use it in a production deployment. apv_compute-compute-1 | Use a production WSGI server instead. apv_compute-compute-1 | * Debug mode: on apv_compute-compute-1 | * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) apv_compute-compute-1 | * Restarting with stat apv_compute-compute-1 | * Debugger is active! apv_compute-compute-1 | * Debugger PIN: 483-995-326
The api insists on starting on 127.0.0.1:5000
suggesting that the environment variables are not set at all.
It also does not work if I change my compose file as follows:
environment: - COMPUTE_HOST="0.0.0.0" - COMPUTE_PORT=27036
So likely not due to an issue with the .env file. When running the app outside of docker it works perfectly fine.
*** UPDATE ***
The environment variables are actually set inside the container since docker exec image_tag env
gives:
COMPUTE_HOST=0.0.0.0 COMPUTE_PORT=27030
Also, if I bash into the container, echo $COPMUTE_PORT
gives the correct value.
So this is either dotenv
not picking this up or the timing of when these variables are set leading to dotenv
not getting them in time.
I have tried with both load_env
and dotenv_values
.
Docker version 20.10.14, build a224086
Advertisement
Answer
For future reference: as mentioned in the comments, the OP was using sudo
for running the container command.
As a result, given sudo
resets the environment by default (for security purposes, unless one uses the CLI option sudo -E
), the environment variables at stake are not preserved.
Note actually that in a Docker context, sudo
is generally not required for running the container command because:
- either the default user in the container already has admin rights,
- or the container process just doesn’t require privileges, in which case a best practice amounts to using a non-privileged user for running the dockerized web service (see also this blog article:
4. Don’t run containers as root
).