简体   繁体   中英

Connect python script to mysql in docker

I wanna connect my python script to MySQL in docker. Here is my docker-compose file:

version: '3.7'

services:

  mysql:
    image: mariadb:${MARIADB_VERSION:-latest}
    container_name: mysql
    volumes:
      - ./mysql:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD:-password}
      - MYSQL_USER=${MYSQL_USER:-root}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD:-password}
      - MYSQL_DATABASE=${MYSQL_DATABASE:-db}
    restart: always

  script:
    container_name: script
    build: ./test_db
    command: bash -c "python3 testDb.py"
    environment:
      - DB_NAME=db
      - HOST=mysql
      - DB_USER=root
      - DB_PASSWORD=password
    volumes:
      - ./test_db:/var/www/html/script
    depends_on:
      - mysql

and here is my Python script file:

import pymysql

class TestDb:
    def run(self):
        conn = pymysql.connect(host='mysql', port=3306, database='db', user='root', password='password')
        print(conn)

if __name__ == "__main__":
    TestDb().run()

and here is my error:

script    | Traceback (most recent call last):
script    |   File "/test_db/testDb.py", line 10, in <module>
script    |     TestDb().run()
script    |   File "/test_db/testDb.py", line 5, in run
script    |     conn = pymysql.connect(host='mysql', port=3306, database='sta_db', user='root', password='Alphashadow1381')
script    |   File "/usr/local/lib/python3.9/site-packages/pymysql/__init__.py", line 94, in Connect
script    |     return Connection(*args, **kwargs)
script    |   File "/usr/local/lib/python3.9/site-packages/pymysql/connections.py", line 327, in __init__
script    |     self.connect()
script    |   File "/usr/local/lib/python3.9/site-packages/pymysql/connections.py", line 619, in connect
script    |     raise exc
script    | pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'mysql' ([Errno 111] Connection refused)")

How can I connect my Python script to MySQL in docker?

This usually means that the ports are not open, or a problem with the hostname!

you haven't exposed the ports to the outside world, maybe add this line

services:

  mysql:
    image: mariadb:${MARIADB_VERSION:-latest}
    container_name: mysql
    volumes:
      - ./mysql:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD:-password}
      - MYSQL_USER=${MYSQL_USER:-root}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD:-password}
      - MYSQL_DATABASE=${MYSQL_DATABASE:-db}
    restart: always
    ports:
      - "3306:3306"

i think you forgot to open your ports add this to your docker-copose: ports: - "3306:3306"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM