connect to mysql server in docker
docker run --name mysqlserver -e MYSQL_ROOT_PASSWORD=pass -d mysql:5.5
and link second docker container with first container:
docker run --name myapp --link mysqlserver:mysql -d vladimir/app
and if in second docker container I have python app, where I just want to connect to the database in first container, how to determine what host to use?
One Solution collect form web for “connect to mysql server in docker”
I am not too familiar with mysql. Looking at the mysql documentation it seems like this might be the sort of command you want:
import _mysql db=_mysql.connect(host="mysql",port=3306,passwd="...",db="...")
when you did the –link in your apps run, you declared that you are linking the EXPOSEd ports for the container named mysqlserver to the container to be named myapp. Docker updates the /etc/hosts file. So, if you cat the /etc/hosts file you should see a line that looks like:
172.17.0.26 mysql 5c960433e26a mysqlserver
so this is why the reference in your python to host ‘mysql’ works. The default port is 3306. So, that should connect you. Use this host and port for whatever mysql connection package you are using from python.
This is how I connect with other objects, on their well known ports. You can also use environment variables, but, I think this might be being phased out…dunno…
root@d23d8be2a6fa:/# env | grep MYSQL MYSQL_ENV_MYSQL_ROOT_PASSWORD=pass MYSQL_PORT_3306_TCP_PORT=3306 MYSQL_PORT_3306_TCP=tcp://172.17.0.32:3306 MYSQL_ENV_MYSQL_VERSION=5.5.42 MYSQL_NAME=/myapp/mysql MYSQL_PORT_3306_TCP_PROTO=tcp MYSQL_PORT_3306_TCP_ADDR=172.17.0.32 MYSQL_ENV_MYSQL_MAJOR=5.5 MYSQL_PORT=tcp://172.17.0.32:3306
so you could modify your connect line to use the environment:
import os myhost = os.environ.get('MYSQL_PORT_3306_TCP_ADDR') myport = int(os.environ.get('MYSQL_PORT_3306_TCP_PORT')) import _mysql db=_mysql.connect(host=myhost,port=myport,passwd="...",db="...")
Either way. This is discovery. There are more complicated methods as well, using consul, etcd, skydns, registrator. I like the skydns/registrator pairing, registrator watches your docker daemon, when new containers are created it inserts dns records into etcd, which skydns can use to mimic a dns server. Using this technique you get ip and port as well.