How to Build a Python Flask Docker Image on Ubuntu

DockerDockerBeginner
Practice Now

Introduction

This tutorial will guide you through the process of building a Python Flask web application and containerizing it using Docker on an Ubuntu system. You'll learn how to set up the development environment, create a Flask app, and package it into a Docker image for easy deployment and scaling. By the end of this tutorial, you'll have a solid understanding of how to create Docker images for Python Flask applications and deploy them on an Ubuntu server.

Introduction to Docker and Its Benefits

Docker is a powerful containerization platform that has revolutionized the way software is developed, packaged, and deployed. It provides a standardized and consistent environment for running applications, ensuring that they work the same way across different systems and platforms.

What is Docker?

Docker is an open-source software platform that allows developers to build, deploy, and run applications in containers. A container is a lightweight, standalone, and executable package that includes everything needed to run an application, including the code, runtime, system tools, and libraries.

Benefits of Docker

  1. Consistency: Docker ensures that applications run the same way across different environments, from development to production, eliminating the "it works on my machine" problem.
  2. Scalability: Docker containers can be easily scaled up or down, making it simple to handle changes in application demand.
  3. Efficiency: Docker containers are lightweight and use fewer resources than traditional virtual machines, allowing for more efficient use of computing resources.
  4. Portability: Docker containers can be easily moved between different platforms and cloud environments, making it easier to deploy and manage applications.
  5. Isolation: Docker containers provide a high degree of isolation, ensuring that applications are isolated from each other and the underlying system, improving security and reliability.

Docker Architecture

Docker uses a client-server architecture, where the Docker client communicates with the Docker daemon, which is responsible for building, running, and managing Docker containers. The Docker daemon can run on the same machine as the Docker client or on a remote machine.

graph LD subgraph Docker Architecture client(Docker Client) daemon(Docker Daemon) client -- communicates with --> daemon daemon -- builds, runs, and manages --> containers end

By understanding the basics of Docker and its benefits, you'll be well on your way to leveraging this powerful technology to streamline your software development and deployment processes.

Setting up the Development Environment on Ubuntu

To get started with building a Python Flask Docker image on Ubuntu, you'll need to set up your development environment. In this section, we'll guide you through the necessary steps.

Installing Docker on Ubuntu

  1. Update the package index:
sudo apt-get update
  1. Install the necessary packages to allow apt to use a repository over HTTPS:
sudo apt-get install \
    ca-certificates \
    curl \
    gnupg \
    lsb-release
  1. Add the official Docker GPG key:
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  1. Set up the Docker repository:
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
  1. Install Docker Engine:
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin

Installing Python and Flask

  1. Install Python 3 and pip:
sudo apt-get install python3 python3-pip
  1. Install the Flask web framework:
pip3 install flask

Now that you have Docker and the necessary Python components installed, you're ready to start building your Flask application and containerizing it using Docker.

Building a Python Flask Web Application

In this section, we'll create a simple Python Flask web application that we'll later containerize using Docker.

Creating the Flask Application

  1. Create a new directory for your project:
mkdir flask-app
cd flask-app
  1. Create a new Python file, app.py, and add the following code:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, LabEx!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

This code creates a simple Flask application that listens on the root URL (/) and returns the message "Hello, LabEx!".

Running the Flask Application

  1. Ensure you have Python 3 and Flask installed:
python3 --version
pip3 list | grep flask
  1. Run the Flask application:
python3 app.py

You should see the following output:

 * Serving Flask app 'app' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://172.17.0.2:5000 (Press CTRL+C to quit)
  1. Open a web browser and navigate to http://localhost:5000. You should see the "Hello, LabEx!" message.

Congratulations! You've successfully created a simple Python Flask web application. In the next section, we'll containerize this application using Docker.

Containerizing the Flask Application using Docker

Now that you have a working Flask application, it's time to containerize it using Docker. This will allow you to package your application, along with its dependencies, into a single, portable image that can be easily deployed and run in different environments.

Creating a Dockerfile

  1. In the flask-app directory, create a new file called Dockerfile and add the following content:
FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python3", "app.py"]

This Dockerfile does the following:

  • Starts from the python:3.9-slim base image, which provides a lightweight Python 3.9 environment.
  • Sets the working directory to /app.
  • Copies the requirements.txt file and installs the required Python dependencies.
  • Copies the entire application code (including app.py) into the container.
  • Specifies the command to run the Flask application when the container starts.

Building the Docker Image

  1. Build the Docker image using the following command:
docker build -t flask-app .

This command builds the Docker image with the tag flask-app using the Dockerfile in the current directory.

