Published on 2024-02-24
DockerPart 2 of Docker to the rescue! A short description of docker compose with a simple example: Docker Compose is a neat way to connect different docker containers as a single service.
Docker Compose When there are multi-containers application, Docker Compose can come in handy.
For Example, in an e-commerce website, there are different products/functions with their own an account database, product database, cart database and other modules running in silo behind the scenes. Each of these can be considered as a micro-service. These micro-services run in isolation but can interact with each other when required. This helps reduce dependencies and enables the system to evolve with minimal downtime.
Docker Compose is a neat way to connect different containers as a single service. Compose files are written in a scripting language called YAML (Yet Another Markup Language). Another great thing about Docker Compose is that users can activate all the services (containers) using a single command.
Docker provides a great guide with the example of separating Application (Todo App) from Database (MySQL). Separate containers let you upgrade and update versions in isolation. Isn't that neat?!
Docker Compose needs to be installed separately from Docker, though recent versions of Docker Desktop (for both Windows and macOS) come with Docker Compose pre-installed.
In order to install Docker compose, in the terminal (CLI): 1. Fetch the Latest Version Programmatically
LATEST_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep "tag_name" | cut -d '"' -f 4)
2. install Docker Compose with Correct URL
sudo curl -L "https://github.com/docker/compose/releases/download/${LATEST_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
3. Set Executable Permissions
sudo chmod +x /usr/local/bin/docker-compose
4. Verify Docker Compose Installation
docker-compose --version
Once done, docker compose is ready to use. Here's a very simple layout of docker-compose yml where I define my backend service with fastapi which exists in the 'server' directory and the port to map is 8000, and frontend with vite in the 'client' directory the port mapping as 5001:500.
Now, all I have to specify is that the backend is dependent on the frontend vite, meaning Docker compose will start the vite service before starting fastapi. This ensures vite is ready when fastapi starts.
version: '3.8'
services:
fastapi:
build:
context: ./server
ports:
- "8000:8000"
depends_on:
- vite
vite:
build:
context: ./client
ports:
- "5001:5000"
Then, I would just need to issue one command to start both fastapi and vite containers.
docker-compose up -d
Cool, ah?