雑記
Using Docker to Package FastAPI, React, and MySQL: A Step-by-Step Guide
Xu Jiantao
In general application development, frontend and backend frameworks are increasingly popular, and containerization technologies like Docker provide significant convenience for development and testing. This blog will detail how to integrate a FastAPI backend, React frontend, and MySQL database into a complete project, and how to package and run it using Docker. I must also extend my gratitude to my colleague, Tang Li, whose critical guidance helped me understand and utilize Docker from scratch. Before proceeding, make sure you have installed development tools like PyCharm or VSCode, Docker Desktop, and a database connection tool you are familiar with (or use a database plugin from your development tools if needed).
1. Project Structure Planning
Clear project structure is crucial before starting development. Below is the basic directory structure of a sample project:
project/
├── backend/ # FastAPI backend
│ ├── app/
│ ├── Dockerfile
│ └── requirements.txt
├── frontend/ # React frontend
│ ├── public/
│ ├── src/
│ ├── package.json
│ └── Dockerfile
├── db/ # MySQL database
│ └── init.sql # Database initialization script
├── docker-compose.yml
└── README.md
2. Development Environment Configuration
2.1 FastAPI Backend
(1) Install Necessary Dependencies
Create a requirements.txt
file and list the required Python libraries:
fastapi
uvicorn
sqlalchemy
pymysql
(2) Write Backend Code
Create a simple FastAPI application in the backend/app
directory, for example:
# backend/app/main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
(3) Create a Dockerfile
# backend/Dockerfile
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY ./app ./app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
2.2 React Frontend
(1) Initialize React Project
Use the create-react-app
tool to quickly generate a project:
npm create-react-app frontend
(2) Write Frontend Code
Modify src/App.js
to interact with the backend:
import React, { useEffect, useState } from "react";
function App() {
const [message, setMessage] = useState("");
useEffect(() => {
fetch("http://localhost:8000/")
.then((response) => response.json())
.then((data) => setMessage(data.message));
}, []);
return <div>{message}</div>;
}
export default App;
(3) Create a Dockerfile
# frontend/Dockerfile
FROM node:18
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install
COPY ./ ./
CMD ["yarn", "start"]
2.3 MySQL Database
(1) Initialize SQL Script
Create db/init.sql
with the following content:
CREATE DATABASE fastapi_react_db;
USE fastapi_react_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL UNIQUE
);
INSERT INTO users (name, email) VALUES ('John', '[email protected]');
3. Integrate Services Using Docker Compose
Create a docker-compose.yml
file to integrate the three services:
version: '3.8'
services:
backend:
build:
context: ./backend
dockerfile: Dockerfile
ports:
- "8000:8000"
depends_on:
- db
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "3000:3000"
depends_on:
- backend
db:
image: mysql:8.0
container_name: mysql_container
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: fastapi_react_db
volumes:
- ./db/init.sql:/docker-entrypoint-initdb.d/init.sql
ports:
- "3306:3306"
4. Build and Run the Project
4.1 Build Containers
Run the following command in the project root directory:
docker-compose build
4.2 Start Containers
Run the following command to start all services:
docker-compose up
Once started, the services will run on the following ports:
- Backend (FastAPI): http://localhost:8000
- Frontend (React): http://localhost:3000
- Database (MySQL):
localhost:3306
You can also see the containers running in the Docker Desktop application. If a service fails to start, check the container logs to troubleshoot the issue.
5. Verify Services
5.1 Backend API Verification
Visit http://localhost:8000. You should see:
{"message": "Hello, FastAPI!"}
5.2 Frontend Page Verification
Visit http://localhost:3000. The page should display the message returned by the backend.
5.3 Database Connection Test
Use a MySQL client (e.g., Navicat) to connect to the database and verify the initialized data. If the connection fails, modify the backend’s database configuration to use the MySQL container name instead of localhost
.
These are the key steps to package the project into a single Dockerized solution. If you have any questions or need further clarification, feel free to reach out. Thank you!