Connect to mysql in a docker container from the host

后端 未结 14 746
青春惊慌失措
青春惊慌失措 2020-11-29 16:25

(It\'s probably a dumb question due to my limited knowledge with Docker or mysql administration, but since I spent a whole evening on this issue, I dare to ask it.)

14条回答
  •  有刺的猬
    2020-11-29 16:44

    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!

提交回复
热议问题