Post

Docker EP - 10: Let's Dockerize a Flask Application

Docker EP - 10: Let's Dockerize a Flask Application

{% raw %}

Let’s develop a simple flask application,

  1. Set up the project directory: Create a new directory for your Flask project.
mkdir flask-docker-appcd flask-docker-app

2. Create a virtual environment (optional but recommended):

python3 -m venv venvsource venv/bin/activate

3. Install Flask

pip install Flask

4. Create a simple Flask app:

In the flask-docker-app directory, create a file named app.py with the following content,

from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world():    return 'Hello, Dockerized Flask!'if __name__ == '__main__':    app.run(host='0.0.0.0', port=5000)

5. Test the Flask app: Run the Flask application to ensure it’s working.

python app.py

Visit http://127.0.0.1:5000/ in your browser. You should see “Hello, Dockerized Flask!”.

Dockerize the Flask Application

  1. Create a Dockerfile: In the flask-docker-app directory, create a file named Dockerfile with the following content:
# Use the official Python image from the Docker HubFROM python:3.9-slim# Set the working directory in the containerWORKDIR /app# Copy the current directory contents into the container at /appCOPY . /app# Install any needed packages specified in requirements.txtRUN pip install --no-cache-dir Flask# Make port 5000 available to the world outside this containerEXPOSE 5000# Define environment variableENV FLASK_APP=app.py# Run app.py when the container launchesCMD ["python", "app.py"]

2. Create a .dockerignore file:

In the flask-docker-app directory, create a file named .dockerignore to ignore unnecessary files during the Docker build process:

venv__pycache__*.pyc*.pyo

3. Build the Docker image:

In the flask-docker-app directory, run the following command to build your Docker image:

docker build -t flask-docker-app .

4. Run the Docker container:

Run the Docker container using the image you just built,

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

5. Access the Flask app in Docker: Visit http://localhost:5000/ in your browser. You should see “Hello, Dockerized Flask!” running in a Docker container.

You have successfully created a simple Flask application and Dockerized it. The Dockerfile allows you to package your app with its dependencies and run it in a consistent environment.

{% endraw %}

This post is licensed under CC BY 4.0 by the author.