Friday, November 23, 2018

Share database container across multiple docker applications


1. Create database container


First create a docker-mysql folder under workspace and create the below docker-compose.yml file in it.


version: '2'
services:
    database:
        image: mysql:5.7
        environment:
            - "MYSQL_ROOT_PASSWORD=secret"
        ports:
            - "3306:3306"
        volumes:
            - ./storage/mysql:/var/lib/mysql

Then start the container by running following command docker-compose up -d. Finally run docker-compose ps command to verify the container started successfully.



2. Update docker application


Now add the below code in docker-compose.yml file under application folder to use the above database container. Also make sure to remove the existing database service and its links from the file. Insert the below code in the same level as version & services.

networks:
    default:
        external:
            name: docker-mysql_default

docker-mysql_default
 is the network name for the database container. Usually it's the folder name (docker-mysql) followed by _default. You can use docker network ls command to get the list of networks and double check the name. 


After you are done with editing run docker-compose up -d command to start the application.


Thats all. You also edit other applications you would like to use the shared database container. 


Hope this will help someone. Have a nice day :)