1
0

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.

docker-compose環境でのmysql接続方法まとめ

Posted at

前提

  • wsl2を使ったDocker環境
  • docker-composeでmysqlをPython flaskの環境を構築
  • flaskサーバからmysqlサーバに接続
  • wsl2のコマンドラインからmysqlを使用
docker-compose.yml
version: '3'
services: 
    db:
        image: mysql:8.0
        container_name: mysql_host
        ports:
            - "3306:3306" #<---wsl2から接続する場合に必要。flask_hostからの接続には不要
        environment: 
            MYSQL_ROOT_PASSWORD: secret
        volumes:
            - ./db/data:/var/lib/mysql
            - ./db/init:/docker-entrypoint-initdb.d
    flask:
        build: .
        container_name: flask_host
        ports:
            - "5000:5000"
        volumes:
            - .:/workspace:cached
        tty: true
        environment:
            TZ: Asia/Tokyo
        # command: flask run --host 0.0.0.0 --port 5000
$ docker-compose ps
     Name                   Command             State                 Ports
-----------------------------------------------------------------------------------------
mysql_host        docker-entrypoint.sh mysqld   Up      0.0.0.0:3306->3306/tcp, 33060/tcp
sample1_flask_1   python3                       Up      0.0.0.0:5000->5000/tcp

接続方法まとめ

接続元 記述方法
flaskサーバからmysqlに接続 mysql_host
mysqlサーバのdocker hostnameを使用
wsl2からmysqlに接続 127.0.0.1
※.wslconfigに追記が必要
※localhostと記述するとmysql.sockを使って接続しようとするので接続できない
.wslconfig
[wsl2]
memory=2GB
swap=2GB
localhostForwarding=true

memory, swapの記述は、localhost接続とは関係ありません。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?