7 Preparing Docker Compose file

So far we have been running individual 'docker' commands, which can be tedious at times as you repeat the commands.

The 'docker-compose' utility allows us to execute a 'docker-compose file' and run multiple 'docker' commands at once.

For instance, the following set of commands:

docker network create my-network docker run -d -p 27017:27017 --network my-network --name my-mongo -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=pass -v my-data:/var/lib/mysql/data mongo docker run -d -p 8081:8081 --network my-network --name my-mongo-express -e ME_CONFIG_MONGODB_ADMINUSERNAME=admin -e ME_CONFIG_MONGODB_ADMINPASSWORD=pass -e ME_CONFIG_OPTIONS_EDITORTHEME=ambiance -e ME_CONFIG_MONGODB_SERVER=my-mongo mongo-express docker run -d -p 80:80 --network my-network --name my-app my-app:7.0

can be restructured and mapped to the following docker-compose file, my-app.yaml:

version: '3.7' services: my-mongo: image: mongo ports: - 27017:27017 environment: - MONGO_INITDB_ROOT_USERNAME=admin - MONGO_INITDB_ROOT_PASSWORD=pass volumes: - my-data:/data/db my-mongo-express: image: mongo-express environment: - ME_CONFIG_MONGODB_ADMINUSERNAME=admin - ME_CONFIG_MONGODB_ADMINPASSWORD=pass - ME_CONFIG_OPTIONS_EDITORTHEME=ambiance - ME_CONFIG_MONGODB_SERVER=my-mongo ports: - 8081:8081 my-app: image: my-app:7.0 ports: - 80:80 volumes: my-data: driver: local

Above, data persistence is ensured for the directory /data/db on the virtual file system of the container my-mongo, so that when you removed and rerun the container, the database data is still intact.

Make sure the spacing is valid:

docker-compose inherently runs the containers within the same netowrk.

To run the the docker-compose file:

docker-compose -f my-app.yaml up

To remove the containers:

docker-compose -f my-app.yaml down