拒绝用户访问连接 python docker 容器中的远程 MySQL 数据库

Access denied for the user to connect remote MySQLdatabase in python docker container

从 Docker 开始,我目前正在尝试设置一个容器,其中 运行 是一个简单的 Python 脚本。该脚本应该使用 mysql.connector 库连接到远程数据库。当我从我的标准 Windows 环境中 运行 它时,它工作得很好,但是当我从容器启动它时它无法连接到数据库。

这是我的Docker文件:

# Docker image to build the container from 
FROM python:3 

# Path to script
ADD DLinvoices.py /



#Download the Mysql library

RUN pip install mysql-connector-python

#Download requests library
RUN pip install requests

#Running the script
CMD [ "python", "./DLinvoices.py" ]

这是我 运行 docker 图片时的控制台输出:

$docker run docker_invoice
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 179, in _open_connection
    self._cmysql.connect(**cnx_kwargs)
_mysql_connector.MySQLInterfaceError: Access denied for user 'user'@'ip.isp.overthebox.ovh' (using password: YES)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./DLinvoices.py", line 15, in <module>
    cnx = mysql.connector.connect(user='user', password='***', host='ip_host', database='dbName')
  File "/usr/local/lib/python3.7/site-packages/mysql/connector/__init__.py", line 172, in connect
    return CMySQLConnection(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 78, in __init__
    self.connect(**kwargs)
  File "/usr/local/lib/python3.7/site-packages/mysql/connector/abstracts.py", line 736, in connect
    self._open_connection()
  File "/usr/local/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 182, in _open_connection
    sqlstate=exc.sqlstate)
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'user'@'ip.isp.overthebox.ovh' (using password: YES)

编辑:python 脚本

import mysql.connector
import datetime
import requests
import io
import xmlrpc.client
import base64
import shutil
import errno

__PATH_TO_NAS__ = "./"

# DataBase connection
try:
    cnx = mysql.connector.connect(user='user', password='pwd', host='ip_host, database='dbname')
    cursor = cnx.cursor(buffered=False, dictionary=False)
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)

## variables ##

dtnow = datetime.datetime.today()
dtnow_tt = dtnow.timetuple()
day = dtnow_tt.tm_mday
month = dtnow_tt.tm_mon
year = dtnow_tt.tm_year

listId = []

## queries ##

query = "SELECT id_order, YEAR(invoice_date) year FROM ps_orders WHERE YEAR( invoice_date ) = " + str(
    year - 1) + " AND MONTH( invoice_date ) = " + str(month) + " AND DAY( invoice_date ) = " + str(day - 1)

cursor.execute(query, year)

##
#recuperation des IDs des factures a imprimer
##

for (id_order, year) in cursor:
    listId.append(id_order)
cursor.close()
cnx.close()



for id in listId:
    data = {"id": id}
    r = requests.post("link_to_the_pdf_file", data=data)
    print(r.headers['Content-type'])
    r.raw.decode_content = True
    try:
        with open(str(id) + "F.pdf", 'wb') as f:
            f.write(r.content)

    except IOError:

        print("Erreur! Le fichier n\' pas pu être ouvert ou est deja existant")

提前感谢您的帮助!

首先,如果没有打错

cnx = mysql.connector.connect(user='user', password='pwd', host='ip_host', database='dbname')

' 在 MySQL 连接字符串中缺失。

我很确定错误不是来自 docker,这里是确认的方法。

docker run --rm --name mariadb -p 3306:3306 -e MYSQL_ROOT_PASSWORD=hellopass -it mariadb:10.4

现在构建 python 基础镜像并 link 使用 maria DB 容器

FROM python:3.7.4-alpine3.10
RUN pip install mysql-connector

RUN echo $'#!/usr/bin/python \n\
import mysql.connector \n\
try:\n\
    cnx = mysql.connector.connect(user=\'root\', password=\'hellopass\', host=\'dbhost\') \n\
    cursor = cnx.cursor(buffered=False, dictionary=False) \n\
except mysql.connector.Error as err: \n\
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: \n\
        print("Something is wrong with your user name or password") \n\
    elif err.errno == errorcode.ER_BAD_DB_ERROR: \n\
        print("Database does not exist") \n\
    else: \n\
        print(err) \n\
print(cnx.is_connected())' >> /root/dbtest.py 
CMD [ "python" , "/root/dbtest.py"]

运行 数据库容器

 docker run --rm --link mariadb:dbhost -it pymsql ash -c "python /root/dbtest.py"

这是连接输出