Creating a Docker image and running a container based on the image is a great way to streamline your development process and ensure consistency in your deployment environment. In this guide, we’ll walk you through building a custom Docker image and running a container for an existing Python Flask website in VSCode in 5 steps.
If you have been following along with my Docker series, you should have already installed Docker Desktop and VSCode. You should also have created a simple Python and Flask website and added your HTML, CSS, and JavaScript files. You can access my code for this project on GitHub.
Creating a Dockerfile for your Flask application
First, we need to create a Dockerfile for our existing Flask application. In the same directory as your Flask application, create a new file named Dockerfile
and paste the following code:
# Use an official Python runtime as the base image
FROM python:3.12.0a5-bullseye
# Set the working directory in the container to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install the required packages
RUN pip install --no-cache-dir -r requirements.txt
# Set the environment variable for Flask
ENV FLASK_APP=app.py
# Run the command to start the Flask application
CMD ["flask", "run", "--host=0.0.0.0"]
This is a Dockerfile for building a custom Docker image for a Python Flask application. Each line of code performs a specific action as follows:
- FROM python3.12.0a5-bullseye: Specifies the official Python image as the base image for our Docker image.
- WORKDIR /app: Sets the working directory inside the container to /app.
- COPY . /app: Copies the contents of the current directory into the container at the /app directory.
- RUN pip install –no-cache-dir -r requirements.txt: Runs the pip install command to install the required Python packages defined in the requirements.txt file. The –no-cache-dir flag tells pip not to store the downloaded packages in the cache directory.
- ENV FLASK_APP=app.py: Sets the FLASK_APP environment variable to app.py, which is the name of the Flask application.
- CMD [“flask”, “run”, “–host=0.0.0.0”]: Specifies the command to run when the container starts, which is to start the Flask application using the flask run command and listen on all network interfaces by specifying the –host=0.0.0.0 option.
Creating a requirements.txt file
Next, we need to create a requirements.txt
file that lists the Python packages that our Flask application depends on. In this case, we only need the Flask package, so create a new file named requirements.txt
in the same directory as your Flask application and paste the following code:
Flask==2.2.2
Specifying Ports in a Flask Application
Next, we need to update our app.py file to specify the ports we will use when we run the docker container:
from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(debug=True, host='0.0.0.0', port=port)
These lines of code are used to start the Flask application in a local development environment or on a server. First, we need to import the OS module which is a part of the standard Python library. It lets the user interact with the native OS Python is currently running on.
if __name__ == '__main__':
, a conditional statement that ensures the application is only run if the script is executed directly by the Python interpreter, rather than being imported as a module into another script.port = int(os.environ.get('PORT', 5000))
: retrieves the port number on which the application should listen from thePORT
environment variable. Theint()
function is used to convert the string value ofPORT
to an integer, and if thePORT
variable is not set, the default value of 5000 is used.app.run(debug=True, host='0.0.0.0', port=port)
: starts the Flask application. Thedebug
parameter is set toTrue
to enable debug mode, which provides detailed error messages during development. Thehost
parameter is set to'0.0.0.0'
, which means the application will listen on all network interfaces. Finally, theport
parameter is set to the value retrieved from thePORT
environment variable or the default value of 5000, allowing the application to listen on the specified port.
Overall, these lines of code enable you to start a Flask application on your local machine or a server by running the script directly, and specifying the port on which the application should listen by setting the PORT
environment variable.
Building the Custom Docker Image
With your Dockerfile, requirements.txt, and app.py files in place, you’re ready to build your Docker image. To do this, open up a terminal or command prompt, navigate to the directory that contains your Flask application and Dockerfile, and run the following command:
docker build -t my_flask_image .
This command tells Docker to build an image, using the current directory and name it my_flask_image.
Running the Docker Container
And finally, we can run the Docker container using the docker run command:
docker run -d -p 5000:5000 my_flask_image
In this example, the -d flag means the container will run in detached mode. The -p option maps maps the host machine’s port 5000 to the container’s port 5000. This allows the Flask application running inside the container to be accessed from the host machine’s web browser at http://localhost:5000. These arguments are followed by the name of the container.
Once your container is running, you can navigate to http://localhost:5000 and you should see your website!
By following these steps, you can build a custom a Docker image for your Python Flask application and run a container in a consistent environment, allowing you to easily deploy your application to any system that supports Docker.
Docker Image vs. Container – Online Course
If you’re struggling with Docker errors, check out my Pluralsight course, Tactics and Tools for Troubleshooting Docker. This course provides developers with the skills they need to troubleshoot and fix the most common Docker errors. By the end of this course, you will have the skills you need to reduce the time it takes you to assess and fix issues. Click the link below to get started with a free trial today!