简体   繁体   中英

how do i connect to redis server in python script inside a Docker container

Here is my python file 'app.py'

import redis
cache = redis.Redis(host='redis', port=6379)
for i in range(8):
  cache.set(i,i)
for i in range(8):
  print(cache.get(i))        

Here is my Dockerfile

FROM python:3.7-alpine
COPY . /code
WORKDIR /code
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
CMD ["python", "app.py"] 

But when i built and run docker image i am getting error not able to connect.

The container you run based on the image does not know who 'redis' is. You can tell it by using the --add-host option to docker run .

Find out the public IP of your redis server. Then use that IP to map it to the redis hostname that your script tries to connect to.

docker run --add-host redis:<public_ip> ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM