You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Docker上运行简单的Python前后端项目

将前后端Python项目Docker化的完整方案

先明确项目结构

先把项目文件按以下目录整理好:

my-project/
├── backend/
│   ├── app.py
│   ├── requirements.txt
│   └── Dockerfile
├── frontend/
│   ├── index.html
│   └── Dockerfile
└── docker-compose.yml

后端实现(Flask示例)

1. 后端代码文件

backend/app.py:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/hello')
def send_hello():
    return jsonify(message="Hello World")

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

backend/requirements.txt:

Flask==2.3.3

2. 后端Dockerfile

backend/Dockerfile:

# 基于官方Python slim镜像构建
FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 先复制依赖文件,利用Docker缓存加速构建
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY app.py .

# 暴露服务端口
EXPOSE 5000

# 启动后端服务
CMD ["python", "app.py"]

前端实现(静态页面)

1. 前端页面文件

frontend/index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Hello World Demo</title>
</head>
<body>
    <h1 id="hello-text">加载中...</h1>
    <script>
        // 调用后端API获取消息
        fetch('http://localhost:5000/api/hello')
            .then(res => res.json())
            .then(data => {
                document.getElementById('hello-text').innerText = data.message;
            })
            .catch(err => {
                document.getElementById('hello-text').innerText = '加载失败';
                console.error(err);
            });
    </script>
</body>
</html>

2. 前端Dockerfile(用Nginx托管静态文件)

frontend/Dockerfile:

# 基于轻量Nginx镜像
FROM nginx:alpine

# 把前端静态文件复制到Nginx默认托管目录
COPY index.html /usr/share/nginx/html/

# 暴露Nginx端口
EXPOSE 80

Docker Compose 配置文件

docker-compose.yml:

version: '3.8'

services:
  backend:
    build: ./backend
    ports:
      - "5000:5000"
    networks:
      - app-network

  frontend:
    build: ./frontend
    ports:
      - "80:80"
    networks:
      - app-network

# 自定义网络让前后端容器互通
networks:
  app-network:
    driver: bridge

运行项目

  1. 进入项目根目录
  2. 执行构建并启动命令:
docker-compose up --build
  1. 打开浏览器访问 http://localhost,就能看到后端返回的Hello World消息了

内容的提问来源于stack exchange,提问作者Joseph Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:01:25