Docker 撰写 mysql 连接失败

2021-12-26 00:00:00 python docker docker-compose mysql

我正在尝试使用 docker-compose 运行 2 个 docker 容器并将 mysql 容器连接到应用程序容器.Mysql 容器正在运行但应用程序容器无法启动并出现错误 错误:2003:无法连接到 MySQL127.0.0.1:3306"上的服务器(111 连接被拒绝)似乎我的应用程序容器正在尝试连接我的主机 mysql 而不是 mysql 容器.

I am trying to run 2 docker containers using docker-compose and connect mysql container to app container.Mysql container is running but app container is failing to start with the error Error:2003: Can't connect to MySQL server on '127.0.0.1:3306' (111 Connection refused) It seems like my app container is trying to connect my host mysql instead of mysql container.

docker-compose.yml

version: '2'
services:
  mysql:
    image: mysql:5.7
    container_name: database
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: malicious
      MYSQL_USER: root
      MYSQL_PASSWORD: root

  app:
    build: .
    restart: unless-stopped
    volumes:
      - .:/Docker_compose_app   #app directory
    depends_on:
     - "mysql"
    command: [ "python", "database_update.py"]
    restart: unless-restart
    environment:
    # Environment variables to configure the app on startup.
     MYSQL_DATABASE: malicious
     MYSQL_HOST: database

Dockerfile

 FROM python:2.7
 ADD . /Docker_compose_app
 WORKDIR /Docker_compose_app
 RUN apt-get update
 RUN pip install --requirement requirement.txt

这是我的 database_update.py 文件.

    def create_TB(cursor,connection): 
      query = '''CREATE TABLE {}(malicious VARCHAR(100) NOT NULL)'''.format("url_lookup")
      cursor.execute(query)
      connection.commit()

    def connection():           
     try:
       cnx = mysql.connector.connect(user="root",password = 'root',database=malicious)
       cursor = cnx.cursor()
       create_TB(cursor,cnx)

     except mysql.connector.errors.Error as err:
       data = {"There is an issue in connection to DB":"Error:  {}".format(err)}

推荐答案

我可以看到两个问题:

  1. 尝试添加

  1. Try to add

links: 
  - mysql:mysql

到 Docker Compose 文件中的 app 服务.这将确保您可以从 app 访问 mysql 容器.它将在您的 app 容器中设置一个主机名映射 (DNS),因此当您从 appping mysql 时,它会将其解析为mysql 容器的 IP 地址.

to the app service in your Docker Compose file. This will make sure that you can reach the mysql container from app. It will set up a hostname mapping (DNS) in your app container, so when you ping mysql from app, it will resolve it to the mysql container's IP address.

在您的 .py 文件中,您在哪里定义要连接的主机?将 host="mysql" 添加到 connect 调用.默认情况下,它将连接到 127.0.0.1,这就是您所看到的.

In your .py file, where are you defining which host to connect to? Add host="mysql" to the connect call. By default, it will connect to 127.0.0.1, which is what you're seeing.

cnx = mysql.connector.connect(host="mysql", user="root", password = 'root', database=malicious)

解决这两个问题应该可以解决您的问题.

Fixing both of these should solve your problem.

相关文章