The Pulsar Cafe    ·

MySQL in Docker

Lots of projects need a database. One option is to run these databases on your host machine. I think a better option is to run these databases in Docker containers on your host.

I feel this way for three reasons:

  1. If you need to run different versions of the same database for different projects, you won’t run into conflicts.
  2. The filesystem on the host machine won’t be affected by the clutter of the database install and config files.
  3. Uninstalling the database is as simple as removing the containers and the image. This is much better than the situation for some popular database platforms.

I’m starting a project that will use the MySQL database. Here is how to run MySQL in a Docker container, and connect to it from your host.

$ docker pull mysql:8.0  # or whatever version you want
$ docker run \
  -d \
  --name <db-name> \
  -p3306:3306 \
  -e MYSQL_ROOT_PASSWORD=<root-pw> \

At this point you will have a container named <db-name> running mysql and listening to port 3306, which is linked to your host port 3306. You can’t connect to it from your host, though, since the only user is ‘root’@‘localhost’. And the localhost for the container is the container, not your host machine.

So, drop a shell on the container and fix those privileges.

$ docker exec -it db-name bash
root@c1db3879590c:/# mysql -u root -p
Enter password:
mysql> create user 'me'@'%' identified by 'secret';
mysql> grant all privileges on *.* to 'me'@'%' with grant option;

That sequence of commands will set up a new user with admin privileges. Now you can log in from your host.

$ mysql -u me -p

Happy hacking.

comments powered by Disqus