Program Club

호스트에서 Docker 컨테이너의 mysql에 연결

proclub 2020. 10. 15. 21:59
반응형

호스트에서 Docker 컨테이너의 mysql에 연결


(Docker 또는 mysql 관리에 대한 제한된 지식으로 인해 어리석은 질문 일 수 있지만이 문제에 대해 저녁을 보냈으므로 감히 물어볼 수 있습니다.)

간단히 말해서

도커 컨테이너에서 mysql을 실행하고 호스트에서 연결하고 싶습니다. 지금까지 내가 달성 한 최고는

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

자세한 내용은

나는 다음을 사용하고 있습니다 Dockerfile

FROM ubuntu:14.04.3
RUN apt-get update && apt-get install -y mysql-server

# Ensure we won't bind to localhost only
RUN grep -v bind-address /etc/mysql/my.cnf > temp.txt \
  && mv temp.txt /etc/mysql/my.cnf

# It doesn't seem needed since I'll use -p, but it can't hurt
EXPOSE 3306

CMD /etc/init.d/mysql start && tail -F /var/log/mysql.log

이 파일이있는 디렉토리에서 이미지를 성공적으로 빌드하고 실행할 수 있습니다.

> docker build -t my-image .
> docker run -d -p 12345:3306 my-image

이미지에 첨부하면 잘 작동하는 것 같습니다.

# from the host
> docker exec -it <my_image_name> bash

#inside of the container now
$ mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
[...]

그러나 나는 호스트로부터 그다지 성공하지 못했습니다.

> mysql -P 12345 -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

더 자세한 정보

  • 내 것과 같은 질문이 있다는 것을 본 적이 있습니다 . 그러나 실제로는 동일하지 않습니다 (어쨌든 답이 없습니다)
    • mysql 전용 이미지가있는 것을 보았지만 더 많은 성공을 거두지 못했습니다.
    • grep -v기분이 이상 할 수 있습니다. 물론 더 깨끗한 방법이있을 수 있습니다. 그러나 내 이미지에 연결하면 실제로 예상대로 작동하는 것을 볼 수 있습니다 (예 : 제거 bind-address). 그리고 컨테이너에서 볼 수 있습니다/var/log/mysql/error.log

서버 호스트 이름 (바인드 주소) : '0.0.0.0'; 포트 : 3306- '0.0.0.0'은 '0.0.0.0'으로 확인됩니다. IP에 생성 된 서버 소켓 : '0.0.0.0'.


Docker MySQL 호스트가 올바르게 실행중인 경우 로컬 컴퓨터에서 연결할 수 있지만 다음과 같이 호스트, 포트 및 프로토콜을 지정해야합니다.

mysql -h localhost -P 3306 --protocol=tcp -u root

3306을 Docker 컨테이너에서 전달한 포트 번호로 변경합니다 (귀하의 경우 12345).

Docker 컨테이너 내에서 MySQL을 실행하고 있기 때문에 소켓을 사용할 수 없으며 TCP를 통해 연결해야합니다. mysql 명령에서 "--protocol"을 설정하면 변경됩니다.


localhost 대신 "127.0.0.1"을 사용하면 mysql은 tcp 메소드를 사용하며 다음과 같이 컨테이너를 연결할 수 있어야합니다.

mysql -h 127.0.0.1 -P 3306 -u root

docker-compose를 확인하는 것이 좋습니다. 작동 방식은 다음과 같습니다.

다음과 같은 docker-compose.yml이라는 파일을 만듭니다.

version: '2'

services:

  mysql:
    image: mariadb:10.1.19
    ports:
      - 8083:3306
    volumes:
      - ./mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: wp

다음으로 실행 :

$ docker-compose up

메모:

이제 다음과 같이 mysql 콘솔에 액세스 할 수 있습니다.

$ mysql -P 8083 --protocol = tcp -u 루트 -p

Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.5.5-10.1.19-MariaDB-1~jessie mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

메모:

  • -d 플래그를 전달하여 분리 / 백그라운드 모드에서 mysql / mariadb 컨테이너를 실행할 수 있습니다.

  • 암호는 docker-compose.yml 파일에 정의 된 "wp"입니다.

  • Same advice as maniekq but full example with docker-compose.


The simple method is to share the mysql unix socket to host machine. Then connect through the socket

Steps:

  • Create shared folder for host machine eg: mkdir /host
  • Run docker container with volume mount option docker run -it -v /host:/shared <mysql image>.
  • Then change mysql configuration file /etc/my.cnf and change socket entry in the file to socket=/shared/mysql.sock
  • Restart MySQL service service mysql restart in docker
  • Finally Connect to MySQL servver from host through the socket mysql -u root --socket=/host/mysql.sock. If password use -p option

if you running docker under docker-machine?

execute to get ip:

docker-machine ip <machine>

returns the ip for the machine and try connect mysql:

mysql -h<docker-machine-ip>

I do this by running a temporary docker container against my server so I don't have to worry about what is installed on my host. First, I define what I need (which you should modify for your purposes):

export MYSQL_SERVER_CONTAINER=mysql-db
export MYSQL_ROOT_PASSWORD=pswd 
export DB_DOCKER_NETWORK=db-net
export MYSQL_PORT=6604

I always create a new docker network which any other containers will need:

docker network create --driver bridge $DB_DOCKER_NETWORK

Start a mySQL database server:

docker run --detach --name=$MYSQL_SERVER_CONTAINER --net=$DB_DOCKER_NETWORK --env="MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD" -p ${MYSQL_PORT}:3306 mysql

Capture IP address of the new server container

export DBIP="$(docker inspect ${MYSQL_SERVER_CONTAINER} | grep -i 'ipaddress' | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])')"

Open a command line interface to the server:

docker run -it -v ${HOST_DATA}:/data --net=$DB_DOCKER_NETWORK --link ${MYSQL_SERVER_CONTAINER}:mysql --rm mysql sh -c "exec mysql -h${DBIP} -uroot -p"

This last container will remove itself when you exit the mySQL interface, while the server will continue running. You can also share a volume between the server and host to make it easier to import data or scripts. Hope this helps!


mysql -u root -P 4406 -h localhost --protocol=tcp -p

Remember to change the user, port and host so that it matches your configurations. The -p flag is required if your database user is configured with a password


For conversion,you can create ~/.my.cnf file in host:

[Mysql]
user=root
password=yourpass
host=127.0.0.1
port=3306

Then next time just run mysql for mysql client to open connection.


run following command to run container

docker run --name db_name -e MYSQL_ROOT_PASSWORD=PASS--publish 8306:3306 db_name

run this command to get mysql db in host machine

mysql -h 127.0.0.1 -P 8306 -uroot  -pPASS

in your case it is

mysql -h 127.0.0.1 -P 12345 -uroot  -pPASS

change "localhost" to your real con ip addr
because it's to mysql_connect()

참고URL : https://stackoverflow.com/questions/33001750/connect-to-mysql-in-a-docker-container-from-the-host

반응형