Docker Compose File
Kamalpreet Singh
AWS certified cloud Practitioner| DevOps Engineer | AWS | Site Reliability Engineer | Linux | Jenkins | Kubernetes | Git | Terraform | Docker
Hi Folks,
In this article, we will learn the importance of docker-compose.yml file.
Consider the case where we are working on a two-tier app deployment using docker Images. If we are not using the docker-compose.yml file then we need to run commands manually for both the frontend docker image and the Backend Docker Image. This means first we need to build the backend docker images and then run it. Similarly, then we need to build a Frontend docker image and then Run it. We even need to add a network in some cases so this is a tedious task. Sometimes if we are working in a PROD environment then it may lead to the site being down due to some incorrect commands.
So to resolve this issue and use only a single command to make the project live we can use the docker-compose.yml file.
In the docker-compose.yml file, we write services (And services contain docker containers and their details).
Sample docker-compose.yml file to deploy two-tier flask app with Mysql backend :
version: '3' //We need to specify the Version at the top. currently, version 3 is used.
services: // under services we need to specify the Two services for Two-tier app
backend: // The first service is Backend Service
build: //Here we are providing context : . to build the docker image in the current Directory.
context: .
port: // port is used to map the Port
-"5000:5000"
environment: // here we are providing the environment variables used for the service
MYSQL_HOST: mysql
MYSQL_USER: admin
MYSQL_PASSWORD: admin
MYSQL_DB: myDB
depends_on: // in depends_on we specify the Service which should be built before this service in which we use depends_on. This means MySQL service should be built before the Flask service
-mysql
领英推荐
mysql: //The second service is Mysql service
image: mysql:5.7 //Since we have not configured the build file for Mysql so we will use the image here.
ports:
-"3306:3306" // port mapping
environment: // environment variables
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: admin
MYSQL_PASSWORD: admin
MYSQL_DB: myDB
volumes: //Here we can specify the volumes / common directory for both services
- ./message.sql:/docker-entrypoint-initdb.d/message.sql // here we use docker-entrypoint-initdb.d to run file before creating services. This means message.sql file will run and the table will be created automatically due to this particular line.
- mysql-data:/var/lib/mysql // mapping directory with the file in the current directory.
volumes:
mysql-data
Now we can use just a single command docker-compose up to run both services. Means with a single command both services will be up and even table will be created frommessage.sql file.