Skip to content

Instantly share code, notes, and snippets.

@nyukeit
Last active August 6, 2024 14:11
Show Gist options
  • Save nyukeit/8ecdfbd8c3f05b015b1e8248dcc39a9d to your computer and use it in GitHub Desktop.
Save nyukeit/8ecdfbd8c3f05b015b1e8248dcc39a9d to your computer and use it in GitHub Desktop.
Docker for MySQL Projects

Using a Docker Container as MySQL DB Server

Requirements

Docker Desktop (MacOS/Windows)
Docker Engine + Docker Compose Plugin (Linux)

Docker-Compose File

Create a folder that you can mount into the container. This will be the persistent volume for your DB.

# This Docker Compose YAML deploys a MySQL database
services:
  container-name:
  
    image: mysql # Official MySQL image from Docker Hub
    restart: always
    
    environment:
      # Note - Root password is mandatory for the container to run and grant privileges to our User.
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      
      MYSQL_DATABASE: ${MYSQL_DATABASE} # Same name as used in your project
      
      # DB User Details
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
      
    ports:
      # Adjust this port as per your needs -> <hostPort>:<containerPort>
      - 3308:3306 # DB is available at localhost:3308 on the host.
      
    volumes:
      - ./volumes/db-mnt:/var/lib/mysql

Environment Variables

You can either create a .env file in the same folder as the docker-compose.yaml or supply the path to the file.

# Contents of .env file
MYSQL_ROOT_PASSWORD=rootpassword
MYSQL_DATABASE=databasename
MYSQL_USER=username
MYSQL_PASSWORD=userpassword

Running the Container

If your .env is in the same folder

docker-compose up -d

If your .env is in another folder

docker-compose up --env-file=/path/to/file -d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment