Docker

Dockerizing the FastAPI Application in VSCode

Introduction to Docker

Docker is a containerization platform that allows you to package an application and its dependencies into a standardized unit called a container. Containers are lightweight, portable, and isolated, making it easy to develop, package, and deploy applications consistently across different environments. Docker has become a fundamental technology in modern software development and operations.

Key Concepts in Docker:



Benefits of Docker in a Kubernetes Context

Kubernetes, as a container orchestration platform, leverages Docker containers to manage and automate the deployment, scaling, and management of containerized applications. Here are the key benefits of Docker in a Kubernetes context:

In summary, Docker is a containerization platform that provides consistency, portability, and isolation for applications. When used with Kubernetes, Docker containers become the building blocks for scalable, efficient, and manageable containerized applications in modern DevOps and cloud-native environments.


Writing a Dockerfile for the FastAPI application.

Create a file named "Dockerfile" in the root of the project with the following:

Dockerfile:

# Use an official Python runtime as a parent image

FROM python:3.9-slim


# Set the working directory to /app

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 -r requirements.txt


# Make port 80 available to the world outside this container

EXPOSE 80


# Define environment variable

ENV NAME World


# Run app.py when the container launches

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]


Here's a brief explanation of each section of the Dockerfile:


Building and testing the Docker image.

To build a Docker image using this Dockerfile, open your terminal in VS Code, navigate to the directory containing the Dockerfile and your FastAPI application code, and run:

docker build -t dev-ops-hello-worldapp .

This command will build a Docker image with the tag "dev-ops-hello-worldapp." You can replace "dev-ops-hello-worldapp" with a different tag name if you prefer.

To run the image after you have built it: 

docker run -p 80:80 dev-ops-hello-worldapp

This will run the image and map the port 80 from the local host to port 80 in the container. 

To check the running application: 

docker ps

This will give you the list of running containers.  

To access the the image open a browser to http://localhost

you should get the message "{"message":"Hello, World!"}"