Docker Compose — beginners
Sometimes, you might need to run many containers at once. For example, when developing a full-stack application. There will be separate containers for the frontend, backend, and database.
To start all these containers, you would need to type the docker run
command to start all the containers. Imagine you had to run 20 containers. Typing the command 20 times would be tedious. Docker compose helps you run many containers at once.
Docker compose is a tool used to run and manage multi-container applications. It helps you create, start and stop many containers using a single command.
To use docker-compose, define the configurations of the different containers in a docker-compose file.
Docker-compose file
A docker-compose file is a YAML file that contains instructions on how docker will create your containers.
Here is an example of a docker-compose file.
How To create a docker-compose file,
- Create a docker-compose.yml file in the root directory where all the project folders are located.
2. In the YAML file, state the version of docker-compose you want o use.
3. Define the configurations for the containers you want to build. This is done in the service section.
To define the configuration for an image,
Step 1: Give the image a name
Step 2: State how the image will be built.
In most cases, you would have written a docker file that contains instructions on how docker will build your images. Use the build
tag to specify the path to the docker file. Docker-compose will use the docker-file to build the image.
In cases where you want to use an existing image, E.g when you need containers for databases. Use the image
tag to specify the image. The image will be pulled from the docker hub during build time.
Step 3: Define other configurations
After specifying how the image will be built, you can specify other configurations for the image. e.g
- container-name
- port-mapping: the ports to be exposed for your container.
- environment-variables: e.g database credentials.
When your compose file is ready, run docker-compose up
in the directory where the docker-compose-file is located. This builds the images and starts up your containers.
Conclusion
To use docker-compose,
- Create Dockerfiles for each of the projects
- Create a docker-compose.yml file in the directory where all the projects are located. In the file, define the configurations for the docker images you need.
- Then in your terminal run
docker-compose up
to start the containers. And rundocker-compose down
to stop the containers.
Hope you found this helpful. Thanks for reading.