Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot connect to redis container

I am trying to connect redis container to python app container using environment variable. I passed password as an environment variable but it is not connecting, if I don't use an environment variable and hard code the password it works fine otherwise it gives 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)

1 Answers

Update your docker-compose.yaml

the environment is a list of strings:

docker-composer interpolates ${ENV} where the value of ENV is loaded from .env file

Use:

command: redis-server --requirepass $PASSWORD --appendonly yes

Instead of:

command: redis-server --requirepass ${PASSWORD} --appendonly yes

You can verify environment variable inside ur container by:

docker-compose run --rm flask_app printenv | grep PASSWORD

That should return:

PASSWORD=pass123a

docker-compose example for environment variables: Here

like image 55
WSMathias9 Avatar answered Dec 01 '25 21:12

WSMathias9