【发布时间】:2021-06-23 23:57:50
【问题描述】:
我正在使用 docker-compose、Django、Redis 和其他服务来提升服务器,但我无法连接到 Redis。 Redis 容器启动时没有错误,但我无法将我的 django 后端连接到它。
首先我尝试像这样配置我的 .env 文件:
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
当我尝试从后端调用 Redis 任务时导致此错误:
连接到 127.0.0.1:6379 时出现错误 111。连接被拒绝
搜索我找到了这个答案: docker-compose + django + redis - Error 111 connecting to 127.0.0.1:6379. Connection refused
基本上,他们教如何像这样配置作曲家:
environment:
- REDIS_HOST=redis
我试过了,结果是这样的:
连接到 redis:6379 时出现错误 -3。名称解析暂时失败。
我注意到我的数据库在作曲家配置中无需环境即可获取 PostgreSQL 地址。 我在 composer 中的 postgreSQL 看起来像这样:
services:
db:
env_file:
- .env
image: postgres
environment:
- POSTGRES_DB=${DATABASE_NAME}
- POSTGRES_USER=${DATABASE_USER}
- POSTGRES_PASSWORD=${DATABASE_PASSWORD}
ports:
- "${DATABASE_PORT}:${DATABASE_PORT}"
expose:
- "${DATABASE_PORT}"
command: -p ${DATABASE_PORT}
backend:
(...)
请注意,我将其命名为 db
这样我就可以在我的 .env 文件中访问它,如下所示:
DATABASE_HOST=db
DATABASE_PORT=5433
这适用于 PostgreSQL,所以我尝试对 Redis 做同样的事情:
services:
(...)
redis_store:
env_file:
- .env
image: redis
ports:
- "${REDIS_PORT}:${REDIS_PORT}"
在 .env 中我是这样做的:
REDIS_HOST=redis_store
REDIS_PORT=6379
但结果又是这样:
连接到 redis_store:6379 时出现错误 111。连接被拒绝
我理解声明环境背后的想法:
environment:
- REDIS_HOST=redis
但我不明白为什么它不工作,也不明白为什么没有它 PostgreSQL 会工作并直接调用 db。
如果有人可以帮助我解决这些疑问,我将不胜感激。
这是我目前的完整配置:
version: '3'
services:
db:
env_file:
- .env
image: postgres
environment:
- POSTGRES_DB=${DATABASE_NAME}
- POSTGRES_USER=${DATABASE_USER}
- POSTGRES_PASSWORD=${DATABASE_PASSWORD}
ports:
- "${DATABASE_PORT}:${DATABASE_PORT}"
expose:
- "${DATABASE_PORT}"
command: -p ${DATABASE_PORT}
backend:
build: .
command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn --bind 0.0.0.0:${GUNICORN_PORT} some_project.wsgi:application"
container_name: some_project_be
env_file:
- .env
volumes:
- .:/some_project_be
ports:
- "${GUNICORN_PORT}:${GUNICORN_PORT}"
expose:
- "${GUNICORN_PORT}"
image: some_project
depends_on:
- db
- redis_store
nginx:
env_file:
- .env
environment:
- NGINX_PORT=${NGINX_PORT}
- GUNICORN_PORT=${GUNICORN_PORT}
command: /bin/sh -c "envsubst '$${NGINX_PORT} $${GUNICORN_PORT}' < /etc/nginx/conf.d/nginx.conf.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
build: ./nginx
ports:
- "${NGINX_PORT}:${NGINX_PORT}"
depends_on:
- backend
restart: "on-failure"
redis_store:
env_file:
- .env
image: redis
ports:
- "${REDIS_PORT}:${REDIS_PORT}"
celery:
env_file:
- .env
restart: always
build:
context: .
command: celery -A some_project worker --pool=solo -l info
links:
- redis_store
volumes:
- .:/some_project_be
depends_on:
- db
- redis_store
- backend
这里是我的 .env:
REDIS_HOST=redis_store
REDIS_PORT=6379
DATABASE_HOST=db
DATABASE_PORT=5432
DATABASE_NAME=some_db_name
DATABASE_USER=some_name
DATABASE_PASSWORD=some_secret
DATABASE_USER_EMAIL=xxx@gmail.com
NGINX_PORT=81
GUNICORN_PORT=8000
GOOGLE_MAPS_API_KEY=some_key
PROJECT_NAME=some_project
【问题讨论】: