基于Docker部署fastapi+VUE3前后端项目 在ubnatu 20.04

步骤 1: 服务器准备 (Ubuntu 20.04.1 x64)

  • 更新系统软件包:
    打开终端,执行以下命令更新你的 Ubuntu 系统软件包列表并升级已安装的软件包:
 sudo apt update
 sudo apt upgrade -y
  • 安装必要的工具:
    安装 Docker 和 Docker Compose,这是我们进行容器化部署的关键工具:
sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
  • 验证 Docker 是否安装成功:
docker --version
docker compose version

步骤 2: 后端 FastAPI 项目搭建

创建后端项目目录:

mkdir fastapi_backend
cd fastapi_backend

创建 Python 虚拟环境 (推荐):

在虚拟环境里手动安装 pip
你遇到 venv 无法安装 pip,可以:

用 --without-pip 创建虚拟环境:

python3.8 -m venv --without-pip myenv
进入虚拟环境:

source myenv/bin/activate
手动安装 pip:
curl -sS https://bootstrap.pypa.io/get-pip.py | python

安装 FastAPI 及相关依赖:
pip install fastapi uvicorn
安装 FastAPI 及相关依赖:

pip install fastapi uvicorn
创建 main.py 文件:

from fastapi import FastAPI

app = FastAPI()

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

创建 requirements.txt 文件:

pip freeze > requirements.txt
创建 Dockerfile:

FROM python:3.9-slim-buster

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

创建 .dockerignore 文件 (可选,但推荐):

venv

.git
__pycache__
*.pyc
*.log

步骤 3: 前端 Vue 3 项目搭建

返回上一级目录并创建前端项目目录:

cd ..
mkdir vue_frontend
cd vue_frontend

确保 Node.js 和 npm (或 yarn) 已安装:
如果尚未安装,请前往 Node.js 官网下载安装。安装完成后,npm 会随之安装。你也可以选择使用 yarn:

node -v
npm -v

使用 Vite 创建 Vue 3 项目:

npm create vite@latest . -- --template vue
或者
yarn create vite . --template vue
按照提示完成项目名称等设置。
安装项目依赖:
npm install
或者
# yarn install
修改前端代码 (例如 src/App.vue):

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const message = ref('Loading...');

onMounted(async () => {
  try {
    const response = await axios.get('/api/hello');
    message.value = response.data.message;
  } catch (error) {
    message.value = 'Failed to fetch data.';
    console.error(error);
  }
});
</script>

<template>
  <h1>Vue 3 Frontend</h1>
  <p>{{ message }}</p>
</template>

<style scoped>
h1 {
  color: green;
}
</style>

安装 axios (用于前端发送 HTTP 请求):

npm install axios
或者
# yarn add axios
修改 vite.config.js 以配置代理 (开发环境):
在开发阶段,为了方便前端访问后端 API,可以配置 Vite 的代理:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

构建前端项目:
npm run build
或者
yarn build
构建完成后,会在项目根目录下生成 dist 文件夹,里面是打包好的静态文件。
创建 Dockerfile:

FROM node:18-alpine

WORKDIR /app

COPY package*.json .
RUN npm install

COPY . .

RUN npm run build

FROM nginx:alpine

COPY --from=0 /app/dist /usr/share/nginx/html

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

创建 .dockerignore 文件 (可选,但推荐):

node_modules
dist
.git

步骤 4: Docker Compose 编排

返回项目根目录 (包含 fastapi_backend 和 vue_frontend 两个文件夹的目录):
cd ..
创建 docker-compose.yml 文件:

version: '3.8'

services:
  backend:
    build: ./fastapi_backend
    ports:
      - "8000:8000"
    environment:
      # 可以在这里设置后端需要的环境变量
      pass: pass
    networks:
      - app-network

  frontend:
    build: ./vue_frontend
    ports:
      - "8080:80"
    depends_on:
      - backend
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

启动 Docker Compose:

docker compose up -d
这会构建并启动后端和前端两个 Docker 容器。此时,你的后端服务应该运行在服务器的 8000 端口,前端服务运行在 8080 端口。

步骤 5: 配置 Nginx 反向代理 (用于挂载到域名)

为了将你的服务通过 anttgov.com 域名访问,你需要配置 Nginx 作为反向代理。

安装 Nginx (如果尚未安装):

sudo apt install -y nginx
配置 Nginx 虚拟主机:
创建一个新的 Nginx 配置文件或者修改默认的配置文件。我们假设创建一个新的配置文件 anttgov.com.conf 在 /etc/nginx/conf.d/ 目录下:

sudo nano /etc/nginx/conf.d/anttgov.com.conf

server {
    listen 80;
    server_name anttgov.com www.anttgov.com;

    location /api/ {
        proxy_pass http://localhost:8000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location / {
        proxy_pass http://localhost:8080/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

解释:

listen 80;: 监听 80 端口 (HTTP 默认端口)。
server_name anttgov.com www.anttgov.com;: 配置域名。
location /api/: 将所有以 /api/ 开头的请求代理到运行在 localhost:8000 的后端服务。
location /: 将所有其他请求代理到运行在 localhost:8080 的前端服务。
proxy_set_header: 设置请求头,以便后端能够获取客户端的真实 IP 等信息。
测试 Nginx 配置:

sudo nginx -t
如果输出 syntax is ok 和 test is successful,则配置没有问题。

重启 Nginx 服务:

sudo systemctl restart nginx
步骤 6: 配置 DNS 解析
你需要在你的域名注册商的管理后台配置 DNS 解析,将 anttgov.com 和 www.anttgov.com 指向你的服务器 IP 地址。这个过程可能需要一些时间生效。

步骤 7: 访问你的应用

完成以上步骤后,你应该可以通过浏览器访问 http://anttgov.comhttp://www.anttgov.com 来看到你的 Vue 3 前端页面,并且前端能够通过 /api/hello 接口与你的 FastAPI 后端进行通信。
访问成功

安装nginx报错

https://blog.csdn.net/stickmangod/article/details/85316142

posted @ 2025-05-07 11:40  执语  阅读(334)  评论(2)    收藏  举报