Techie
Techie

Reputation: 61

sqlalchemy.exc.OperationalError : Can't connect to mysql in docker

I am working with sqlalchemy and mysql, the process is working fine for mysql installed locally but I am not able to connect it with a mysql docker image. I am using pymysql as a driver. Here is the line of commands that I run and I am getting an error shown below.

Following are the portions of /docker-compose.yml and the python file. Also I have a script that creates a database named "sqlalchemy" in docker mysql which is not shown below.

/docker-compose.yml

services:
  db:
    build: ./database
    restart: always
    ports:
      - "3309:3306"
    environment:
      - MYSQL_USER=root
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_HOST=db

/sqlalchemy.py

 msqldb_uri = 'mysql+pymysql://root:password@db:3309/sqlalchemy'
 engine = create_engine(msqldb_uri)



sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'db' ([Errno 111] Connection refused)")

Upvotes: 5

Views: 6880

Answers (1)

Adiii
Adiii

Reputation: 59896

If the script is running inside container then you do not use the publish port in the connection but you should use 3306 within localhost or same network. The publish port is for outer world.

 msqldb_uri = 'mysql+pymysql://root:password@localhost:3306/sqlalchemy'
 engine = create_engine(msqldb_uri)

If the script is runnin in other container that is in the same docker-compose file then you also you do not need the publish port.

 msqldb_uri = 'mysql+pymysql://root:password@db:3306/sqlalchemy'
 engine = create_engine(msqldb_uri)

if the script in running on host and DB is running inside container then you need connect with the publish port but you should not use container name as a IP.

 msqldb_uri = 'mysql+pymysql://root:password@localhost:3309/sqlalchemy'
 engine = create_engine(msqldb_uri)

Upvotes: 2

Related Questions