Open In App

Dockerize your Flask App

Last Updated : 03 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Deploying a Flask application manually can lead to dependency issues and inconsistencies across different environments. Docker solves this problem by packaging applications into containers, ensuring they run seamlessly on any system.

In this article, we’ll learn how to Dockerize a Flask app step by step. We will cover:

  • The basics of Docker and why it’s useful.
  • Creating a Docker file for a Flask app.
  • Building and running the Docker container.
  • Best practices for deploying Flask applications using Docker.

What is Docker

Docker is a containerization tool that allows applications to run in isolated environments. It helps developers:

  • Package applications with all dependencies to avoid compatibility issues.
  • Deploy apps consistently across different environments.
  • Reduce overhead compared to traditional virtual machines (VMs).

Key Concepts:

  • Docker Image – A blueprint of an application, containing code, dependencies, and configurations.
  • Docker Container – A running instance of a Docker image.
  • Dockerfile – A script containing instructions to build a Docker image.
  • Docker Hub – A repository for storing and sharing Docker images.

Setting Up a Flask App for Docker

Let’s create a simple Flask API and containerize it using Docker.

File Structure

The file structure of our application should look like this:


docker-fs
File Structure
  • app.py: Contains the Flask application code, defining routes and app behavior. Here, it has a simple route that shows a welcome message.
  • Dockerfile: Specifies instructions for building a Docker image, including the base Python image, required files, dependencies, and the command to run the app.
  • requirements.txt: Lists the Python libraries needed for the app (like Flask) so Docker can install them during the build process.

Step 1: Create a Flask App

Inside the project folder, create app.py:

Python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to Flask with Docker!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

Explanation:

  • host="0.0.0.0" allows external access to the app.
  • port=5000 sets the server port.

Step 2: Create requirements.txt

The requirements.txt file lists all the dependencies required for a Python project. It allows easy installation of all the dependencies that are used in the application.

To create requirements.txt file for our application, use this command:

pip freeze > requirements.txt

To install all the dependencies from the requirements.txt file, use this command:

pip install -r requirements.txt

Step 3: Writing the Dockerfile

A Dockerfile contains instructions to create a Docker image. Create Dockerfile (without an extension) in the project folder and add the following content in it:

# Use an official lightweight Python image
FROM python:3.9-slim

# Set the working directory
WORKDIR /app

# Copy project files into the container
COPY . /app

# Install dependencies
RUN pip install -r requirements.txt

# Expose port 5000 for Flask
EXPOSE 5000

# Command to run the app
CMD ["python", "app.py"]

Explanation of Dockerfile:

  • FROM python:3.9-slim - Uses a lightweight Python image.
  • WORKDIR /app - Sets /app as the working directory inside the container.
  • COPY . /app - Copies project files to the container.
  • RUN pip install -r requirements.txt - Installs dependencies.
  • EXPOSE 5000 - Opens port 5000 for external access.
  • CMD ["python", "app.py"] - Runs the Flask app.

Building and Running the Docker Container

Step 1: Build the Docker Image

Run this command in the terminal:

docker build -t flask-docker-app

  • -t flask-docker-app assigns a tag (name) to the image.
  • . refers to the current directory where the Dockerfile is located.

Step 2: Run the Docker Container

docker run -p 5000:5000 flask-docker-app

  • -p 5000:5000 maps the container’s port 5000 to the local machine.

Step 3: Test the Flask App

Open a browser and visit: http://localhost:5000

4. Test the flask app

Go inside the root folder "flask-docker-demo" if you aren't already in this directory and run the following command "python demo.py" It should start our development server which comes with the flask on "http://0.0.0.0:5001/". see the screenshot below. We should have the following output in the browser

5. Close the server by pressing CTRL + C

Refresh the browser again and it should give an error since the server has been closed.

Creating a Docker Image of a Project and Running

1. Build the Docker Image

Make sure you are in root directory of the project and run the following command.

sudo docker build --tag flask-docker-demo-app .

The above command will create an app with the tag flask-docker-demo-app. Note: Enter the password if required. Refer screenshot below.

2. Run the docker image we just created

Run the following command:

sudo docker run --name flask-docker-demo-app -p 5001:5001 flask-docker-demo-app

In the above command, -name parameter gives name to the container and -p parameter maps the host's(my laptop in this case) port 5001 to the container's port 5001 since the container is isolated and we need to map it in order to access it from external environment. And at last "flask-docker-demo-app" refers to the image to run.

3. Test again

Refresh the browser.

Close the image by running "docker stop" command. To know the container id enter "docker ps" command. It shows all the running containers. Visit Docker's website for more docker commands like "saving the image as tar file" and exporting it in another system.

Best Practices for Managing Docker Containers in Production

When you’re ready to deploy your Flask application with Docker in a production environment, following some best practices can make a significant difference in your app’s performance and security:

  • Choose Official Base Images: Always start with official Docker images whenever possible. These are maintained and regularly updated, providing a solid foundation for your application. For Flask apps, using a lightweight image like python:3.x-slim can help reduce overhead.
  • Optimize Your Dockerfile: A well-written Dockerfile can greatly reduce the size of your images and speed up build times. Consider using multi-stage builds to separate dependencies from the final application. By including only what’s necessary for production, you not only speed up deployments but also enhance security by limiting the potential attack surface.
  • Handle Secrets Safely: Be careful with sensitive information like API keys and database passwords. Instead of hardcoding these directly into your Dockerfiles or source code, use Docker secrets or environment variables. This helps protect your sensitive data and reduces the chance of accidental exposure.
  • Implement Health Checks: Take advantage of Docker's health check feature to keep tabs on your Flask application’s status. This way, if a container becomes unhealthy or unresponsive, Docker can automatically restart it, helping ensure your application stays up and running.
  • Log and Monitor: Set up logging and monitoring for your Docker containers. Tools like the ELK stack (Elasticsearch, Logstash, Kibana) or Prometheus and Grafana can help you collect and visualize logs and performance metrics. Being proactive with monitoring allows you to identify issues before they become critical.
  • Use Orchestration Tools: For more complex deployments, consider using orchestration tools like Kubernetes or Docker Swarm. These tools can manage your containers, providing features like load balancing, scaling, and automated recovery, which simplifies managing your production environment.

By embracing Docker for your Flask applications and following these best practices, you’ll set yourself up for smoother deployments and more reliable performance, ensuring your applications run efficiently in production.

Conclusion

In summary, Docker provides a powerful way to package and deploy your Flask applications, ensuring they run smoothly across various environments. By creating a Docker container, you can manage dependencies effectively and eliminate potential conflicts, making your application more portable and reliable.

This article guided you through converting a simple Flask app into a Docker image, highlighting essential steps and commands. Following best practices—such as using official base images, optimizing your Dockerfile, securing sensitive information, and implementing health checks—will further enhance your app's performance and security in production.


Next Article
Practice Tags :

Similar Reads