Docker Compose — beginners

Ezeofor Philip
AWS Tip
Published in
3 min readJan 12, 2023

--

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,

  1. Create a docker-compose.yml file in the root directory where all the project folders are located.
Example of how your folder structure should look like.

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,

  1. Create Dockerfiles for each of the projects
  2. 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.
  3. Then in your terminal run docker-compose up to start the containers. And run docker-compose down to stop the containers.

Hope you found this helpful. Thanks for reading.

--

--

Hello and welcome. I'm a software engineer. I build projects using Java | Kotlin| Aws. I write about my learnings. I hope you enjoy my blog.