Reputation: 101
I'm trying to run a simple hello world program from a docker container. What I want to do is display a custom message that I pass to the environment variable. If nothing is passed to the environment variable than the program should just display a default message of "Hello World!". I've already created an environment variable in my dockerfile and I'm trying to override that variable in my environment variable file using the --env-file flag. However, I'm not sure what the correct syntax would be for setting the environment variable since I'm getting "invalid syntax".
Below are my files:
Dockerfile
FROM python:3
ADD main.py /
ENV MESSAGE "Hello World!"
CMD ["python3", "./main.py"]
env_file
MESSAGE="Goodbye World!"
main.py
# simple hello world program
print($MESSAGE)
This is how I'm building and running my container
docker build -t example -f Dockerfile .
docker run --env-file=env_file --rm --name example example
Upvotes: 0
Views: 8685
Reputation: 3022
Change your main.py
to:
import os
print(os.environ['MESSAGE'])
Accessing environment variables using $
in Python is not supported and is not valid Python syntax.
Note that this will raise an exception if there's no such environment variable, so you may want to use os.environ.get('MESSAGE')
and check for None
or do some error handling in that case.
Upvotes: 6