无法从docker容器中的python连接redis

时间:2019-06-11 16:52:34

标签: python docker redis

Dockerfile

FROM python:3.6-slim

ENV PYTHONUNBUFFERED 1
WORKDIR /usr/src/duck

COPY ./ /usr/src/duck

RUN apt-get update
RUN apt-get install -y redis-server

RUN pip install -r requirements.txt

CMD ["/bin/bash","-c","python manage.py runserver 0.0.0.0:8000"]

python代码:

import redis
red = redis.StrictRedis(host="redis", port=6379, db=0)
red.set("working", "yes")

在这里,我正在尝试将python和redis都进行docker化。 上面是我的Dockerfile和python代码。

它使我陷入错误:

在运行python代码时。

Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/src/duck/settings/views.py", line 6, in check_redis
    red.set("working", "yes")
File "/usr/local/lib/python3.6/site-packages/redis/client.py", line 1451, in set
    return self.execute_command('SET', *pieces)
File "/usr/local/lib/python3.6/site-packages/redis/client.py", line 772, in execute_command
    connection = pool.get_connection(command_name, **options)
File "/usr/local/lib/python3.6/site-packages/redis/connection.py", line 994, in get_connection
    connection.connect()
File "/usr/local/lib/python3.6/site-packages/redis/connection.py", line 497, in connect
    raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. Name or service not known.

请看看。

1 个答案:

答案 0 :(得分:2)

容器仅运行python服务器,而不运行redis。 您应该在另一个容器上启动redis服务器(redis默认映像可能会这样做)。并使python服务器指向它。

您很幸运,因为撰写文档中有一个包含python应用程序和Redis服务器的示例。 https://docs.docker.com/compose/gettingstarted/