What is Docker-Compose? Give an example.

What is Docker-Compose? Give an example.

Docker Compose is a tool that helps you manage and run applications with multiple Docker containers. You can create a YAML file to set up multiple containers, and then use just one command to make and start all the containers in the file. This tool makes it easier to handle complicated applications by letting you organize and control many containers, their settings, and their connections. Here is a simple example to illustrate how Docker Compose works:

Let's consider a basic Flask web application with a Redis database. The structure of the project may look like this:

/myapp
|-- app
|   `-- app.py
|-- docker-compose.yml
`-- requirements.txt
  1. app/app.py (Flask Application):
from flask import Flask
from redis import Redis

app = Flask(__name__)
redis = Redis(host='redis', port=6379)

@app.route('/')
def hello():
    redis.incr('hits')
    return f'Hello from Docker! This page has been viewed {redis.get("hits").decode("utf-8")} times.'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
  1. requirements.txt (Flask and Redis dependencies):
Flask==2.0.1
redis==3.5.3
  1. docker-compose.yml (Docker Compose configuration):
version: '3'
services:
  web:
    build: ./app
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

In this example:

  • The web service builds the Flask application using the Dockerfile located in the ./app directory. It also exposes port 5000 on the host, mapping it to port 5000 on the container.

  • The redis service uses the official Redis image from the Docker Hub.

To use Docker Compose with this setup, navigate to the directory containing your docker-compose.yml file and run the following commands:

# Build and start the services
docker-compose up

# Access the Flask application at http://localhost:5000

This will create and start the defined services (Flask and Redis) in separate containers. The Flask application is accessible at http://localhost:5000, and it interacts with the Redis container.

To stop and remove the containers created by Docker Compose, you can use:

docker-compose down

This example is easy, but Docker Compose can handle more complicated setups with many services, networks, and volumes. It's a strong tool for managing applications that use multiple containers.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!