How to run a MySQL server in a Docker container and connect to it from the host machine?

How to run a MySQL server in a Docker container and connect to it from the host machine?

ยท

2 min read

1. Create an EC2 instance

  • Creating an EC2 instance on AWS is very easy. You can follow the instruction on this website here or AWS document.

2. Run a MySQL server in a Docker container

  • Read docker doc to install docker here.
# check docker version
docker --version
  • Pull down the MySQL image from docker
# Pull the latest mysql version
docker pull mysql
  • Run MySQL image
# `some-mysql` is the name of your container
# `my-secret-pw` is the password of your root user
# `127.0.0.1:3307:3306` specifying where the port you want mysql to run `<host>:<host port>:<mysql port>`
# `tag` specifying the mysql version you want
docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -p 127.0.0.1:3307:3306 -d mysql:tag
  • Shows all of the Docker processes actively running to

3. Connect to it from the host machine

3.1. First method: docker exec

You need to run docker exec to run a command in the mysql container. You can read docs for more options and arguments here.

docker container exec [OPTIONS] CONTAINER COMMAND [ARG...]

Follow all steps below to connect to mysql.

  • Get the container id
docker ps

Screenshot from 2021-11-18 23-05-45.png

  • Execute command in mysql container with docker exec.
# `docker exec` run a command in a running container
# `eafb788cfd28` is the container id
# `mysql -uroot -pmy-secret-pw -e 'show databases;'` is the command you want to run in mysql container
# `root` is user `root`
# `mysecert-pw` is your password

docker exec eafb788cfd28 mysql -uroot -pmy-secret-pw -e 'show databases;'

Screenshot from 2021-11-18 23-28-35.png

3.2. Second method: mysql client

The second method is short and simpler. You don't need to run docker exec for every command.

  • You need to have mysql run on your machine.
# check where mysql in your machine
which mysql
  • If you run mysql in your machine without specifying host and post, it will return an error.
mysql -uroot -p123 -e 'show databases;' # error

Screenshot from 2021-11-18 23-24-39.png

# `-h` is your host
# `-P` is your host port. Don't be confused it with mysql port.
mysql -uroot -p123 -h 127.0.0.1 -P3307 -e 'show databases;' # correct

Screenshot from 2021-11-18 23-28-35.png

Did you find this article valuable?

Support Anh Nhat Tran by becoming a sponsor. Any amount is appreciated!

ย