Remote Connect to MariaDB on Docker containers

Quick Tip

When you setup MariaDB or MaxScale on containers for testing purposes, normally you only access them within Docker, either from other containers or from the host.
But what happens if you want to access the database from a remote site, for example when you have to connect an application to the database or you want to use a mysql graphical client on a remote laptop.

In order to do that you need to publish the container listener port to the Docker host using the option -p hostport:containerport when creating a container.

Publish MariaDB Port

If you have a single instance you can publish directly the MariaDB database port 3306 to have a connectivity like this:

Remote mysql client -> 7706:Docker host -> 3306:MariaDB Container

Publish the port at container creation time:

docker run -d -p 7706:3306 --name patomariadb --network pato-net -v patovoldb:/var/lib/mysql patomx/patomariadb

now the port is listening on the Docker host:

pato@patocontainer ~ $ netstat -na | grep LISTEN
tcp6       0      0 :::7706                 :::*                    LISTEN

and the database can be accessed remotely connecting like this:

mysql -u remoto -p -h patocontainer -P 7706
Publish MaxScale Port

For a MariaDB cluster our MaxScale should be the single access point, so we are going to publish only the MaxScale container ports in order to achieve this:

Remote mysql client -> 8006:Docker host -> 4006:MaxScale Container -> 3306:MariaDB Container(s)

Publish the Maxscale ports (4006, 4008) at container creation time:

docker run -d -p 8006:4006 -p 8008:4008 --name patomaxgalera --network pato-net patomx/patomaxscale

now those ports are also listening on the Docker host and can be accessed remotely:

pato@patocontainer ~ $ netstat -na | grep LISTEN
tcp6       0      0 :::8006                 :::*                    LISTEN
tcp6       0      0 :::8008                 :::*                    LISTEN

and we can connect from outside, like this:

mysql -u remoto -p -h patocontainer -P 8006

Now you can use your container MariaDB database remotely