Running Flask App in Production Mode
When running a Flask application in a production environment, it's important to use a production-ready server instead of the built-in development server. In this section, we'll learn how to run a Flask application in production mode using Docker.
Choosing a Production Server
There are several production-ready web servers that can be used to run a Flask application, such as Gunicorn, uWSGI, and Waitress. In this example, we'll use Gunicorn, a popular and widely-used web server for Python applications.
Modifying the Dockerfile
To run the Flask application in production mode using Gunicorn, we need to update the Dockerfile. Replace the contents of the Dockerfile
with the following:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN pip install gunicorn
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "app:app"]
The main changes are:
- We added
RUN pip install gunicorn
to install the Gunicorn web server.
- We changed the
CMD
instruction to use Gunicorn to start the Flask application. The "gunicorn", "--bind", "0.0.0.0:5000", "app:app"
command tells Gunicorn to bind the application to the 0.0.0.0:5000
address and use the app
object from the app.py
file as the WSGI application.
Building and Running the Production-ready Docker Container
Now, let's build the Docker image and run the container in production mode:
- Build the Docker image:
docker build -t labex-flask-app-prod .
- Run the Docker container:
docker run -p 5000:5000 labex-flask-app-prod
The application should now be running in production mode using Gunicorn.
Verifying the Production Setup
To verify that the Flask application is running in production mode, you can use the following command to check the logs:
docker logs <container_id>
You should see output similar to the following:
[2023-04-11 12:34:56 +0000] [1] [INFO] Starting gunicorn 20.1.0
[2023-04-11 12:34:56 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1)
[2023-04-11 12:34:56 +0000] [1] [INFO] Using worker: sync
[2023-04-11 12:34:56 +0000] [8] [INFO] Booting worker with pid: 8
This confirms that the Flask application is running in production mode using the Gunicorn web server.