Installing Docker on Ubuntu
Docker runs on Linux, Windows, and macOS, but in this example we focus on an Ubuntu server. The following instructions are adapted from the official Docker documentation.Before starting the installation, update your package index to ensure you have the latest information from the repositories.
Step 1: Prerequisites
Update your package index and install the required packages:Step 2: Add the Docker Repository
Add the Docker repository to your system. This command automatically determines your system’s version codename:Step 3: Install Docker Engine
Update the package list again and install the Docker Engine, CLI, containerd, and additional required packages. This process may take a few moments:Verifying the Docker Installation
To confirm that Docker has been installed correctly, check the version:Building a Docker Image for the Flask App
This section walks you through containerizing a Flask application by creating a Dockerfile that outlines the necessary build steps.Dockerfile Explanation
The Dockerfile below uses a slim official Python image and installs the CPU version of PyTorch to minimize the image size. It then installs Python dependencies, copies your Flask app, and sets up a non-root user for enhanced security.requirements.txt file and your Flask app. Then, build your Docker image with the following command:
After optimizing the image by including only CPU dependencies, you may notice a reduction in image size (e.g., from 5.39GB to 1.34GB).
Running the Docker Container
Now that your Docker image is ready, you can run it as a container. The command below maps port 8000 in the container to port 8000 on your local machine:-d flag:
Testing the Flask Application Inside Docker
With your container running, test the Flask endpoint by sending a POST request with an image payload. The following Python script encodes an image in Base64, constructs a JSON payload, and sends it to the/predict endpoint:
Tagging and Pushing the Docker Image to Docker Hub
To share your Docker image, start by tagging it with your Docker Hub username:Conclusion
In this lesson, you learned how to:- Install Docker on an Ubuntu server.
- Build a Docker image using a Dockerfile that packages a Flask application along with CPU-based PyTorch dependencies.
- Run a Docker container and verify its operation by sending a test inference request.
- Tag and push the Docker image to Docker Hub for easy distribution and deployment.