Docker 101: Microservices Architecture with Docker Networking

Microservices Architecture with Docker Networking (微服务架构与 Docker 网络)

Introduction / 介绍

Microservices architecture involves breaking down an application into smaller, independent services that can be developed, deployed, and scaled independently. Each service typically runs in its own container and communicates with other services over a network. Docker networking allows these services to communicate with each other seamlessly, even though they are isolated in their own containers.

微服务架构涉及将应用程序分解为较小的、独立的服务,这些服务可以独立开发、部署和扩展。每个服务通常在自己的容器中运行,并通过网络与其他服务通信。Docker 网络允许这些服务无缝通信,即使它们被隔离在各自的容器中。

Step 1: Set Up the Authentication Service / 步骤1: 设置身份验证服务

  1. Create the Authentication Service
    The authentication service handles user login and token management.

    创建身份验证服务
    身份验证服务处理用户登录和令牌管理。

    mkdir auth_service
    cd auth_service

    Create the main.py for the authentication service:

    为身份验证服务创建 main.py

    # main.py
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.post("/login")
    def login(user: str, password: str):
       # Dummy authentication logic
       if user == "admin" and password == "secret":
           return {"token": "fake-token"}
       return {"error": "Invalid credentials"}

    Create the Dockerfile:

    创建 Dockerfile

    # Dockerfile
    FROM python:3.9-slim
    
    WORKDIR /app
    
    COPY . .
    
    RUN pip install fastapi uvicorn
    
    CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]
  2. Build and Run the Authentication Service
    Build and run the authentication service in a Docker container.

    构建并运行身份验证服务
    在 Docker 容器中构建并运行身份验证服务。

    docker build -t auth_service .
    docker run -d --name auth_service -p 8001:8001 auth_service

Step 2: Set Up the User Service / 步骤2: 设置用户服务

  1. Create the User Service
    The user service manages user data and profiles.

    创建用户服务
    用户服务管理用户数据和配置文件。

    mkdir user_service
    cd user_service

    Create the main.py for the user service:

    为用户服务创建 main.py

    # main.py
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/user/{user_id}")
    def get_user(user_id: int):
       # Dummy user data
       return {"user_id": user_id, "name": "John Doe", "role": "admin"}

    Create the Dockerfile:

    创建 Dockerfile

    # Dockerfile
    FROM python:3.9-slim
    
    WORKDIR /app
    
    COPY . .
    
    RUN pip install fastapi uvicorn
    
    CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8002"]
  2. Build and Run the User Service
    Build and run the user service in a Docker container.

    构建并运行用户服务
    在 Docker 容器中构建并运行用户服务。

    docker build -t user_service .
    docker run -d --name user_service -p 8002:8002 user_service

Step 3: Set Up the Payment Service / 步骤3: 设置支付服务

  1. Create the Payment Service
    The payment service handles payment processing and transactions.

    创建支付服务
    支付服务处理支付处理和交易。

    mkdir payment_service
    cd payment_service

    Create the main.py for the payment service:

    为支付服务创建 main.py

    # main.py
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.post("/pay")
    def process_payment(amount: float, token: str):
       # Dummy payment processing logic
       if token == "fake-token":
           return {"status": "success", "amount": amount}
       return {"status": "failed", "reason": "Invalid token"}

    Create the Dockerfile:

    创建 Dockerfile

    # Dockerfile
    FROM python:3.9-slim
    
    WORKDIR /app
    
    COPY . .
    
    RUN pip install fastapi uvicorn
    
    CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8003"]
  2. Build and Run the Payment Service
    Build and run the payment service in a Docker container.

    构建并运行支付服务
    在 Docker 容器中构建并运行支付服务。

    docker build -t payment_service .
    docker run -d --name payment_service -p 8003:8003 payment_service

Step 4: Docker Networking Setup / 步骤4: Docker 网络设置

To allow these services to communicate with each other, you need to ensure they are all on the same Docker network.

