skip to Main Content

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


  1. If you have an environment file .env at the same level as docker-compose file

    version: '3.7'
    
    services:
      myapp:
        build:
          context: .
        container_name: my_app
        ports:
          - 8080:8080
        env_file:
          - .env
    

    It 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.

    MY_VARIABLE=my_value
    

    If you want to run create a new container while passing env variables via .env file using docker run command

    docker run --env-file=.env your_image_name
    
    Login or Signup to reply.
  2. In a comment you describe two ways of running the container:

    I’m running docker-compose up.

    This should work as you expect. If you run docker-compose up without a -d option, you should see the configured my_value appear as the container’s output, and docker-compose logs myapp should show it as well.

    Go to the Docker Desktop app and press the run button on the image.

    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 the docker-compose.yml file.

    I thought the environment variables were already included in the image.

    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 contains environment: settings (or env_file:), or overrides the command:, 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

    ENV MY_VARIABLE=my_value
    

    This doesn’t stop you from overriding that value when you run a container, either from a docker run -e option or Compose environment:. Those values will take precedence over anything configured in a Dockerfile.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search