Welcome to this detailed tutorial on using Docker Compose with Flask! In this lesson, we'll explore how to create and manage Flask applications using Docker Compose, making it easier to deploy and scale your projects. 🎯
By the end of this tutorial, you'll be able to:
Let's get started! 🚀
Before diving into the Docker Compose for Flask tutorial, make sure you have the following prerequisites:
First, let's create a simple Flask application. Create a new directory for your project and navigate to it:
mkdir flask_docker_compose
cd flask_docker_composeNext, create a new file named app.py and paste the following code:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def hello():
return jsonify({'message': 'Hello, Docker!'})
if __name__ == '__main__':
app.run(debug=True)This code creates a basic Flask application that responds with a JSON message when accessed at the root URL.
Now, let's add a Dockerfile to our project to create a Docker image for our Flask application:
FROM python:3.9
WORKDIR /app
COPY . /app
RUN pip install flask
EXPOSE 5000
CMD ["python", "app.py"]Next, create a docker-compose.yml file:
version: "3.8"
services:
web:
build: .
ports:
- 5000:5000
command: python app.pyThis docker-compose.yml file defines a single service called web that uses the Dockerfile in the current directory to build an image, exposes port 5000, and runs our Flask application.
Now, let's try building and running our Docker Compose application:
docker-compose up --buildThis command will build the Docker image, start the service, and make our Flask application accessible at http://localhost:5000.
To stop the application, press Ctrl+C in the terminal where the docker-compose up command is running.
In real-world projects, you may have multiple services, such as a database, queue, or cache. To manage these services, we can use multi-service Docker Compose files.
Create a new file named docker-compose-multi.yml:
version: "3.8"
services:
web:
build: .
ports:
- 5000:5000
command: python app.py
db:
image: postgres:13.2-alpine
environment:
POSTGRES_PASSWORD: mysecretpassword
POSTGRES_DB: mydatabase
redis:
image: redis:6.0-alpineIn this example, we added a PostgreSQL database (db) and Redis cache (redis) to our application. To build and run the services, use the following command:
docker-compose -f docker-compose-multi.yml up --buildNow you have a better understanding of how to use Docker Compose with Flask. Let's test your knowledge with a quick quiz!
What command is used to build and run the services in a multi-service Docker Compose file?