Connect to mysql in a docker container from the host Connect to mysql in a docker container from the host docker docker

Connect to mysql in a docker container from the host


If your Docker MySQL host is running correctly you can connect to it from local machine, but you should specify host, port and protocol like this:

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

Change 3306 to port number you have forwarded from Docker container (in your case it will be 12345).

Because you are running MySQL inside Docker container, socket is not available and you need to connect through TCP. Setting "--protocol" in the mysql command will change that.


If you use "127.0.0.1" instead of localhost mysql will use tcp method and you should be able to connect container with:

mysql -h 127.0.0.1 -P 3306 -u root


I recommend checking out docker-compose. Here's how that would work:

Create a file named, docker-compose.yml that looks like this:

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

Next, run:

$ docker-compose up

Notes:

Now, you can access the mysql console thusly:

$ mysql -P 8083 --protocol=tcp -u root -p

Enter password:Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 8Server version: 5.5.5-10.1.19-MariaDB-1~jessie mariadb.org binary distributionCopyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql>

Notes:

  • You can pass the -d flag to run the mysql/mariadb container in detached/background mode.

  • The password is "wp" which is defined in the docker-compose.yml file.

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