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

I am attempting to connect a FastAPI with sqlAlchemy to a mysql db container.

I am using the alias. Unfortunately it wont connect and I don't know why.

Using MySQL Workbench on the external port with the environment variables works to connect.

SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:3091@db:3306/investing"

Here is the docker compose file

version: '3.8'
services: 
  db:
    command: '--default-authentication-plugin=mysql_native_password'
    environment:
      - MYSQL_DATABASE=investing
      - MYSQL_ROOT_PASSWORD=3091
    image: mysql:8.0.28
    ports: 
      - "3307:3306"
    restart: on-failure
    volumes: 
      - "./db/init:/docker-entrypoint-initdb.d"
    # healthcheck:
    #   test: mysqladmin ping -h 127.0.0.1 -u $$MYSQL_USER --password=$$MYSQL_PASSWORD


  # client:
  #   build: client
  #   ports: [3000]
  #   restart: always

  server:
    build: server
    ports: 
      - "5000:5000"
    restart: always
    depends_on:
      - db
    volumes:
      - ./server:/tmp
      - ./server/data:/tmp/data

Docker PS

CONTAINER ID   IMAGE                    COMMAND                  CREATED          STATUS                         PORTS                                                  NAMES
cccbd4651340   react-flask-app_server   "python /tmp/app.py"     47 minutes ago   Restarting (0) 6 seconds ago                                                          react-flask-app_server_1
690185103a7b   mysql:8.0.28             "docker-entrypoint.s…"   47 minutes ago   Up 45 seconds                  33060/tcp, 0.0.0.0:3307->3306/tcp, :::3307->3306/tcp   react-flask-app_db_1


Solution 1:[1]

Hilariously enough, in converting from Flask to FastAPI, I had forgotten to uncomment the uvicorn to actually properly run the server. Bit of a woops there xD.

# uvicorn.run(host="0.0.0.0", port="5000")

I'm completely surprised that it was giving me an inability to connect instead of a pure exit code 0 with no logs. That really threw me off.

if __name__ == '__main__':
    uvicorn.run("app:app", host="0.0.0.0", port="5000")

PS. my main file is app.py not main.py hence app:app not main:app

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Paccione