Docker撰写MySQL连接失败 [英] Docker compose mysql connection failing

查看:79
本文介绍了Docker撰写MySQL连接失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用docker-compose运行2个docker容器并将mysql容器连接到应用容器.mysql容器正在运行,但应用容器无法启动并显示错误错误:2003:无法连接到MySQL服务器在 127.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),因此当您从<$ c中 ping mysql $ c> app ,它将解析为 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.

这篇关于Docker撰写MySQL连接失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