1

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?

1
  • What I just noticed is that if I change password in scripts to some random strings the behaviour does not change Commented Aug 11, 2022 at 22:05

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Compose provides exactly that default network for you even if you don't define it, and attaches containers to it if they don't otherwise have a networks: block. You shouldn't need either of the networks: blocks you show. Networking in Compose in the Docker documentation describes this further.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.