Running the Docker Container

  1. Run the Docker container:
docker run -p 5000:5000 flask-app

This command starts the flask-app container and maps the container's port 5000 to the host's port 5000.

  1. Open a web browser and navigate to http://localhost:5000. You should see the "Hello, LabEx!" message, just as before when you ran the Flask application directly.

By containerizing your Flask application using Docker, you've created a portable, consistent, and reproducible environment that can be easily deployed and run on different systems.

Deploying the Docker Image on Ubuntu Server

Now that you have a Docker image containing your Flask application, you can deploy it to an Ubuntu server. In this section, we'll guide you through the process of deploying the Docker image on an Ubuntu server.

Preparing the Ubuntu Server

  1. Ensure that the Ubuntu server has Docker installed. You can follow the steps in the "Setting up the Development Environment on Ubuntu" section to install Docker on the server.
  2. Optionally, you can also install Docker Compose, which will make it easier to manage and scale your Docker containers.

Deploying the Docker Image

  1. Transfer the Docker image to the Ubuntu server. You can do this by either:
    • Pushing the image to a Docker registry (e.g., Docker Hub, AWS ECR, or a private registry) and pulling it on the server.
    • Saving the image as a tarball on your local machine and copying it to the server, then loading the image on the server.
  2. Once the image is available on the server, you can run the container using the following command:
docker run -d -p 80:5000 flask-app

This command:

  • Runs the container in detached mode (-d).
  • Maps the container's port 5000 to the host's port 80 (-p 80:5000).
  • Uses the flask-app image to start the container.

Verifying the Deployment

  1. Open a web browser and navigate to the server's IP address or domain name (e.g., http://your-server-ip). You should see the "Hello, LabEx!" message, indicating that the Flask application is running inside the Docker container.

Scaling the Application

If you need to scale your application, you can use Docker Compose to manage multiple containers. Create a docker-compose.yml file in the same directory as your Dockerfile, with the following content:

version: "3"
services:
  web:
    build: .
    ports:
      - 80:5000
    deploy:
      replicas: 3

This Docker Compose file will create three replicas of the Flask application, and automatically load-balance the traffic across them.

To deploy the application using Docker Compose, run the following command:

docker-compose up -d

This will start the application with three replicas, and you can scale the number of replicas up or down as needed.

By deploying your Docker image on an Ubuntu server, you can easily scale and manage your Flask application in a consistent and reliable environment.

Managing and Maintaining the Docker Container

Once your Flask application is deployed as a Docker container, you'll need to manage and maintain it to ensure its smooth operation. In this section, we'll cover some common tasks and best practices for managing and maintaining your Docker container.

Monitoring the Container

  1. Check the status of the running container:
docker ps

This command will show you all the running containers, including the one running your Flask application.

  1. View the logs of the container:
docker logs <container_id>

This will display the logs of the running container, which can be helpful for troubleshooting and monitoring.

Updating the Application

  1. Make changes to your Flask application code.
  2. Rebuild the Docker image with the updated code:
docker build -t flask-app .
  1. Stop the running container:
docker stop <container_id>
  1. Run the updated container:
docker run -d -p 80:5000 flask-app

This will replace the old container with the updated one, ensuring that your application is running the latest version.

Scaling the Application

If you need to handle increased traffic or load, you can scale your application by running multiple instances of the Docker container. You can use tools like Docker Compose or Kubernetes to manage the scaling and load balancing of your containers.

Backing up and Restoring the Container

  1. To back up the container, you can save it as an image:
docker commit <container_id> flask-app:backup
docker push flask-app:backup

This will create a new image tag flask-app:backup and push it to a Docker registry.

  1. To restore the container from the backup image, you can run:
docker pull flask-app:backup
docker run -d -p 80:5000 flask-app:backup

This will pull the backup image and start a new container from it.

Updating the Base Image

If a security vulnerability is found in the base image you're using (e.g., python:3.9-slim), you'll need to update your Dockerfile to use a newer, patched base image. This will ensure that your application is running on a secure and up-to-date environment.

By following these best practices for managing and maintaining your Docker container, you can ensure that your Flask application remains reliable, secure, and scalable over time.

Summary

In this tutorial, you have learned how to create a Docker image for a Python Flask web application and deploy it on an Ubuntu server. You've explored the benefits of containerization, set up the development environment, built a Flask app, and packaged it into a Docker image. You've also learned how to manage and maintain the Docker container. With these skills, you can now confidently containerize and deploy your Python Flask applications on Ubuntu, taking advantage of the scalability and portability offered by Docker.

Other Docker Tutorials you may like