1

first of all I must say that I am totally new on Docker. I want to make an app that uses a Python script to connect to a mysql database and read a table showing the first rows. I am working on ubuntu 18.04

I have a dockerfile file with reference to the Python script, I have the Python script and I have the docker-compose (.yml) file.

The dockerfile is:

FROM python:latest

WORKDIR /app

COPY . /app
RUN pip install --trusted-host pypi.python.org -r requirements.txt

EXPOSE 80

CMD ["python", "reg.py"]

The Docker compose file is:

version: '3.3'

services:

  mysqldev:
    image: mysql:5.7
    volumes:
      - type: volume
        source: my-db
        target: /home/pakin/Documents/db-on-docker
    command: --secure-file-priv=/home/pakin/Documents/db-on-docker
    environment:
      MYSQL_ROOT_PASSWORD: 1234
      MYSQL_DATABASE: pruebas

    ports:
      - "3308:3306"
    restart: always

  reg-py:
    build: .
    depends_on:
      - mysqldev

# Names our volume
volumes:
  my-db:

And the Python script is:

import numpy as np
import pandas as pd
from sqlalchemy import create_engine
import pymysql

engine = create_engine('mysql+pymysql:/root:1234@mysqldev:3306/pruebas')

df = pd.read_sql_query('SELECT * FROM reg_db', engine)
df.head()

Using docker-compose up the app initiates but the Python script shows an error 2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Cannot assign requested address then the mysql container works fine but python simply does not connect to it.

I appreciate any help you can provide me!

1 Answer 1

1

The easiest solution will be set IP to mysqldev as an env variable:

reg-py:
    build: .
    environment:
      - MY_SQL_IP:mysqldev
    depends_on:
      - mysqldev

and in your code:

db_ip = os.environ['MY_SQL_IP']
engine = create_engine(f'mysql+pymysql:/root:1234@{db_ip}:3306/pruebas')

UPD 1: - "3308:3306" is - "HOST:CONTAINER". So you should use port 3308 or create network

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

2 Comments

Thank you @amarynets i just tried your solution but still the same error. Do You think it has to do with ports or paths?
note: the port mapping is for the outside world, not for the internal network which the python and mysql containers are in. so, from python, mysql port num is the original 3306 only.

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.