Deploy Flask Apps with Docker on Ubuntu 20.04: A Step-by-Step Guide


6 min read 14-11-2024
Deploy Flask Apps with Docker on Ubuntu 20.04: A Step-by-Step Guide

Flask has emerged as one of the most popular web frameworks for building lightweight and efficient web applications in Python. Coupled with Docker, it becomes easy to package applications and their dependencies into isolated containers. This enhances portability and scalability, allowing developers to run their Flask applications seamlessly across different environments. In this detailed guide, we will walk you through the process of deploying Flask applications with Docker on Ubuntu 20.04. Let’s dive in!

Understanding Flask and Docker

Before we get into the nitty-gritty of deploying Flask apps with Docker, let’s take a moment to discuss what Flask and Docker are and why they are essential tools in modern web development.

Flask is a micro web framework written in Python. Its simplicity and flexibility make it an excellent choice for developing small to medium-sized web applications and RESTful APIs. Flask provides essential tools and libraries without imposing project layout or dependencies, giving developers the freedom to structure their applications as they see fit.

Docker, on the other hand, is a platform that automates the deployment of applications within lightweight, portable containers. It allows developers to package applications with all their dependencies, ensuring that they run consistently on any system that supports Docker, irrespective of the underlying architecture or software environment.

By combining Flask with Docker, developers can easily create an application that is not only robust and efficient but also easily deployable and scalable.

Setting Up Your Environment

Step 1: Installing Ubuntu 20.04

First and foremost, you will need a running instance of Ubuntu 20.04. This could be a virtual machine, a cloud instance (like AWS or DigitalOcean), or even your personal laptop.

  • To install Ubuntu, download the ISO from the official Ubuntu website.
  • Follow the installation instructions, and you will have a fresh system ready for development.

Step 2: Installing Docker on Ubuntu

To use Docker, you first need to install it on your Ubuntu system. Here’s how you can do it:

  1. Update the System: Always start by updating your package repository.

    sudo apt update
    sudo apt upgrade -y
    
  2. Install Required Packages: Docker requires a few prerequisites to be installed. Use the command below to install them.

    sudo apt install apt-transport-https ca-certificates curl software-properties-common -y
    
  3. Add Docker’s Official GPG Key: This ensures the integrity of your installations.

    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
    
  4. Add Docker Repository: Add the Docker repository to your package sources.

    sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
    
  5. Install Docker: Now you can install Docker using the following command.

    sudo apt update
    sudo apt install docker-ce -y
    
  6. Check Docker Status: Confirm that Docker is running properly.

    sudo systemctl status docker
    
  7. Run Docker Without Sudo: (Optional) To avoid typing sudo every time you run a Docker command, add your user to the Docker group.

    sudo usermod -aG docker $USER
    

    Log out and log back in for this change to take effect.

Step 3: Installing Docker Compose

Docker Compose is a tool for defining and running multi-container Docker applications.

  1. Install Docker Compose:

    sudo apt install docker-compose -y
    
  2. Verify Installation: Check if Docker Compose has been installed correctly.

    docker-compose --version
    

Creating a Flask Application

Now that we have Docker set up, it’s time to create a simple Flask application.

Step 4: Set Up Your Flask Application

  1. Create a Project Directory:

    mkdir flask-docker-app
    cd flask-docker-app
    
  2. Create a Virtual Environment: Although Docker can manage dependencies, creating a virtual environment can help during development.

    python3 -m venv venv
    source venv/bin/activate
    
  3. Install Flask:

    pip install Flask
    
  4. Create a Simple Flask App: Create a file named app.py in the project directory and add the following code:

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        return "Hello, Docker with Flask!"
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)
    
  5. Test Your Flask Application: Run the application locally to ensure it works.

    python app.py
    

    Navigate to http://localhost:5000 in your web browser; you should see "Hello, Docker with Flask!".

Dockerizing Your Flask Application

Step 5: Creating the Dockerfile

Now, let’s dockerize our Flask application. The Dockerfile will contain all the commands to assemble the Docker image.

  1. Create a Dockerfile: In your project directory, create a file named Dockerfile (no file extension) and add the following content:

    # Use the official Python image from the Docker Hub
    FROM python:3.8-slim
    
    # Set the working directory in the container
    WORKDIR /app
    
    # Copy the current directory contents into the container at /app
    COPY . /app
    
    # Install any needed packages specified in requirements.txt
    RUN pip install --no-cache-dir Flask
    
    # Make port 5000 available to the world outside this container
    EXPOSE 5000
    
    # Define environment variable
    ENV NAME World
    
    # Run app.py when the container launches
    CMD ["python", "app.py"]
    

Step 6: Creating a Requirements File

For best practices, it is recommended to specify your dependencies in a requirements.txt file.

  1. Create the requirements.txt File: Add Flask to this file.

    echo "Flask" > requirements.txt
    

Step 7: Building the Docker Image

Now that we have our Dockerfile ready, let’s build our Docker image.

  1. Build the Docker Image:

    docker build -t flask-docker-app .
    

    Here, flask-docker-app is the name we are giving to our Docker image.

Step 8: Running the Docker Container

Now we will run our Docker container based on the image we just created.

  1. Run the Container:

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

    This command tells Docker to map port 5000 on the host to port 5000 on the container, allowing you to access the Flask application.

Step 9: Access Your Application

Open a web browser and navigate to http://localhost:5000. You should see "Hello, Docker with Flask!" displayed.

Using Docker Compose for Flask Applications

While using Docker directly works great for small applications, Docker Compose becomes handy for more complex applications, particularly when multiple services need to communicate with each other.

Step 10: Creating docker-compose.yml

In your project directory, create a file named docker-compose.yml. Here’s how to define your services:

version: '3.8'
services:
  flask:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/app
    environment:
      - NAME=World

Step 11: Running Docker Compose

You can now use Docker Compose to build and run your application.

  1. Start the Application:

    docker-compose up
    
  2. Access Your Application: Navigate to http://localhost:5000, and you should still see "Hello, Docker with Flask!" displayed.

Step 12: Stopping the Application

To stop the application, press CTRL+C or use:

docker-compose down

Best Practices for Deploying Flask Apps with Docker

Once your Flask application is ready for deployment, keep in mind several best practices to follow:

  1. Multi-Stage Builds: Use multi-stage builds in your Dockerfile to reduce the final image size by separating the build environment from the runtime environment.

  2. Use .dockerignore: Similar to .gitignore, use .dockerignore to prevent unnecessary files from being added to your Docker image.

  3. Health Checks: Implement health checks in your Docker Compose file to monitor the health of your containerized application.

  4. Configuration Management: Use environment variables for configuration management rather than hardcoding values in your code.

  5. Continuous Integration/Continuous Deployment (CI/CD): Integrate Docker with CI/CD pipelines for automated testing and deployment.

Conclusion

Deploying Flask applications with Docker on Ubuntu 20.04 is not only straightforward but also leverages the full potential of containerization. With Docker, you can ensure that your applications run consistently regardless of where they are deployed. We walked through setting up our environment, creating a simple Flask application, dockerizing it, and managing it using Docker Compose.

By mastering these tools and techniques, you are now well-equipped to develop, deploy, and scale Flask applications with ease. Happy coding!

FAQs

Q1: What is Docker? Docker is an open-source platform that enables developers to automate the deployment of applications within lightweight, portable containers, ensuring consistency across different environments.

Q2: Why should I use Docker with Flask? Using Docker with Flask allows you to encapsulate your application and its dependencies, ensuring it runs uniformly across various environments, simplifying the deployment process.

Q3: What is Docker Compose? Docker Compose is a tool that allows you to define and run multi-container Docker applications. It uses a YAML file to configure your application’s services, networks, and volumes.

Q4: Can I run a Flask application in production using Docker? Yes, Docker is widely used in production environments for running applications, as it provides isolation and consistency, reducing the chances of deployment errors.

Q5: How can I deploy my Flask app to a cloud platform using Docker? You can deploy your Flask app to cloud platforms like AWS, Google Cloud, or Azure by pushing your Docker image to their respective container registries and using their services to run your Docker container.