Building a Docker Image for a Python Flask App: A Step-by-Step Guide

Posted by


Docker is a popular containerization tool that allows you to package your application along with all its dependencies into a standardized unit called a Docker image. In this tutorial, we will walk you through the process of building a Docker image for a Python Flask application.

Step 1: Write your Flask application
Before we can build a Docker image for our Python Flask app, we first need to have a Flask application to work with. For the purposes of this tutorial, we will create a simple "Hello World" Flask application. Here’s a basic Flask app that we can work with:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

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

Save this code in a file named app.py in a directory of your choice.

Step 2: Create a Dockerfile
Next, we need to create a Dockerfile. The Dockerfile is a text file that contains instructions for building a Docker image. Here is an example Dockerfile for our Python Flask application:

# Use the official Python image as a base image
FROM python:3.8-slim

# Set the working directory in the container
WORKDIR /app

# Copy the requirements.txt file into the container at /app
COPY requirements.txt .

# Install any dependencies specified in the requirements.txt file
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of the application code into the container at /app
COPY . .

# Expose port 5000 to the outside world
EXPOSE 5000

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

Save this code in a file named Dockerfile in the same directory as your Flask application.

Step 3: Create a requirements.txt file
In order to install the required dependencies for our Flask application, we need to create a requirements.txt file. This file should list all the Python packages that our Flask application depends on. Here’s an example requirements.txt file for our Flask application:

Flask==2.0.2

Save this code in a file named requirements.txt in the same directory as your Flask application.

Step 4: Build the Docker image
Now that we have our Flask application, Dockerfile, and requirements.txt file in place, we can proceed to build the Docker image. Open a terminal window and navigate to the directory where your Flask application, Dockerfile, and requirements.txt file are located.

To build the Docker image, run the following command:

docker build -t flask-app .

This command builds a Docker image with the tag flask-app using the current directory (.) as the build context.

Step 5: Run the Docker container
Once the Docker image has been successfully built, we can run a Docker container based on that image. To do this, run the following command:

docker run -p 5000:5000 flask-app

This command runs a Docker container based on the flask-app image and maps port 5000 from the container to port 5000 on the host machine.

Step 6: Test the Flask application
With the Docker container running, you can now access your Flask application by opening a web browser and navigating to http://localhost:5000. You should see the message "Hello, World!" displayed in the browser, indicating that your Flask application is up and running successfully in the Docker container.

Congratulations! You have successfully built a Docker image for a Python Flask application. Docker provides a convenient and portable way to package and deploy your applications, making it easier to manage dependencies and ensure consistent behavior across different environments.

0 0 votes
Article Rating

Leave a Reply

27 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@poltergeistducs2948
2 hours ago

the container said successfully but the localhost is error

@SAISHWADKAR-w1s
2 hours ago

Hi Hitesh and everyone, this solution is good but what if I want to fetch my code which is in remote repository like gitlab and its a private project. Then how can I pass it to Dockerfile to create an image ? Your help is much appreciated.

@DJenriqez
2 hours ago

For those doing things on the edge of boundary with app.run(), you have to make host="0.0.0.0", otherwise app will be stuck in docker container not allowed on network to go outside.

@TrashallAllsites
2 hours ago

thanks for your share;
i have a question about reload the page after changing the code it's possible instead to hit the reload buttons pages each time ?

@creativekid4534
2 hours ago

after "docker container ls" command at 12:33, its not showing the content of the labels in the terminal, and the app isn't running on the specified port. the docker image and containers are getting formed in the docker desktop app, tho

@baburamchaudhary159
2 hours ago

15:05 While pushing docker image to docker hub, **we need to be logged in to docker desktop**.

@MandarKarekar
2 hours ago

Good Video, Thanks

@mbeecher9921
2 hours ago

My god, I spent half my day bashing my brains against a wall. Turns out I was doing this part right, but I had nginx running on my box that was grabbing all the port 80 traffic and not forwarding it to the docker container. But your video put me on the right track. Thank you for the sanity check.

@akSingh_120
2 hours ago

Thanks buddy

@LaercioDeCosta-is4fy
2 hours ago

Congrats!

@alir8zana635
2 hours ago

thank you so much for your clear explananation
I am looking into learning docker and your video was very helpful
this would be a great start and I will continue watching your videos

@Ankitha_shriram
2 hours ago

After stop what is numeric value u are giving of

@bengraham1798
2 hours ago

I watched your video and followed along but I could not access my container, so I changed my docker run command to "docker container run -d -p 3005:5000 flask_app:latest" and now it works

@clementpickel5014
2 hours ago

Tank you sir

@abdullahsaid8561
2 hours ago

this whole video is going to be different if it weren't for just localhost, but also real domain with apache / nginx

@khalidRaza01
2 hours ago

Hey, will this deploy flask app in container as development server or in production.

@playcodeacm
2 hours ago

This really awesome, Can you create tutorial build docker for flask app and mysql ?

@yasirali8409
2 hours ago

you are very cool sir ❤, and how you taught is always amazed me

@CuddleCoder
2 hours ago

So is this is called Microservice?

@kuppilijagadeeswararao7765
2 hours ago

Good explanations

27
0
Would love your thoughts, please comment.x
()
x