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:
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.
Similar Reads
How To Dockerize a ReactJS App?
Dockerizing a React app ensures that your application runs consistently across various environments by containerizing it. By creating a Docker container, you can package your React app, along with its dependencies, to ensure that it runs the same way regardless of the environment. In this article, w
4 min read
How to Dockerize an ExpressJS App ?
Docker is an open-source containerization platform used for building, running, and managing applications in an isolated environment. A container is isolated from another and bundles its software, libraries, and configuration files. This article will discuss how to dockerize an Express app for the de
4 min read
Flask App Routing
App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL ("/") is associated with the root URL. So if our site's
3 min read
How to Dockerize a Golang Application?
Docker is a containerization platform that lets you build, run, and manage applications in an isolated environment. In a container, software, libraries, and configuration files are bundled together and isolated from one another. Golang is an open-source, procedural, and statically typed programming
4 min read
Flask Creating Rest APIs
A REST API (Representational State Transfer API) is a way for applications to communicate over the web using standard HTTP methods. It allows clients (such as web or mobile apps) to interact with a server by sending requests and receiving responses, typically in JSON format.REST APIs follow a statel
4 min read
Features of Docker
Pre-requisite: Docker Docker is one of the most popular open-source sets of platforms for developing and automating the deployment of applications. It deploys applications into containers and enables us to separate our applications from infrastructure. It is designed to provide a lightweight and fas
4 min read
Create a Weather app using Flask | Python
Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide curr
2 min read
FastAPI - Mounting Flask App
A modern framework in Python that is used for building APIs is called FastAPI while a micro web framework written in Python that is used for developing web applications is called Flask. The FastAPI and Flask provide different features. Sometimes, it becomes crucial to use features of both in a singl
2 min read
How to Change Port in Flask app
In this article, we will learn to change the port of a Flask application. The default port for the Flask application is 5000. So we can access our application at the below URL. http://127.0.0.1:5000/ We may want to change the port may be because the default port is already occupied. To do that we ju
1 min read
Dockerizing a Python Flask Application with a Database
Applications are packaged, distributed, and run via Docker within Docker containers throughout the process of "dockerizing". The exact environment and dependencies must be installed in order to run that application on another local machine when it is developed under a specific environment and depend
5 min read