Docker : Database Syncing on local environment

To address the problem of database synchronization in local development, Docker plays the very important role. With the help of docker containerization, We can manage the database syncing with in the team.

Let’s Assume we have a team of 40 people and out of them 25 are in development. Development team working on micro service architecture. So it is essential to provide the database setup on local and make it syncing with each developer machine. So that every developer must have database up to date with in the same version of other environment like Prod/QA/Stage/Prod etc…

Lets design the concept of docker file where we will put the connection of database like MySQL. Developer can write the own updated SQL query in one file and publish it to other developer. Please see the below docker-compose.yaml file

version: "3.8"

services:
  mysql:
    image: "mysql:8.0"
    restart: always
    ports:
      - "${MYSQL_PORT:-3306}:3306"
    environment:
      - VIRTUAL_HOST="mysql.testlab.local"
      - MYSQL_ROOT_PASSWORD=test123
    volumes:
      - ./mysql/init:/docker-entrypoint-initdb.d
      - testdata:/var/lib/mysql
    networks:
      - test-base

networks:
  test-base:
    name: test-base

volumes:
  testdata:
    driver: local

Some important point to know here is use of Image, we are using mysql version 8.0.

Defining Environment variable for the root password and host etc. We can define more like MYSQL_USER, MYSQL_PASSWORD etc. Further if you want to see other environment variable please follow the link https://dev.mysql.com/doc/refman/5.7/en/environment-variables.html

Define the Network section that help to connect with other container, if we have.

Now you are ready to use the docker-compose.yaml file. Next task is to run the docker file with the help of below command.

docker-compose up

Here, One thing is noticeable that is use of Volumes section where we are defining the local data path. That path has SQL file that is used to create database/table or insert/update/delete table records etc.. Here path is “./mysql/init/*.sql” for SQL files.

Whenever the developer feel there is some update coming from any other folks then we have to run the below command in the terminal.

$ docker-compose down //To down the running docker
$ docker volume ls    // To get the list of volume attached 
Select the Volume that has suffice "testdata"
$ docker volume rum <volume-name> // remove the old volume
$ docker-compose up.     //get the updated container with new dataset

That’s all !!

  • 23
    Shares