問題
Error connecting to MySQL: (2003, "Can't connect to MySQL server on 'db_server' ([Errno 111] Connection refused)")
docker環境に上記のエラーが出てしまってコンテナ間でデータベースのテストができなかった
結論
色々 docker-compose.yml を操作して頑張っていましたが、結論としては
「DBコンテナが立ち上がる前に、別コンテナがアクセスしようとしてエラーとなって落ちていること」
が原因でした。以下のテストコードで接続が成功するかを試してコンテナ間の問題ではないことをチェックしてみてください。5回のリトライ試行を導入したコードになります。
import time
import pymysql
from cryptography.fernet import Fernet
retries = 5 # Number of retry attempts
while retries > 0:
try:
conn = pymysql.connect(
host='db_server',
user='authoperator',
password='authoperatorpass',
database='authdb'
)
print("Connected to MySQL")
break # Exit the loop if connection is successful
except pymysql.err.OperationalError as e:
retries -= 1
print(f"Error connecting to MySQL: {e}")
print(f"Retrying... ({5-retries}/5)")
time.sleep(5) # Wait 5 seconds before retrying
if retries == 0:
print("Failed to connect to MySQL after 5 attempts")