我在一個框架中使用 Docker 和 InfluxDB 和 Python。我想在框架內寫信給 InfluxDB,但我總是收到錯誤“名稱或服務未知”并且不知道問題出在哪里。
我將 InfluxDB 容器鏈接到 docker compose 檔案中的框架容器,如下所示:
version: '3'
services:
influxdb:
image: influxdb
container_name: influxdb
restart: always
ports:
- 8086:8086
volumes:
- influxdb_data:/var/lib/influxdb
framework:
image: framework
build: framework
volumes:
- framework:/tmp/framework_data
links:
- influxdb
depends_on:
- influxdb
volumes:
framework:
driver: local
influxdb_data:
在框架內部,我有一個只專注于寫入資料庫的腳本。因為我不想使用 url“localhost:8086”訪問資料庫,所以我使用鏈接使其更容易,并使用 url“influxdb:8086”連接到資料庫。這是我在該腳本中的代碼:
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS, WritePrecision
bucket = "bucket"
token = "token"
def insert_data(message):
client = InfluxDBClient(url="http://influxdb:8086", token=token, org=org)
write_api = client.write_api(write_options=SYNCHRONOUS)
point = Point("mem") \
.tag("sensor", message["sensor"]) \
.tag("metric", message["type"]) \
.field("true_value", float(message["true_value"])) \
.field("value", float(message["value"])) \
.field("failure", message["failure"]) \
.field("failure_type", message["failure_type"]) \
.time(datetime.datetime.now(), WritePrecision.NS)
write_api.write(bucket, org, point) #the error seams to happen here
每次我使用該功能時insert_data,我都會收到錯誤訊息urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7fac547d9d00>: Failed to establish a new connection: [Errno -2] Name or service not known。
為什么我不能寫入資料庫?
uj5u.com熱心網友回復:
我認為問題出在您的 docker-compose 檔案中。首先links是一個遺留功能,所以我建議您改用用戶定義的網路。更多資訊在這里:https ://docs.docker.com/compose/compose-file/compose-file-v3/#links
我創建了一個簡約示例來演示該方法:
version: '3'
services:
influxdb:
image: influxdb
container_name: influxdb
restart: always
environment: # manage the secrets the best way you can!!! the below are only for demonstration purposes...
- DOCKER_INFLUXDB_INIT_USERNAME=admin
- DOCKER_INFLUXDB_INIT_PASSWORD=secret
- DOCKER_INFLUXDB_INIT_ORG=my-org
- DOCKER_INFLUXDB_INIT_BUCKET=my-bucket
- DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=secret-token
networks:
- local
framework:
image: python:3.10.2
depends_on:
- influxdb
networks:
- local
networks:
local:
注意附加networks定義和local網路。這個網路也是從容器中參考的。
還要確保根據 docker 映像的檔案使用正確的環境變數初始化您的 influxdb:https ://hub.docker.com/_/influxdb
framework然后通過 docker-compose在你的容器中運行一個 shell 來測驗它:
docker-compose run --entrypoint sh framework
然后在容器中安裝客戶端:
pip install influxdb_client['ciso']
然后在 python shell 中 - 仍然在容器內 - 您可以驗證連接:
from influxdb_client import InfluxDBClient
client = InfluxDBClient(url="http://influxdb:8086", token="secret-token", org="my-org") # the token and the org values are coming from the container's docker-compose environment definitions
client.health()
# {'checks': [],
# 'commit': '657e1839de',
# 'message': 'ready for queries and writes',
# 'name': 'influxdb',
# 'status': 'pass',
# 'version': '2.1.1'}
最后但并非最不重要的一點是清理測驗資源:
docker-compose down
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/444530.html
