Installation on Linux
Download the latest stable binary direct from the project's GitHub repository. Use the following command, which automatically detects your operating system and architecture:
curl -L "https://github.com/docker/compose/releases/download/v2.24.5/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
Apply executable permissions to the downloaded binary:
chmod +x /usr/local/bin/docker-compose
Optionally, create a symbolic link to make the command accessible system-wide:
ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
Verify the installation by checking the version:
docker-compose version
Building a Sample Application
1. Project Setup
Create a working directory for the project:
mkdir my-web-app
cd my-web-app
Create a Python application file named main.py. This script uses Flask for the web server and Redis for caching. Note that the hostname redis coresponds to the service name defined later in the Compose file.
import time
import redis
from flask import Flask
app = Flask(__name__)
redis_client = redis.Redis(host='redis', port=6379)
def fetch_visit_count():
attempts = 5
while True:
try:
return redis_client.incr('visits')
except redis.exceptions.ConnectionError as e:
if attempts == 0:
raise e
attempts -= 1
time.sleep(0.5)
@app.route('/')
def index():
count = fetch_visit_count()
return f'Hello! This page has been viewed {count} times.\n'
Create a requirements.txt file to list the Python dependencies:
flask
redis
2. Defining the Container Image
Create a Dockerfile to containerize the Python application:
FROM python:3.9-slim
WORKDIR /app
ENV FLASK_APP=main.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apt-get update && apt-get install -y --no-install-recommends gcc && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["flask", "run"]
3. Orchestration with Compose
Create a docker-compose.yml file to define the multi-container setup. This configuraton manages a web service (built from the local Dockerfile) and a database service (using a public Redis image).
version: '3.8'
services:
web:
build: .
ports:
- "5000:5000"
depends_on:
- redis
redis:
image: redis:alpine
4. Running the Environment
Execute the following command in the project directory to build the images and start the containers in the foreground:
docker-compose up --build
Once the services are running, navigate to http://localhost:5000 in your browser to see the visit counter.