smeeb
smeeb

Reputation: 29487

Connecting to Docker container from host

I just pulled and run the official Docker MySQL image and have it running locally on my machine:

docker run --name mydb -e MYSQL_ROOT_PASSWORD=12345 -d mysql:5.7.11

The instructions on that screen tell you how to connect to the MySQL server (container) from inside yet another container (which is configured as a command-line client). But I have a generic JDBC fat client (SQuirreL) and am wondering how to connect to my docker container.

For the JDBC connection string, I need to provide both a hostname and a dbname, what can I use? I would imagine the Docker container is somehow addressable from my host OS, but I haven't actually created any databases yet, so I'm not sure what dbname value I can supply:

jdbc:mysql://<hostname>:3306/<dbname>

Upvotes: 0

Views: 2483

Answers (1)

joksnet
joksnet

Reputation: 2325

You could run your instance with forwarding 3306:

$ docker run --expose=3306 -p 3306 mysql

See incoming ports.

The you specify:

jdbc:mysql://127.0.0.1:3306/<dbname>

You command become:

$ docker run --name mydb -e MYSQL_ROOT_PASSWORD=12345 -d --expose=3306 -p 3306 mysql:5.7.11

You might need to change the MySQL configuration.

Can go inside the container with:

$ docker exec -it mydb bash

And then you could:

$ echo "bind-address = 0.0.0.0" >> /etc/mysql/my.cnf

Don't forget to reload mysql.

Then you have to create the database and import your schema (if needed).

$ mysql -uroot -p12345 -e"CREATE DATABASE mydb"
$ mysql -uroot -p12345 mydb < mydb-schema.sql

Upvotes: 3

Related Questions