How to run Flask app in production mode in Docker?

DockerDockerBeginner
Practice Now

Introduction

Docker has become a popular choice for deploying web applications, including Flask-based applications. In this tutorial, we will guide you through the process of Dockerizing a Flask application and running it in production mode using Docker. By the end of this article, you will have a solid understanding of how to leverage Docker to deploy your Flask app in a production environment.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/ContainerOperationsGroup(["`Container Operations`"]) docker(("`Docker`")) -.-> docker/ImageOperationsGroup(["`Image Operations`"]) docker(("`Docker`")) -.-> docker/DockerfileGroup(["`Dockerfile`"]) docker/ContainerOperationsGroup -.-> docker/create("`Create Container`") docker/ContainerOperationsGroup -.-> docker/ps("`List Running Containers`") docker/ContainerOperationsGroup -.-> docker/run("`Run a Container`") docker/ContainerOperationsGroup -.-> docker/start("`Start Container`") docker/ContainerOperationsGroup -.-> docker/stop("`Stop Container`") docker/ImageOperationsGroup -.-> docker/pull("`Pull Image from Repository`") docker/DockerfileGroup -.-> docker/build("`Build Image from Dockerfile`") docker/ContainerOperationsGroup -.-> docker/ls("`List Containers`") subgraph Lab Skills docker/create -.-> lab-415824{{"`How to run Flask app in production mode in Docker?`"}} docker/ps -.-> lab-415824{{"`How to run Flask app in production mode in Docker?`"}} docker/run -.-> lab-415824{{"`How to run Flask app in production mode in Docker?`"}} docker/start -.-> lab-415824{{"`How to run Flask app in production mode in Docker?`"}} docker/stop -.-> lab-415824{{"`How to run Flask app in production mode in Docker?`"}} docker/pull -.-> lab-415824{{"`How to run Flask app in production mode in Docker?`"}} docker/build -.-> lab-415824{{"`How to run Flask app in production mode in Docker?`"}} docker/ls -.-> lab-415824{{"`How to run Flask app in production mode in Docker?`"}} end

Understanding Docker

Docker is a popular open-source platform that allows developers to build, deploy, and run applications in a containerized environment. It provides a way to package an application and all its dependencies into a single container, making it easy to move the application between different computing environments.

What is Docker?

Docker is a software platform that enables developers to build, deploy, and run applications in containers. A container is a lightweight, standalone, and executable package that includes everything needed to run an application, including the code, runtime, system tools, and libraries. Containers are isolated from each other and from the host operating system, ensuring consistent and reliable application deployment.

Benefits of Docker

  1. Portability: Docker containers can run consistently across different computing environments, from a developer's laptop to a production server, ensuring that the application will behave the same way regardless of the underlying infrastructure.
  2. Scalability: Docker makes it easy to scale applications up or down, depending on the demand, by adding or removing containers as needed.
  3. Efficiency: Docker containers are lightweight and use fewer resources than traditional virtual machines, allowing for more efficient use of computing resources.
  4. Consistency: Docker ensures that the application and its dependencies are packaged together, eliminating the "it works on my machine" problem and ensuring consistent behavior across different environments.

Docker Architecture

The Docker architecture consists of the following key components:

graph TD A[Docker Client] --> B[Docker Daemon] B --> C[Docker Images] B --> D[Docker Containers] B --> E[Docker Networking] B --> F[Docker Storage]
  1. Docker Client: The Docker client is the primary user interface for interacting with Docker. It allows users to issue commands to the Docker daemon, such as building, running, and managing containers.
  2. Docker Daemon: The Docker daemon is the backend service that manages the creation, modification, and removal of Docker objects, such as images, containers, networks, and volumes.
  3. Docker Images: Docker images are the blueprints for creating Docker containers. They contain the application code, libraries, dependencies, and any other files needed to run the application.
  4. Docker Containers: Docker containers are the running instances of Docker images. They are isolated, lightweight, and portable environments that run the application.
  5. Docker Networking: Docker provides built-in networking capabilities that allow containers to communicate with each other and the outside world.
  6. Docker Storage: Docker provides various storage options, including volumes and bind mounts, to manage the persistent data associated with a container.

Understanding the Docker architecture and its key components is crucial for effectively using and managing Docker in your application development and deployment processes.

Dockerizing a Flask Application

In this section, we will learn how to containerize a Flask application using Docker.

Creating a Flask Application

Let's start by creating a simple Flask application. Create a new directory and navigate to it in your terminal. Then, create a new file called app.py with the following content:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, LabEx!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

This Flask application has a single route that returns the message "Hello, LabEx!".

Dockerizing the Flask Application

To containerize the Flask application, we need to create a Dockerfile. Create a new file called Dockerfile with the following content:

FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python", "app.py"]

Let's break down the Dockerfile:

  1. FROM python:3.9-slim: This specifies the base image for the Docker container, which in this case is the slim version of the Python 3.9 image.
  2. WORKDIR /app: This sets the working directory inside the container to /app.
  3. COPY requirements.txt .: This copies the requirements.txt file into the container's working directory.
  4. RUN pip install --no-cache-dir -r requirements.txt: This installs the Python dependencies specified in the requirements.txt file.
  5. COPY . .: This copies the entire application code (including app.py) into the container's working directory.
  6. CMD ["python", "app.py"]: This specifies the command to run when the container starts, which is to execute the app.py script using the Python interpreter.

Building and Running the Docker Container

Now, let's build the Docker image and run the container:

  1. Build the Docker image:
    docker build -t labex-flask-app .
  2. Run the Docker container:
    docker run -p 5000:5000 labex-flask-app

The -p 5000:5000 option maps the host's port 5000 to the container's port 5000, allowing you to access the Flask application from your local machine.

After running the container, you can access the Flask application by opening a web browser and navigating to http://localhost:5000. You should see the message "Hello, LabEx!" displayed.

Congratulations! You have successfully containerized a Flask application using Docker.

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:

  1. We added RUN pip install gunicorn to install the Gunicorn web server.
  2. 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:

  1. Build the Docker image:
    docker build -t labex-flask-app-prod .
  2. 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.

Summary

This tutorial has covered the essential steps to run a Flask application in production mode using Docker. We've explored the process of Dockerizing a Flask app, including creating a Dockerfile and building the Docker image. Additionally, we've discussed how to run the Flask app in production mode within the Docker container, ensuring a reliable and scalable deployment. By following the practices outlined in this guide, you can effectively leverage Docker to deploy your Flask-based web applications in a production environment.

Other Docker Tutorials you may like