Home > Software engineering >  Cannot connect to MySQL database container on Docker with Python script
Cannot connect to MySQL database container on Docker with Python script

Time:08-12

When I try to connect to MySql Database my script get stuck. It simply does nothing. I use docker-compose.yml file (shown below) to run MySql database.

version: '3.1'

services:

  db:
    image: mysql
    # NOTE: use of "mysql_native_password" is not recommended: https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html#upgrade-caching-sha2-password
    # (this is just an example, not intended to be a production configuration)
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example
      MYSQL_DATABASE: database

  adminer:
    image: adminer
    restart: always
    ports:
      - 3306:8080

My php script for database connection:

<?php
    $conn = mysqli_connect('127.0.0.1', 'root', 'example', 'database');
    if ($conn->connect_errno) {
        echo("failed");
        exit();
    }
    $conn->close();
?>

I have also created python script which also get stuck. Here is the code:

import mysql.connector

mydb = None
try:
    mydb = mysql.connector.connect(
      host="127.0.0.1",
      user="root",
      password="database",
      use_pure=True
    )
except Exception as e:
    print(e)

print(mydb)

Log from docker-compose:

adminer_1  | [Thu Aug 11 22:03:52 2022] [::ffff:172.18.0.1]:56018 Accepted

For tests purposes I used php8.0-cli and python3. Do you have any ideas what could be the reason?

CodePudding user response:

You will either need to:

1: Expose the port on the database Docker container to allow access to it through your application

For example:

ports:
    - "3306:3306"

2: Create a container for your application which can store your script in it, and you can tunnel into your mysql server via a virtual network.

For example:

networks:
  default:
    driver: bridge

And you can use this network on both of your application by adding the following under each app.

networks: 
    - default

Heres a good resource to kick you off. https://runnable.com/docker/docker-compose-networking

  • Related