我正在尝试使用环境变量将Redis容器连接到python应用程序容器。我将密码作为环境变量传递,但是没有连接,如果我不使用环境变量并对密码进行硬编码,则密码可以正常工作,否则它将给出redis.exceptions.ConnectionError
version: "3.7"
services:
nginx_app:
image: nginx:latest
depends_on:
- flask_app
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf
ports:
- 8090:80
networks:
- my_project_network
flask_app:
build:
context: .
dockerfile: Dockerfile
expose:
- 5000
environment:
- PASSWORD=pass123a
depends_on:
- redis_app
networks:
- my_project_network
redis_app:
image: redis:latest
command: redis-server --requirepass ${PASSWORD} --appendonly yes
environment:
- PASSWORD=pass123a
volumes:
- ./redis-vol:/data
expose:
- 6379
networks:
- my_project_network
networks:
my_project_network:
index.py
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)
答案 0 :(得分:0)
更新您的docker-compose.yaml
环境是字符串列表:
docker-composer插入$ {ENV},其中从.env文件加载ENV的值
使用:
command: redis-server --requirepass $PASSWORD --appendonly yes
代替:
command: redis-server --requirepass ${PASSWORD} --appendonly yes
您可以通过以下方式验证ur容器中的环境变量:
docker-compose run --rm flask_app printenv | grep PASSWORD
应该返回:
PASSWORD=pass123a
docker-compose环境变量示例:Here
答案 1 :(得分:0)
您好像错过了将环境变量传递到Redis容器的过程。
尝试一下:
version: "3.7"
services:
nginx_app:
image: nginx:latest
#LOCAL IMAGE
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
environment:
- PASSWORD=pass123a
depends_on:
- redis_app
networks:
- my_project_network
redis_app:
image: redis:latest
command: redis-server --requirepass ${PASSWORD} --appendonly yes
environment:
- PASSWORD=pass123a
volumes:
- ./redis-vol:/data
expose:
- 6379
networks:
- my_project_network
networks:
my_project_network: