Flask on Docker
Ok, at this point, you might want a meatier example of why we would use docker. What if we had built an entire flask app and now wanted to transport it to production. How could we use docker to accomplish that?
Setting up the Project Directory
First we need to create the directory to hold this:
mkdir flask
cd flask
Then we are going to add some boilerplate to a file called app.py
:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Docker!"
if __name__ == '__main__':
app.run()
Setting Up the Requirements
Next we are going to set up the requirements.
To start, we are going to create a venv
that will hold what dependencies we need for this project.
python -m venv venv
Don't forget to activate your venv
source venv/bin/activate
Then we will install flask:
pip install flask
Finally, we are going to freeze our pip requirements into a txt:
pip freeze > requirements.txt
At this point if you wanted to, you could run your flask app locally. All you would have to do enter:
python app.py
This is essentially your development environment. When you are ready to have your flask app go to production, you would put it in a container and send that container to wherever you need it to go.
The Dockerfile
Ok now that we have our app ready to go. We need to build a Dockerfile so we can have it running on an image:
# Use the official Python image from the Docker Hub
FROM python:3.11-alpine
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set the working directory inside the container
WORKDIR /app
# Copy requirements.txt and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the application code
COPY . .
# Expose port 5000 to access the app
EXPOSE 5000
CMD ["python", "app.py"]
Let's take a look at what's happening here in a bit more detail:
FROM python:3.11-alpine
we are starting with a python image from DockerhubWORKDIR /app
we are creating a working dir within the containerCOPY requirements.txt .
We are copying our requirements into that containerRUN pip install --no-cache-dir -r requirements.txt
installing the requirements onto the container from the requirements.txtCOPY . .
we are copying the rest of the application overEXPOSE 5000
we are exposing a port so that the container can interact with the outside worldCMD ["python", "app.py"]
and finally we are setting a default command that will be executed when the container is started.
Running the Application
There is one thing that might really trip you up if you are not careful. Exit the venv before running docker commands.
deactivate
Next we are going to build the image and then run it:
docker build -t flask .
docker run -p 8080:5000
The navigate to http://localhost:8080
to see your flask app up and running!