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

Docker Compose中自定义容器无法连接InfluxDB容器问题排查

Docker Compose环境中自定义容器无法连接InfluxDB的问题

我通过Docker Compose搭建了包含自定义容器、InfluxDB及其他服务的环境,所有容器处在同一网络且能互相ping通,但自定义容器内Python代码创建的InfluxClient在容器外可正常工作,在容器内却抛出连接拒绝错误。

自定义容器代码

from influxdb_client import InfluxDBClient, Point, WritePrecision, BucketRetentionRules
from influxdb_client.client.write_api import SYNCHRONOUS
import json


print("Starting writing test")

token = "xxxxxxxxx"
org = "rootyPi"
url = "http://influxdb:8086"
bucket = "user1"
client = InfluxDBClient(url=url, token=token)
write_api = client.write_api(write_options=SYNCHRONOUS)
record = '{"measurement": "testDocker","fields": { "test": 1}}'
while True:
    print("Writing..")
    write_api.write(bucket=bucket, org=org, record=json.loads(record))

报错信息

File "/usr/local/lib/python3.12/site-packages/urllib3/connection.py", line 198, in _new_conn
2024-04-20 20:06:45     sock = connection.create_connection(
2024-04-20 20:06:45            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2024-04-20 20:06:45   File "/usr/local/lib/python3.12/site-packages/urllib3/util/connection.py", line 85, in create_connection
2024-04-20 20:06:45     raise err
2024-04-20 20:06:45   File "/usr/local/lib/python3.12/site-packages/urllib3/util/connection.py", line 73, in create_connection
2024-04-20 20:06:45     sock.connect(sa)
2024-04-20 20:06:45 ConnectionRefusedError: [Errno 111] Connection refused

排查与解决思路

1. 修正InfluxDB的监听地址

InfluxDB默认可能仅监听127.0.0.1,导致容器网络内的服务无法访问。需确保其监听所有网卡:

  • 在Docker Compose的InfluxDB服务中添加环境变量:
    services:
      influxdb:
        environment:
          - INFLUXDB_HTTP_BIND_ADDRESS=0.0.0.0:8086
    
  • 或挂载自定义配置文件influxdb.conf,设置http.bind-address = 0.0.0.0:8086。

2. 确保InfluxDB完全启动后再连接

自定义容器可能在InfluxDB初始化完成前就发起连接,需通过健康检查控制启动顺序:

services:
  influxdb:
    image: influxdb:latest
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8086/health"]
      interval: 5s
      timeout: 5s
      retries: 5
  your-custom-service:
    build: .
    depends_on:
      influxdb:
        condition: service_healthy

3. 验证Token权限

确认使用的token拥有rootyPi组织下user1桶的写入权限:

  • 进入InfluxDB容器执行命令检查:
    influx auth list --token <你的管理员token>
    

若权限不足,需重新生成包含对应写入权限的token。

4. 测试容器内API连通性

在自定义容器内执行curl命令验证InfluxDB API是否可达:

docker exec -it <自定义容器名> curl http://influxdb:8086/ping

返回204 No Content说明网络正常,问题出在配置或权限;若仍拒绝连接,需检查Docker Compose网络配置,确保所有服务在同一自定义网络中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:46:37