Reputation: 65
I'm starting to use Docker and I'm making a webservice using Flask. In order to connect to databases I need to tell the service the credentials to connect. I don't want to put the variable directly on the Dockerfile or worst, on code. I thought of passing them through environment variables that are set on build time via a shell script called on the Dockerfile.
The thing here is that I've tried using CMD,RUN and ENTRYPOINT to achieve this without success.
Here's the last version of my Dockerfile:
FROM python:2.7-slim
WORKDIR /app
ADD . /app
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
EXPOSE 5000
ENTRYPOINT ["python"]
CMD ["/app/con.sh"]
CMD ["-u","app.py"]
The script is named con.sh and has a structure like this:
export REDSHIFT_HOST="[Host of the DB]"
export REDSHIFT_USER="[DB user]"
export REDSHIFT_PASSWD="[DB password]"
export POSTGRES_DB="[DB name]"
export MODEL_IP="[endpoint of another service]"
export USER_SF="[user]"
export PASS_SF="[pass]"
export TOKEN="[Token]"
export INSTANCE_URL="[URL]"
What I get from this is:
Traceback (most recent call last):
File "app.py", line 4, in <module>
from clean_leads import *
File "/app/clean_leads.py", line 13, in <module>
HOST = os.environ['REDSHIFT_HOST']
File "/usr/local/lib/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'REDSHIFT_HOST'
Which confirms that the environment variables didn't get set.
Upvotes: 1
Views: 3744
Reputation: 4269
You have two CMD
statements in your Dockerfile, which isn't going to work. You can only have 1 CMD
statement, so your last one is going to overwrite the first.
From the Docker documentation:
There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect.
You'll need to combine your CMD
s into a single statement.
See here: Execute a script before CMD
Upvotes: 1
Reputation: 3077
You seem to be looking for an .env file.
Create a file in the format <variable>=value
with the variables you want to set.
REDSHIFT_HOST="[Host of the DB]"
REDSHIFT_USER="[DB user]"
REDSHIFT_PASSWD="[DB password]"
# ...
Then pass it to your run command with the --env-file option (name it .env for instance):
sudo docker run --rm -ti --env-file .env alpine sh
You can then check the output of echo $REDSHIFT_HOST
:
"[Host of the DB]"
Also, take a look at this part of the docs.
Upvotes: 0