標題不完全準確,我樂意提供建議!在Docker中運行時無法從python連接到influxdb
你可以找到一個完整的MCVE這裏:
- 搬運工引擎17.05.0〜CE-0〜Ubuntu的xenial
- 泊塢窗,撰寫版本1.13.0:https://github.com/timstoop/20170614-python-docker-influxdb-problem
與測試,build 1719ceb
所以docker-compose啓動了influxdb和一個小型的python3應用程序。該應用程序唯一的做法是嘗試連接到influxdb,運行一個命令,如果失敗,請等待5秒鐘,然後重試。如果我在此代碼上運行docker-compose up
,應用程序將永遠不會連接,它會不斷重試。這些都是它輸出的日誌行:
app_1 | 2017-06-14 18:57:36.892955 ticker Trying InfluxDB connection...
app_1 | 2017-06-14 18:57:36.892977 ticker Influx host: 'influxdb'
app_1 | 2017-06-14 18:57:36.892984 ticker Influx port: 8086
app_1 | 2017-06-14 18:57:36.935112 ticker No InfluxDB connection yet. Waiting 5 seconds and retrying.
不過,如果我使用docker exec -ti <container name> /bin/sh
打開特定容器外殼,以下工作正常:
/ # python3 -u
Python 3.6.1 (default, Jun 8 2017, 21:50:56)
[GCC 6.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from influxdb import InfluxDBClient
>>> ci = InfluxDBClient(host='influxdb')
>>> ci.get_list_database()
[{'name': '_internal'}]
>>>
我敢肯定,我俯瞰東西愚蠢,但我無法解釋爲什麼app.py
不會建立連接。因此,我無法解決這個問題。任何意見在這裏將不勝感激。
我的代碼僅供參考,如下所示。
app.py:
#!/usr/bin/env python
from influxdb import InfluxDBClient
import datetime
import sys
import time
import os
import requests
def output(msg):
# Convenience function to always show a correct output
now = datetime.datetime.now()
print("%s ticker %s" % (now, msg))
if __name__ == '__main__':
# Gather our settings
influx_host = os.getenv('INFLUX_HOST', 'localhost')
influx_port = os.getenv('INFLUX_PORT', '8086')
influx_user = os.getenv('INFLUX_USER', 'root')
influx_pass = os.getenv('INFLUX_PASS', 'root')
# Create our connections
# Check to make sure we can create a connection
got_if_connection = False
while not got_if_connection:
output('Trying InfluxDB connection...')
output("Influx host: %s" % influx_host)
output("Influx port: %s" % influx_port)
influx_client = InfluxDBClient(host=influx_host, port=influx_port,
username=influx_user,
password=influx_pass)
try:
influx_client.get_list_database()
except requests.exceptions.ConnectionError:
output('No InfluxDB connection yet. Waiting 5 seconds and '+
'retrying.')
time.sleep(5)
else:
got_if_connection = True
Dockerfile:
FROM python:alpine3.6
MAINTAINER Tim Stoop <[email protected]>
# Copy the script in
COPY app.py /app.py
COPY requirements.txt /requirements.txt
# Install dependencies
RUN pip install -r /requirements.txt
CMD ["python3", "-u", "/app.py"]
泊塢窗,compose.yml:
version: '2'
services:
influxdb:
image: "influxdb:alpine"
ports:
- "8086:8086"
app:
build: .
links:
- influxdb
environment:
- INFLUX_HOST='influxdb'
請讓我知道如果你需要任何額外的信息!
我想你試圖連接到錯誤的端點。輸出('嘗試InfluxDB連接...') 輸出(「Influx主機:%s」%influx_host) 輸出(「Influx端口:%s」%influx_port)' 還請嘗試手動執行'python3 -u/app.py'(在應用程序容器內)。 –
將日誌行的輸出添加到我的問題中。你說得對,當我通過容器中的exec運行腳本時,它給了我相同的輸出。但我不明白爲什麼,因爲我手動調用InfluxDBClient似乎是完全一樣的? –