Docker

What is Docker?

Docker is a platform that allows developers to automate the deployment of applications inside lightweight, portable containers. These containers include everything needed to run an application, including the code, runtime, libraries, and system tools. By using Docker, you can ensure that your application behaves the same, regardless of where it is deployed.

What is a Docker Image?

A Docker image is a lightweight, standalone, executable package that includes everything needed to run a piece of software. It contains the application code, runtime, libraries, environment variables, and configuration files. Images are built from a Dockerfile and can be stored in Docker Hub or other container registries.

What is a Dockerfile?

A Dockerfile is a script composed of various instructions (commands) that are executed sequentially to build a Docker image. It defines what goes into your Docker image, such as the base image to use, environment variables, files to include, and commands to run.

Creating the Docker Image

Prerequisites

Dockerfile

Here’s the Dockerfile we’ll use to build the Docker image for our FastAPI application:

# Use the official Python image from the Docker Hub
FROM python:3.10-slim

# Set the working directory in the container
WORKDIR /app

# Copy only the requirements file to leverage Docker cache
COPY requirements.txt .

# Install the dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of the application code to the working directory
COPY . .

# Expose port 8000
EXPOSE 8000

# Use a minimal entrypoint and CMD
ENTRYPOINT ["python"]
CMD ["main.py"]

Dockerfile Explanation

Building and Running the Docker Image

Building the Docker Image:

Once the image is built, you can run the container using:

docker run -p 8000:8000 fastapi-app

This command runs the container, mapping port 8000 of the container to port 8000 on your host machine. You can now access the FastAPI application at

http://localhost:8000

Note: This is only for illustration purposes. We are going to use Kubernetes to run the Docker container.

← Previous Next →