简体   繁体   中英

Unable to connect redis from python inside docker container

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 code:

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

Here i am trying to dockerize both python and redis. Above is my Dockerfile and python code.

It is throwing me below error:

while running python code.

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.

Please have a look.

The container is running only the python server, not redis. You should initiate the redis server on another container (probably the redis default image will do). And make the python server point to it.

You are lucky, because the compose docs have an example with a python app and Redis server. https://docs.docker.com/compose/gettingstarted/

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