0Pricing
FastAPI Backend Development Bootcamp · 课时

将 FastAPI 应用容器化

学习使用 Docker 将 FastAPI 服务容器化,创建高效且便于移植的部署镜像。

将 FastAPI 应用容器化 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Docker & FastAPI: Why Containerize?

Welcome! In this lesson, we'll learn how to package your FastAPI application using Docker. This makes your app incredibly consistent and easy to deploy anywhere.

  • What is Docker? It's a platform that uses OS-level virtualization to deliver software in packages called containers.
  • Why use it for FastAPI? It solves the "it works on my machine" problem by packaging your app and its dependencies together.

Docker's Core: Images & Containers

Before we dive into Dockerizing, let's understand two key concepts:

  • Docker Image: Think of an image as a blueprint or a template. It's a static, immutable file that contains your application code, libraries, dependencies, and configuration.
  • Docker Container: A container is a runnable instance of an image. It's an isolated environment where your application runs, completely separate from your host system.

You build an image, then run a container from it.

A Basic FastAPI Service

Let's start with a simple FastAPI application that we'll containerize. This file will be named main.py.

It has a single endpoint that returns a 'Hello' message.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello from FastAPI!"}

# To run locally (without Docker):
# uvicorn main:app --host 0.0.0.0 --port 8000

The Dockerfile: Starting Strong

A Dockerfile is a text file that contains all the commands a user could call on the command line to assemble an image. It's your recipe for building the image.

We start by picking a base image and setting our working directory:

  • FROM: Specifies the base image (e.g., Python version).
  • WORKDIR: Sets the current working directory inside the container.
# Dockerfile
FROM python:3.9-slim-buster
WORKDIR /app

FastAPI Dependencies: requirements.txt

Your FastAPI app needs specific Python packages to run. We list these in a requirements.txt file. This file tells Docker which packages to install inside the container.

Here's a typical requirements.txt for our simple FastAPI app:

# requirements.txt
fastapi==0.104.1
uvicorn[standard]==0.24.0.post1

Dockerfile: Installing Dependencies

Now, let's add commands to our Dockerfile to copy and install these dependencies:

  • COPY requirements.txt .: Copies the requirements.txt from your local machine to the container's /app directory.
  • RUN pip install ...: Executes the command to install all packages listed in requirements.txt. --no-cache-dir helps keep the image size small.
# Dockerfile (continued)
FROM python:3.9-slim-buster
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

Dockerfile: App Code & Entrypoint

Finally, we add our application code and tell Docker how to run it:

  • COPY . .: Copies all remaining files from your current directory (including main.py) into the container's /app directory.
  • EXPOSE 8000: Informs Docker that the container listens on port 8000. It's documentation, not a firewall rule.
  • CMD [...]: Specifies the command to run when the container starts. This is how Uvicorn will serve your FastAPI app.
# Dockerfile (final)
FROM python:3.9-slim-buster
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Building Your Docker Image

With your Dockerfile and FastAPI app ready, it's time to build the Docker image!

Open your terminal in the same directory as your Dockerfile and main.py, then run:

  • docker build .: Tells Docker to build an image using the Dockerfile in the current directory.
  • -t myfastapi-app: Tags the image with a name (myfastapi-app) for easy reference.
# Terminal Command
docker build -t myfastapi-app .

Running Your FastAPI Container

Once the image is built, you can run your FastAPI application in a container!

Use the docker run command:

  • -p 8000:8000: This maps port 8000 on your host machine to port 8000 inside the container.
  • myfastapi-app: The name of the image we just built.

After running, open your browser or use curl to visit http://localhost:8000.

# Terminal Command
docker run -p 8000:8000 myfastapi-app

Introducing Docker Compose

For applications with multiple services (like a FastAPI app and a database), Docker Compose simplifies management. It lets you define and run multi-container Docker applications using a YAML file.

Instead of running multiple docker run commands, you define everything in docker-compose.yml and use docker-compose up.

# docker-compose.yml (simplified)
version: '3.8'
services:
  web:
    build: .
    ports:
      - "8000:8000"

Dockerfile Command Check

Which Dockerfile command is used to copy files or directories from your local machine into the Docker image?

Recap: FastAPI in a Box!

Great job! You've learned the fundamentals of Dockerizing your FastAPI application. We covered:

  • The difference between Docker Images and Containers.
  • Writing a Dockerfile with commands like FROM, WORKDIR, COPY, RUN, EXPOSE, and CMD.
  • Building and running your FastAPI app in a Docker container.
  • A brief introduction to Docker Compose for multi-service apps.

This skill is crucial for consistent and scalable deployments!

常见问题解答

「将 FastAPI 应用容器化」课时是免费的吗?

是的 — 「将 FastAPI 应用容器化」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「将 FastAPI 应用容器化」这节课中我会学到什么?

学习使用 Docker 将 FastAPI 服务容器化,创建高效且便于移植的部署镜像。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「将 FastAPI 应用容器化」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 将 FastAPI 应用容器化
  2. 使用 Gunicorn 与 Uvicorn 部署
  3. 云部署策略
  4. 管理环境变量与密钥
← 返回 FastAPI Backend Development Bootcamp