无法连接到redis容器

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

我正在尝试使用环境变量将redis容器连接到python应用程序容器。我将password作为一个环境变量传递,但它没有连接,如果我不使用环境变量并硬编码密码,它就可以正常工作,否则它会给出 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:

索引.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)

a8jjtwal

a8jjtwal1#

更新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

bq9c1y66

bq9c1y662#

看起来您没有将环境变量传递到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:

相关问题