In this tutorial, we will introduce Docker Compose, a tool that simplifies the deployment and management of multi-container Docker applications. Docker Compose allows you to define and run multi-container Docker applications with just a single command.
By the end of this tutorial, you will:
Prerequisites
Before you start, you should have:
Docker Compose is a tool that allows you to manage and deploy multi-container Docker applications. It uses YAML files to configure application services and with a single command, you can create and start all services from your configuration.
The first step in using Docker Compose is to create a docker-compose.yml
file. This YAML file defines the services, networks, and volumes for your application.
Here's an example docker-compose.yml
file:
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
In this example, we have two services: web
and redis
. The web
service builds from the current directory and maps port 5000 on the host to port 5000 on the container. The redis
service uses the official Redis image from Docker Hub.
After creating the docker-compose.yml
file, you can start your application with the docker-compose up
command. This command will start and run your entire app.
Let's look at a practical example of using Docker Compose.
Suppose we have a simple Flask application that uses Redis as a message broker. Our project directory might look like this:
/
|-- app.py
|-- Dockerfile
|-- docker-compose.yml
The app.py
file is a simple 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 'Hello World! I have been seen %s times.' % redis.get('hits')
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
The Dockerfile
for the web
service might look like this:
FROM python:3.7-alpine
WORKDIR /app
ADD . /app
RUN pip install flask redis
CMD ["python", "app.py"]
And the docker-compose.yml
file:
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
To start the application, you would run docker-compose up
from your project directory. You should see output indicating that both the web and redis services have been started. If you navigate to http://localhost:5000
in your web browser, you'll see the text "Hello World! I have been seen n times.", with n incrementing each time you refresh the page.
In this tutorial, we've covered the basics of Docker Compose. We've learned how to define and run multi-container applications with a single command.
To continue learning about Docker Compose, you can:
docker-compose down
, docker-compose pause
, and docker-compose restart
.Remember, the best way to learn Docker Compose is by doing. Don't hesitate to experiment and try new things. Happy learning!