我在一个容器中有一个Django应用,试图用Redis和Mysql容器组成它。但是,打电话
redis://redis:6379
来自Django应用,给了我
ConnectionError: Error -2 connecting redis://redis:6379. Name or service not known.
与其他可行的解决方案相比,我的设置没有任何差异。我想念什么吗? 我的docker-compose.yml
version: '3'
services:
web:
build: .
environment:
- REDIS_HOST=redis
restart: always
command: bash -c "python manage.py runserver --settings=settings.production_cs 0.0.0.0:8000"
container_name: eprofi
volumes:
- .:/eprofi
ports:
- "8000:8000"
depends_on:
- db
- redis
links:
- db:postgres
- redis:redis
db:
image: mysql:latest
command: mysqld --default-authentication-plugin=mysql_native_password
volumes:
- "./mysql:/var/lib/mysql"
ports:
- "3306:3306"
restart: always
environment:
- MYSQL_ROOT_PASSWORD=secret123
- MYSQL_DATABASE=django_app
- MYSQL_USER=django_app
- MYSQL_PASSWORD=django_app123
redis:
restart: always
image: redis:latest
ports:
- "6379:6379"
我的Dockerfile
# We Use an official Python runtime as a parent image
FROM python:2.7.13
ENV DEBIAN_FRONTEND noninteractive
ENV PYTHONDONTWRITEBYTECODE 1
# The enviroment variable ensures that the python output is set straight
# to the terminal with out buffering it first
ENV PYTHONUNBUFFERED 1
# create root directory for our project in the container
RUN mkdir /www
# Set the working directory to /www
WORKDIR /www
#Upgrade pip
RUN pip install pip -U
#Install dependencies
ADD requirements.txt /www/
RUN pip install -r requirements.txt --src /usr/local/src
# Copy the current directory contents into the container at /www
ADD . /www/
然后我做
docker-compose build
docker-compose up
一切都按预期开始,但是使用“ redis:// redis:6379”调用Redis会得到上述“名称或服务未知”。错误。
我的工具
docker-compose version 1.17.1, build unknown
docker-py version: 2.5.1
Client: Docker Engine - Community
Version: 19.03.4
更新1 我如何从python应用(旧Django)中调用Redis。
Django应用的设置:
CACHES = {
'my_cache': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': 'redis://{}:{}'.format(REDIS_HOST, REDIS_PORT),
'KEY_PREFIX': 'project/my_cache',
'TIMEOUT': 60*60*24, # expire in 24 hours
'OPTIONS': {
'DB': 1,
'PARSER_CLASS': 'redis.connection.HiredisParser'
}
},
}
致电:
cache = get_cache('my_cache')
cache.get(cache_key)
更新2
命令
ping redis
在容器中运行会给我一个错误
ping: unknown host
答案 0 :(得分:1)
根据documentation,不推荐使用links
选项。为了使服务互相呼叫,它们应该在同一网络上。因此,对于您的示例,解决方案是这样的。您可以了解有关网络here的更多信息。
version: '3'
services:
web:
...
networks:
- my_network
db:
...
networks:
- my_network
redis:
...
networks:
- my_network
networks:
my_network:
external:
name: my_network