I am using a Docker container to connect to mysql but I am getting this following error.
error:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Cannot assign requested address)")
I am not sure about 'localhost' I am using a linode/Digital Ocean instance.
Test class (test_mysql.py)
import pymysql
class TestDBConnectionFromDocker(object):
def test_docker(self):
connection = pymysql.connect(
host='localhost',
user='root',
password='myodesi123',
port=6603)
assert connection == True
docker-compose.yaml
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
Dockerfile
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 pymysql==0.9.3
RUN pip3 install pytest
WORKDIR /sp_odesi_report_project/
CMD "pytest"
ENV PYTHONDONTWRITEBYTECODE=true
Command line
docker-compose build
docker-compose run test sh
pytest -v
inspect
[root@li1975-241 sp_odesi]# docker container inspect c3e | grep -C 2 '3306'
"AttachStderr": false,
"ExposedPorts": {
"3306/tcp": {}
},
"Tty": false,
--
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"3306/tcp": null
},