0

Why is the ENV set correctly in the container by the first Dockerfile but not by the second one?

I have a small script that I want to run every 10 minutes. I dockerized cron and have it call the script (I know that might be a little weird). If I hardcode the env into the script everything works as intended. But I need to pass them in the Dockerfile instead.

This Dockerfile dockerizes the lone script and the ENV is set appropriately.

FROM python:3.10 WORKDIR /app COPY . /app ENV c_setting=5 CMD ["python", "script.py"] 

Right now the script just calls os.environ[c_setting] and prints it. Like I said, this finds the ENV set in the dockerfile correctly.

This is the cron version of the dockerfile. All it does is call the same script every 10 minutes.

FROM python:3.10 RUN apt-get update && apt-get -y install cron vim WORKDIR /app COPY crontab /etc/cron.d/crontab COPY . /app ENV c_setting=5 RUN chmod 0644 /etc/cron.d/crontab RUN /usr/bin/crontab /etc/cron.d/crontab CMD ["cron", "-f"] 

The cron aspect of this works just fine. It hits the KeyError(c_setting) exception at the right time intervals lol.

Why is the ENV set in the first Dockerfile but not in the second?

Something to do with layers and ordering?

script.py for ref

if __name__ == "__main__": import os print(os.environ["c_setting"]) 

crontab for ref

* * * * * cd ../app && /usr/local/bin/python script.py >> script.log 2>>error.log 
2
  • As far as I know cron doesn’t take environment variables for the commands from the environment it’s started from. You’ll need to put the variable definition into crontab for it to take effect when cron runs the command. Commented Jul 2, 2023 at 4:47
  • I've linked this to two very similar questions. The "Docker set environment variables" question addresses the very specific case of making Dockerfile ENV or docker run -e options accessible to cron jobs, but the "where can I set" question discusses some much simpler approaches directly using the crontab. Commented Jul 2, 2023 at 11:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.