Install and run MySQL with Docker and Docker Compose

docker-mysql

MySQL is one of the most common open-source relational database engines. Running it with Docker is useful for development, testing and portable environments because the database can be isolated, recreated and moved more easily.

Pull the MySQL image

docker pull mysql:latest

Create a Docker network

A dedicated network lets applications communicate with the database by container name.

docker network create buenosaires

Run MySQL with persistent data

mkdir -p /opt/mysql

docker run -d \
  --name buenosaires-mysql \
  --network buenosaires \
  -e MYSQL_ROOT_PASSWORD="RandomPassword" \
  -v /opt/mysql:/var/lib/mysql \
  -p 3306:3306 \
  mysql:latest

The mounted directory keeps data available even if the container is recreated.

Using a Docker volume

docker volume create buenosaires-mysql-data

Docker Compose example

version: '3'

networks:
  default:
    external:
      name: buenosaires

volumes:
  buenosaires-mysql-data:
    external: true

services:
  mysql:
    image: mysql:latest
    ports:
      - 3306:3306
    volumes:
      - "./buenosaires-mysql/mysql:/etc/mysql/mysql.conf.d"
      - "buenosaires-mysql-data:/var/lib/mysql"
      - "./buenosaires-mysql/scripts:/tmp/scripts"
    environment:
      - MYSQL_HOST=${MYSQL_HOST}
      - MYSQL_USER=${MYSQL_USER}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
      - MYSQL_PORT=${MYSQL_PORT}

Production note

Use strong secrets, private networks, backups and monitoring. Avoid exposing port 3306 publicly unless there is a specific secured requirement.

Leave a Reply