如何使用pymysql连接到docker容器上的mariadb

我正在使用Docker容器连接到mysql,但出现以下错误。

错误:

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

我不确定“ localhost”是否在使用linode / Digital Ocean实例。

测试类(test_mysql.py)

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

docker-compose.yml

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

Docker文件

 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 pymsql
 RUN pip3 install pytest

 WORKDIR /sp_odesi_report_project/

 CMD "pytest"
 ENV PYTHONDONTWRITEBYTECODE=true

命令行

docker-compose build

docker-compose run test sh

pytest -v
评论