将env变量传递给docker compose

tsm1rwdh  于 2021-06-10  发布在  Redis
关注(0)|答案(2)|浏览(390)

我用python和redis创建了一个示例docker应用程序。python连接到redis来存储数据。我想通过考试
password servername 将redis作为docker compose文件中的环境变量。我怎样才能做到这一点?docker撰写:

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)
4bbkushb

4bbkushb1#

只需在flask app中定义环境变量,并在python应用程序中对其执行os.getenv,然后将它们添加到docker compose文件中的flask app服务中:

flask_app:
  environment:
    RABBIT_USER: guest
    RABBIT_PASSWORD: pass123

在python文件中:

import os

redis = Redis(host='redis_app', port=6379, password=os.getenv('RABBIT_PASSWORD'))
mkshixfv

mkshixfv2#

正如@andriyivaneyko所说,在你的docker中:

flask_app:
  environment:
    - PASSWORD=password

获取该值的另一种方法是在shell中设置一个env变量 export PASSWORD="password" 并将其导入docker compose:

flask_app:
  environment:
    - PASSWORD

这是我推荐的方法,因为它可以确保docker compose文件中没有明文形式的凭证。此外,由于env变量可以独立配置,协作变得更简单。
在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)

您可以对其他env变量执行相同的操作。这是文件。

相关问题