How to install MySQl and phpMyAdmin using Docker Compose

Whenever you start a new project, you always need a database and a dashboard to access and monitor your data. For most of the web applications, mysql and phpmyadmin are the most common tools being used for this purpose. Today we are going to write a docker compose file so that we can spin off a fresh database and phpmyadmin dashboard to access your database.

version: '3.1'

services:
  mysqldb:
    networks: 
      - my-project-network
    image: mysql:8.0
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    container_name: mysqldb-test # Container name has to be unique system wide
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: db_test
    ports:
      - 33060:3306 # The host ip, eg, 33060, has to be unique system wide
    volumes:
      - ./mysqldata:/var/lib/mysql
      - ./initdb:/docker-entrypoint-initdb.d # ./initdb has to be shared folder from docker

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    networks: 
      - my-project-network
    restart: always
    container_name: phpmyadmin-test # Container name has to be unique system wide
    ports:
      - 8083:80 # The host ip, eg, 8083, has to be unique system wide
    depends_on:
      - mysqldb
    environment:
      PMA_HOST: mysqldb

networks:
  my-project-network:
    driver: bridge

Create a docker-compose.yaml file with the above instructions. Create two directories in the same place where your docker compose yaml file resides called initdb and mysqldata. You can put any sql script to be run when the database is initialized. For example, the initial database stcuture and table creation sql commands can be a good thing to put in the initdb. The docker container uses the directory mysqldata to write the database files. It is a good practice to write the database files on host machine so that can be used by multiple containers when necessary.

So, now we are ready to start our database and phpmyadmin control panel. Just execute docker-compose up in the terminal where the docker compose yaml file exists. Docker compose by default looks for a file named docker-compoase.yaml when no docker compose file is specifically mentioned. After the containers are ready, you can access the phpmyadmin at http://localhost:8083 and login with root as username/password. The mysql database can also be accessed from host machine using this following command:

mysql -u root -P 33060 --protocol=TCP -p

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top