I’m running a Python app, and I want to dockerize it.
I have environment variables to pass to the program,
but I don’t manage to do it in docker.
my demo app (main.py):
import os
print(os.environ.get('MY_VARIABLE', 'NO VARIABLE IN ENVIRONMENT'))
Docker file :
FROM python:3.10-slim AS BASE
COPY . .
EXPOSE 8080
ENTRYPOINT ["python", "main.py"]
docker-compose.yml :
version: '3.7'
services:
myapp:
build:
context: .
container_name: my_app
ports:
- 8080:8080
environment:
- MY_VARIABLE=my_value
output of running the created image :
2024-01-10 13:22:29 NO VARIABLE IN ENVIRONMENT
the environment variable did not get its value from the docker-compose file.
what am I doing wrong?
2
Answers
If you have an environment file
.env
at the same level asdocker-compose
fileIt is a good practice to have all your environment variables in one environment variables file (
.env
) instead of writing them one by one in the compose file.If you want to run create a new container while passing env variables via
.env
file usingdocker run
commandIn a comment you describe two ways of running the container:
This should work as you expect. If you run
docker-compose up
without a-d
option, you should see the configuredmy_value
appear as the container’s output, anddocker-compose logs myapp
should show it as well.This just runs the image, without any particular configuration. It is the same as
docker run your-image
, without mentioning Compose. This path ignores anything in thedocker-compose.yml
file.The only things in the image are what’s described in the Dockerfile, possibly as modified by the Compose file’s
build:
block. If the Compose file containsenvironment:
settings (orenv_file:
), or overrides thecommand:
, or has other settings, these are not included in the image.This means another way to get consistent behavior here is to include the environment value in the Dockerfile
This doesn’t stop you from overriding that value when you run a container, either from a
docker run -e
option or Composeenvironment:
. Those values will take precedence over anything configured in a Dockerfile.