Quickly Spin Up MySQL w/ Docker Compose

alexmacarthur

Alex MacArthur

Posted on August 23, 2019

Quickly Spin Up MySQL w/ Docker Compose

I’ve often needed to quickly spin up a local instance of MySQL. Docker Compose this makes it stupid easy. Rather than running a long, convoluted docker command, I can configure an image just the way I want it while maintaining the ability to turn it easily turn it on and off as needed.

Getting Set Up

Inside a new directory, create a data directory and docker-compose.yml file.

new-directory
├── data
└── docker-compose.yml
Enter fullscreen mode Exit fullscreen mode

Paste the following into your docker-compose.yml file:

version: '3'

services: 
  db:
    container_name: docker-local-mysql
    image: mysql:5.7.21
    volumes:
      - "./data:/var/lib/mysql"
    restart: always
    ports:
      - 3306:3306
    environment:
      MYSQL_ROOT_PASSWORD: root
Enter fullscreen mode Exit fullscreen mode

Managing a Container

To start the container, run docker-compose up. To stop & remove the container, run docker-compose down. For more information on the plethora of commands avaible to leverage your container, see here.

Persisting Data

Whenever MySQL modifies any data within the container, it will persist locally inside your ./data directory, even after you stop and restart everything. This is configured by the volumes: property in your docker-compose.yml file.

Running Commands Inside Container

To run any Bash commands inside the running container, use docker-compose exec db bash.

Connecting w/ SequelPro or Similar Tool

Use the following values to connect to the running container.

Host: 127.0.0.1

Username: root

Password: root

Port: 3306

The End.

Boom. With a single command, you have a running, persistent, self-contained MySQL instance ready for your development needs. Have a hot, helpful tip related to anything here? Share it!

💖 💪 🙅 🚩
alexmacarthur
Alex MacArthur

Posted on August 23, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related