I have create a sample docker app with python and redis. Python is connected to the redis to store data. I want to pass the password
servername
to redis as an environment variable in docker-compose file. How can I achieve that?
Docker-compose:
version: "3.7"
services:
nginx_app:
image: nginx:latest
depends_on:
- flask_app
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf
ports:
- 8082:80
networks:
- my_project_network
flask_app:
build:
context: .
dockerfile: Dockerfile
expose:
- 5000
depends_on:
- redis_app
networks:
- my_project_network
redis_app:
image: redis:latest
command: redis-server --requirepass pass123 --appendonly yes
volumes:
- ./redis-vol:/data
expose:
- 6379
networks:
- my_project_network
networks:
my_project_network:
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis_app', port=6379, password='pass123')
@app.route('/')
def hello():
redis.incr('hits')
return 'Hello World! I have been seen %s times.' % redis.get('hits')
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
2
Answers
just define environement variables in flask app and do os.getenv of them in python application, than add them to your flask app service in docker compose file:
In your python file place following:
As @AndriyIvaneyko says, in your docker-compose:
Another way that you can get this value is by setting an env variable in your shell
export PASSWORD="password"
and importing it into your docker-compose:This is the approach I would recommend since it ensures that your credentials are not available in plain text in the docker-compose file. Moreover, collaboration becomes simpler as the env variable can be configured independently.
In your python:
You can do the same thing with other env variables. Here is the documentation.