skip to Main Content

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


  1. 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:

    flask_app:
      environment:
        RABBIT_USER: guest
        RABBIT_PASSWORD: pass123
    
    

    In your python file place following:

    import os
    
    redis = Redis(host='redis_app', port=6379, password=os.getenv('RABBIT_PASSWORD'))
    
    Login or Signup to reply.
  2. As @AndriyIvaneyko says, in your docker-compose:

    flask_app:
      environment:
        - PASSWORD=password
    

    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:

    flask_app:
      environment:
        - PASSWORD
    

    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:

    from flask import Flask
    from redis import Redis
    import os
    
    app = Flask(__name__)
    redis = Redis(host='redis_app', port=6379, password=os.getenv('PASSWORD'))
    @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)
    

    You can do the same thing with other env variables. Here is the documentation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search