1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コンテナ上のpython3/mysql-connector-pythonでホストのmysqlにアクセスする

Last updated at Posted at 2020-02-25

概要

こちらの記事でWindowsホストのdockerコンテナ上にpython環境を構築しました。

コンテナからホストのmysqlにアクセスした時のメモです。

2/28追記

もう少し、簡単に使えるように改良しました。

前提

環境

ホストOS Windows10
dockerイメージ python:3
※ホストにdocker for windowsがインストールされていること

mysqlの設定ファイル書き換え

my.cnf内のbind-addressをコメントアウトする。

[mysqld]
# bind-address = 127.0.0.1

mysqlにユーザー追加

> grant all privileges on [db_name].* to [user_name]@"[ip_address]" identified by '[password]' with grant option;
> select user,host from mysql.user;
> FLUSH PRIVILEGES;

手順

以下のディレクトリを作成します。

.
├── Dockerfile
├── docker-compose.yml
└── sample.py

以下を記述します。

FROM python:3
USER root

RUN apt-get update
RUN apt-get -y install locales && \
    localedef -f UTF-8 -i ja_JP ja_JP.UTF-8
ENV LANG ja_JP.UTF-8
ENV LANGUAGE ja_JP:ja
ENV LC_ALL ja_JP.UTF-8
ENV TZ JST-9
ENV TERM xterm

# install additional utilities
RUN apt-get install -y vim less
RUN pip install --upgrade pip
RUN pip install --upgrade setuptools

# install mysql utilities
RUN pip install mysql-connector-python

# add sample code
RUN mkdir /sample
ADD . /sample
WORKDIR /sample

CMD /bin/bash ./entrypoint.sh
docker-compose.yaml
version: '3'
services:
  python3:
    restart: always
    build: .
    container_name: 'python3'
    working_dir: '/sample'
    tty: true
    volumes:
      - .:/sample
    extra_hosts:
      - "(ホストのCOMPUTERNAME):(ホストのIPアドレス)"
    ports:
      - 3306:3306
mysql_demo.py
import mysql.connector as mydb


conn = mydb.connect(
    host='(ホストのIPアドレス)',
    port='3306',
    user='admin',
    password='password',
    database='sample_db'
)

conn.ping(reconnect=True)
print(conn.is_connected())
cur = conn.cursor()
cur.execute("SELECT * FROM sample_table;")
cur.close
conn.close

rows = cur.fetchall()
for row in rows:
    print(row)

結果

> docker-compose up -d --build
...
> docker container ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                    NAMES
aa4d45f07158        pyodbc_py370_python3   "/bin/sh -c '/bin/ba…"   27 minutes ago      Up 27 minutes       0.0.0.0:3312->3312/tcp   python3
> docker exec -it aa4d45f07158 /bin/bash
/sample# python --version
Python 3.8.1
/sample# pip list
Package                Version
---------------------- -------
dnspython              1.16.0
mysql-connector-python 8.0.19
pip                    20.0.2
protobuf               3.6.1
setuptools             45.2.0 
six                    1.14.0
wheel                  0.34.2
/sample# python sample.py
...SQL結果が表示されます。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?