为了让这些服务能够相互通信,你需要确保它们都在同一个 Docker 网络上。

  1. Create a Docker Network
    Create a custom bridge network that all services will use.

    创建一个 Docker 网络
    创建一个所有服务将使用的自定义桥接网络。

    docker network create microservices_network
  2. Connect Services to the Network
    When running the services, connect them to this network.

    将服务连接到网络
    在运行服务时,将它们连接到此网络。

    docker run -d --name auth_service --network microservices_network -p 8001:8001 auth_service
    docker run -d --name user_service --network microservices_network -p 8002:8002 user_service
    docker run -d --name payment_service --network microservices_network -p 8003:8003 payment_service

Step 5: Service Communication / 步骤5: 服务间通信

Now, these services can communicate with each other using their container names as hostnames. For example, the payment service can call the authentication service to verify a token.

现在,这些服务可以使用它们的容器名称作为主机名相互通信。例如,支付服务可以调用身份验证服务以验证令牌。

  1. Example: Payment Service Calls Authentication Service
    Update the payment service to call the authentication service before processing a payment.

    示例:支付服务调用身份验证服务
    更新支付服务以在处理付款之前调用身份验证服务。

    Update main.py in the payment service:

    更新支付服务中的 main.py

    # main.py
    import requests
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.post("/pay")
    def process_payment(amount: float, token: str):
       auth_response = requests.post("http://auth_service:8001/login", data={"user": "admin", "password": "secret"})
       if auth_response.json().get("token") == token:
           return {"status": "success", "amount": amount}
       return {"status": "failed", "reason": "Invalid token"}
  2. Rebuild and Run the Updated Payment Service
    Rebuild the Docker image for the payment service and run it again.

    重建并运行更新后的支付服务
    为支付服务重建 Docker 镜像并再次运行它。

    docker build -t payment_service .
    docker run -d --name payment_service --network microservices_network -p 8003:8003 payment_service
  3. Test the Communication
    You can now test the entire flow by sending a request to the payment service, which will internally communicate with the authentication service.

    测试通信
    现在你可以通过向支付服务发送请求来测试整个流程,该请求将在内部与身份验证服务进行通信。

    curl -X POST "http://localhost:8003/pay" -d "amount=100&token=fake-token"

    The expected output would be:

    预期输出将是:

    {"status": "success", "amount": 100}

Summary / 总结

In a microservices architecture, different services like authentication, user management, and payment processing are containerized and need to communicate with each other. Docker networking allows each service to be deployed in its own container while ensuring they can still communicate over a shared network. This setup not only enables modular development and deployment but also facilitates scaling and maintenance.

在微服务

架构中,不同的服务(如身份验证、用户管理和支付处理)被容器化,并需要相互通信。Docker 网络允许每个服务部署在自己的容器中,同时确保它们仍然可以通过共享网络进行通信。此设置不仅支持模块化开发和部署,还促进了扩展和维护。

5Ws / 5个W

  1. What: Demonstrating how microservices architecture works using Docker networking.
    什么: 演示如何使用 Docker 网络实现微服务架构。
  2. Why: To enable independent services to communicate while being isolated in their own containers.
    为什么: 为了让独立的服务在被隔离在各自的容器中时能够相互通信。
  3. When: When deploying a microservices architecture where services need to be developed, deployed, and scaled independently.
    什么时候: 在部署需要独立开发、部署和扩展的微服务架构时。
  4. Where: In any environment that supports Docker, including development, staging, and production.
    在哪里: 在支持 Docker 的任何环境中,包括开发、测试和生产环境。
  5. Who: DevOps engineers, system administrators, and developers implementing microservices architecture.
    谁: 实现微服务架构的 DevOps 工程师、系统管理员和开发人员。

Recommended Resources / 推荐资源

  1. Docker Networking Documentation: Docker Networking

  2. Microservices Architecture Guide: Microservices Guide

  3. FastAPI Documentation: FastAPI

  4. Docker 网络文档: Docker 网络

  5. 微服务架构指南: 微服务指南

  6. FastAPI 文档: FastAPI


By using Docker’s networking features, you can effectively deploy and manage a microservices architecture where each service is isolated yet able to communicate seamlessly.

通过使用 Docker 的网络功能,你可以有效地部署和管理一个微服务架构,其中每个服务都是隔离的,但能够无缝通信。

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *