In last week’s blog, I introduced the power of container technology, Docker. Besides the advantage of easy implementation, however, implementing a command again and again using a terminal is not a good idea long-term. Therefore, Docker Compose is a tool for defining and running multi-container Docker applications by implementing all the applications commands to a YAML file and having it executed when needed.
According to the Overview of Docker Compose, using Compose is a three-step process:
1. Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
2. Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
3. Run docker compose up and the Docker compose command starts and runs your entire app. You can alternatively run docker-compose up using the docker-compose binary.
Dockerfile is another concept, while in this blog I will introduce how to manipulate Docker compose. Let’s take this command as an example when we want to create a nginx server
docker run -d --rm \
--name nginx-server \
-p 8080:80 \
-v /some/content:/usr/share/nginx/html:ro \
nginx
This command serves the purpose of mounting an html file to the nginx server running at port 8080 locally where nginx-server is the name of the container, -p 8080:80 is mapping the local port at first parameter and the default container port at the second parameter, separated by a colon and -v /some/content:/usr/share/nginx/html:ro will mount that 8080 port with the html file at the pointed directory. Translating this command into Docker compose:
version: “3.9”
services:
nginx-server:
image: nginx
ports:
- 8080:8080
volumes:
- /some/content:/usr/share/nginx/html:ro
Version is the version of Docker compose we want to use, all the necessary commands will be integrated and placed under the services section. Name of the container is placed at first then all of its entities are written after a colon and one indentation in the next line. Image tag is the application we want to create, ports is equivalent to -p to map the port, and volume is the same as -v used for mounting. Under this format, we can implement as many images as we want at once and just rerun it with the command docker-compose up
in the directory containing that docker-compose.yml file.
version: “3.9”
services:
nginx-server:
image: nginx
ports:
- 8080:8080
volumes:
- /some/content:/usr/share/nginx/html:ro
redis-container:
image: redis
…
Overall, the convenience of Docker is taken to a higher level thanks to the compose concept. Also, this video is another source that I watched to understand more about docker-compose. Therefore, I suggest using the main Docker Compose page from their site and this video as a reference if you might need it in the future.
From the blog CS@Worcester – Vien's Blog by Vien Hua and used with permission of the author. All other rights reserved by the author.