You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目Docker部署Elasticsearch遇ConnectionError连接拒绝问题

解决Docker中Django连接Elasticsearch的ConnectionRefused错误

问题现象

单独通过docker-compose运行Elasticsearch容器时功能正常,但同时启动Django服务、PostgreSQL数据库和Elasticsearch后,Django项目的搜索功能抛出以下错误:

ConnectionError at /
Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f4935a81fa0>: Failed to establish a new connection: [Errno 111] Connection refused))

问题原因

Docker容器内的localhost指向容器自身,而非宿主机。你的Django容器尝试访问localhost:9200,但Elasticsearch运行在另一个名为es的独立容器中,因此无法建立连接。

解决方案

1. 修改Django的Elasticsearch配置

更新settings.py中的ELASTICSEARCH_DSL配置,将localhost替换为docker-compose中Elasticsearch服务的名称es:

ELASTICSEARCH_DSL = {
    'default': {
        'hosts': 'http://es:9200'
    }
}

Docker默认网络会自动解析服务名称到对应容器的IP,因此Django容器可以直接通过es:9200访问Elasticsearch服务。

2. 确保Elasticsearch完全就绪后启动Django(可选但推荐)

depends_on仅保证服务启动顺序,不确保Elasticsearch完成初始化。添加健康检查可以避免因Elasticsearch未就绪导致的连接失败:

  • 在docker-compose.yml的es服务中添加健康检查配置:
es:
  image: docker.elastic.co/elasticsearch/elasticsearch:7.14.0
  environment:
    - discovery.type=single-node
  ports:
    - "9200:9200"
  volumes:
    - es_data:/usr/share/elasticsearch/data
  healthcheck:
    test: ["CMD-SHELL", "curl -f http://localhost:9200/_cluster/health || exit 1"]
    interval: 10s
    timeout: 10s
    retries: 5
  • 更新web服务的depends_on配置,等待Elasticsearch健康后再启动:
web:
  build: .
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  depends_on:
    db:
      condition: service_started
    es:
      condition: service_healthy
  environment:
    - DATABASE_URL=postgres://myprojectuser:password@db:5432/myproject

内容的提问来源于stack exchange,提问作者Sampurna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 18:27:15