Search code examples
pythondockercronenvironment

Python script can't find ENV variable run with CRON in docker container


I want to run a Python script in a Docker container with crontab, now cron successfully run the python script but it can't find ENV variable given from Dockerfile, when i run echo $DOG from inside the container is shows up expected string "dog" or when ik manaully run the python script /> python dog.py it can find the ENV variables. So the ENV are in the OS inside the container.

Why isnt it reachable for the script running by cron?

Crontab

* * * * * /usr/local/bin/python3 /app/dog.py > /proc/1/fd/1 2>/proc/1/fd/2
# empty line

Dockerfile

FROM python:3.10

RUN apt-get update && apt-get install -y cron

WORKDIR /app/

COPY crontab .

COPY dog.py .

RUN chmod -R 755 /app/

RUN crontab /app/crontab

CMD ["cron", "-f"]

dog.py

#!/usr/bin/python
import os
# Check os env variables
if "DOG" in os.environ:
    dog = os.environ.get("DOG")
    print(dog)
else:
    print("no env")

docker-compose.yaml

---
version: "3.8"
services:
  prd-workorder-worker:
    build: .
    environment:
    - DOG=dog

Solution

  • i have solved it by running a bash script that put all variables to /etc/environment when the container is started.

    Dockerfile

    ...
    
    CMD ["./entry.sh"]
    

    entry.sh

    #!/bin/bash
    
    printenv | grep -v "no_proxy" >> /etc/environment
    
    cron -f