0

I am using a Docker container to connect to mysql but I am getting this following error.

error:

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Cannot assign requested address)")

I am not sure about 'localhost' I am using a linode/Digital Ocean instance.

Test class (test_mysql.py)

import pymysql
class TestDBConnectionFromDocker(object):
    def test_docker(self):
        connection = pymysql.connect(
                host='localhost', 
                user='root', 
                password='myodesi123', 
                port=6603)
        assert connection == True

docker-compose.yaml

version: '3.1'
services:
  test:
    build: .
    links:
      - mariadb
    volumes:
      - .:/sp_odesi_report_project
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=sp_odesi
      - MYSQL_USER=odesi
      - MYSQL_PASSWORD=myodesi123
    stdin_open: true
    ports:
      - 6603:3306
    depends_on:
      - mariadb
    tty: true

  mariadb:
    image: mariadb:latest
    restart: unless-stopped
    container_name: mariadb-odesi
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=sp_odesi
      - MYSQL_USER=odesi
      - MYSQL_PASSWORD=myodesi123
    expose:
      - 3306

Dockerfile

 FROM python:3.7.6-buster

 RUN mkdir /sp_odesi_report_project/
 COPY ./test_mysql.py /sp_odesi_report_project/

 RUN pip install --upgrade pip
 RUN pip3 install pymysql==0.9.3
 RUN pip3 install pytest

 WORKDIR /sp_odesi_report_project/

 CMD "pytest"
 ENV PYTHONDONTWRITEBYTECODE=true

Command line

docker-compose build

docker-compose run test sh

pytest -v

inspect

[root@li1975-241 sp_odesi]# docker container inspect c3e | grep -C 2 '3306'
            "AttachStderr": false,
            "ExposedPorts": {
                "3306/tcp": {}
            },
            "Tty": false,
--
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "3306/tcp": null
            },
Papouche Guinslyzinho
  • 4,477
  • 8
  • 43
  • 82

2 Answers2

2

Your connection settings are not quite right. You had:

connection = pymysql.connect(
                host='localhost', 
                user='root', 
                password='myodesi123', 
                port=6603)

However that does not match the way you have setup the dB in your docker-compose file for the MariaDB service. Instead it should be:

connection = pymysql.connect(
                host='mariaDB', 
                user='root', 
                password='root', 
                port=3306)

Alternatively you could make your docker-compose match the settings you have in your connection string. (Using root as password is probably not good).

camba1
  • 1,635
  • 2
  • 10
  • 18
0

Use mariadb (ie the hostname of the container running your database) instead of localhost.

Błotosmętek
  • 11,945
  • 16
  • 26