Running and connecting to different MySQL servers in Docker containers

Running and exposing default MySQL port:

docker run -e MYSQL_ROOT_PASSWORD=mypassword -p 3306:3306 -d mysql
mysql -u root -p

Running with a different exposed port on the host:

docker run -e MYSQL_ROOT_PASSWORD=mypassword -p 3307:3306 -d mysql

Connecting to server on different port : -P option, but also requires -h for host, otherwise seems to connect to whatever is running on 3306 by default:

mysql -h 127.0.0.1 -P 3307 -u root -p

Which my.cnf is mysql using?

mysql searches for your local my.cnf in a number of default places, so finding which is actually in use can be an issue.

To find which search paths are currently being used by your current mysql install (from here), use:

mysql --help | grep my.cnf

And it will show a list of paths like this:

> mysql --help | grep my.cnf
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/my.cnf /etc/mysql/my.cnf /opt/homebrew/etc/my.cnf ~/.my.cnf

Note that if you installed mysql via homebrew (on MacOS), this will also show the homebrew path where my.cnf is located.

Moving from msql client to mysqlsh

I posted a while back about running mysql in a Docker container on an Apple Silicon MacBook. It’s been a while since I’ve run mysql locally, and it seems the mysqlsh client is now preferred over the previous mysql client.

With mysqlsh, after connecting, to issue a ‘use’ command to select a db, use ‘\use dbname’

Once a db is selected, to issue other mysql commands enter the sql mode with ‘\sql’ command.

Running MySQL in a Docker container on MacOS

It’s been a while since I’ve run MySQL server on my MacBook Pro (see past notes here , here and more here) and since I got my new M1 MBP I haven’t installed it yet. Rather than doing a native install, I want to run it as a Docker container so I can throw it away easily when I’m done.

Starting MySQL in a Container

From the MySQL Docker page, run:

docker run -p 3306:3306 --name mysql-springboot -e MYSQL_ROOT_PASSWORD=your-root-pass-here -d mysql

The important part here is -p to expose port 3306 in the container as 3306 on the host. This will allow you to connect to localhost:3306 locally to MySQL in the container as if it’s running locally.

Connecting with mysql shell locally

Connect with mysql shell as if the server is running locally:

mysqlsh -u root

and enter the password when prompted. Create a db and setup a user that you use from your app running locally:

create database example;
create user 'exampleuser' identified by 'examplepassword';
grant all on example.* to 'exampleuser'