【FastAPI 基础】20、docker打包本地fastapi服务及环境,并线上部署

这篇博客介绍了如何使用FastAPI构建应用,包括代码目录结构解析、关键配置文件如nginx和supervisord的设置,以及Docker镜像的打包和运行。博主分享了从代码到部署的全过程,涉及日志、静态文件、环境变量和端口映射等细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言:
最近工作中有机会接触FastAPI这个框架,所以就把官方文档看了一遍,对框架的各个特性及使用方法做了总结,会逐步的发出来,希望对您有用。
如果您之前接触过python的其他框架,看起来会非常简单和顺畅,其实就是很简单。


我的FastAPI专栏,有兴趣可以看看

一、我的代码目录结构(分为bin、log、server)

1.1、bin(系统配置)和log(系统日志)的完整目录

1.2、 目录-文件释义

  • cert/cacert.pem: 发送短信的证书。
  • conf/mime.types: nginx文件类型。

         PS:没有就自己网上找去

  •     conf/nginx.conf: nginx配置文件。

       PS:我这边就一个前端服务代理一个后端服务,前端端口30000;后端服务30001。

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       30000;
        set $root_host "http://127.0.0.1:30001";
        server_name  localhost;

        autoindex on;

        types {
		 text/html html htm shtml;
		 text/log log;
		 text/css css;
		 text/xml xml;
		 text/js js;
		 text/md md;
		 text/woff woff;
		 text/ttf ttf;
		}

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        location / {
			autoindex on;
            alias  /data/apps/server/view/dist/;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        location /static/ {
            alias   /data/static/;
        }
        location /openapi.json {
            add_header 'Access-Control-Allow-Origin' '*';
            proxy_pass $root_host/openapi.json;
        }
        location /docs {
            add_header 'Access-Control-Allow-Origin' '*';
            proxy_pass $root_host;
        }
        location /redoc {
            add_header 'Access-Control-Allow-Origin' '*';
            proxy_pass http://127.0.0.1:30000;
        }
        location /api {
            add_header 'Access-Control-Allow-Origin' '*';
            proxy_pass $root_host;
        }
    }

}
  • conf/requirements.txt: python安装包,我用的是python3.8。
fastapi[all]==0.61.2
aiohttp==3.7.3
aiofiles==0.5.0
aiomysql==0.0.21
aioredis==1.3.1
gunicorn==20.0.4
sqlalchemy==1.3.20
pika==1.1.0
pymysql==0.9.3
aioredis==1.3.1
redis==3.5.3
loguru==0.5.3
databases==0.4.1
python-cas==1.5.0
APScheduler==3.6.3
numpy==1.19.0
rsa==4.6
requests-toolbelt==0.9.1
xpinyin==0.7.6
minio==7.0.2
rabbitpy==2.0.1
requests==2.25.1
uvicorn==0.11.8
WeRoBot==1.10.1
Twisted==21.2.0
DBUtils==1.3
django==3.2.4
python-dateutil==2.8.1
xlwt==1.3.0
xlrd==1.2.0
qrcode==6.1
bs4==0.0.1

  • conf/supervisord.conf: 守护进程配置文件。

[program:server_service] 中的command命令是个坑。

此处要找到fastapi的主进程实例app。

; supervisor config file

[supervisord]
logfile=/data/logs/supervisord.log ; 日志文件,默认是 $CWD/supervisord.log
logfile_maxbytes=50MB        ; 日志文件大小,超出会 rotate,默认 50MB
logfile_backups=10           ; 日志文件保留备份数量默认 10
loglevel=info                ; 日志级别,默认 info,其它: debug,warn,trace
pidfile=/data/tmp/supervisord.pid ; pid 文件
nodaemon=false               ; 是否在前台启动,默认是 false,即以 daemon 的方式启动
minfds=1024                  ; 可以打开的文件描述符的最小值,默认 1024
minprocs=200                 ; 可以打开的进程数的最小值,默认 200

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///data/tmp/supervisor.sock ; 通过 UNIX socket 连接 supervisord,路径与 unix_http_server 部分的 file 一致

; The [include] section can just contain the "files" setting.  This
; setting can list multiple files (separated by whitespace or
; newlines).  It can also contain wildcards.  The filenames are
; interpreted as relative to this file.  Included files *cannot*
; include files themselves.

[program:server_service]
directory = /data/apps/
command = gunicorn server:app -b 0.0.0.0:30001  -w 4 -k uvicorn.workers.UvicornH11Worker --daemon
autostart = true
autorestart = true
stdout_logfile = /data/logs/server_out.log
stderr_logfile = /data/logs/server_err.log

; [program:nginx_service]
; command = nginx -c /data/conf/nginx.conf
; autostart = true
; autorestart = true
; stdout_logfile = /data/logs/nginx_out.log
; stderr_logfile = /data/logs/nginx_err.log
  • Dockerfile: docker build 配置文件
FROM ubuntu:20.04

ADD sources.list /etc/apt/sources.list

RUN apt-get update && apt-get install -y vim supervisor python3.8 python3-distutils nginx

# 设置语言
ENV LANG C.UTF-8
ENV LANGUAGE C.UTF-8
ENV LC_ALL C.UTF-8

ADD pip.conf /root/.pip/pip.conf

RUN mkdir -p /data/package /data/conf /data/tmp /data/apps/server /data/static /data/logs

# pip 工具目录
# /data/static 静态文件目录   需要映射本地目录
# /data/logs 日志文件目录   需要映射本地目录
# /data/apps  应用程序目录    需要映射本地目录
# /data/apps/server  后台应用程序目录
# /data/apps/view  前台应用程序目录  只要dist 即可

# /data/tmp 进程等临时文件
# /data/conf 配置文件
# /data/package 工具目录
WORKDIR /data/package
ADD get-pip.py ./
RUN python3.8 get-pip.py

# 配置文件
WORKDIR /data
COPY ./conf/ /data/conf/
RUN ln -s /data/conf/supervisord.conf /etc/supervisor/conf.d/ \
      && supervisord -c /etc/supervisor/conf.d/supervisord.conf

RUN pip3 install -r /data/conf/requirements.txt

# 8000 前端服务 ...
# 8001 后台服务 ...
# 8002 ...
EXPOSE 30000 30001

CMD ["/usr/bin/supervisord", "-n"]

  • get-pip.py: pip安装脚本

         PS:没有就自己网上找去,复制不上来

  • pip.conf: pip镜像
[global] index-url = http://mirrors.aliyun.com/pypi/simple/ 

[install] trusted-host = mirrors.aliyun.com
  • sources.list: pip源
# 添加阿里源
deb http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse 
deb http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse 
deb http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse 
deb http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse

2.1、server(系统代码)的完整目录

 

2.2 目录-文件释义

  1. __init__.py: 初始化文件,本文很重要的一个文件
  2. config.py:系统配置文件
  3. manage.py: 系统脚本执行文件
  4. command:存放minio、操作数据库、定时、缓存等封装包
  5. logs:日志目录
  6. script:系统脚本文件
  7. static: 静态文件
  8. task:定时任务
  9. test:测试
  10. utils:封装好的脚本
  11. 前端打包好的静态文件
  12. app_*****:凡是以app开头的都是各模块的增删改查接口

二、build打包

1)、打包命令,在bin目录下执行

docker build -t fastapi:1.0 --rm=true .

命令执行过程如下:

三、run(将目录与镜像中的目录进行映射,并启动服务)

1)、启动命令,任何目录都可以

docker run -dit --name fastapi1.0 -p 30000:30000 -p 30001:30001 -e ENV=dev -e STATIC=/data/static/ -v D:/software_workspace_new/151hlwcxgs/fastapi_project/cxgs_fastapi_base/server:/data/apps/server -v D:/software_workspace_new/151hlwcxgs/fastapi_project/cxgs_fastapi_base/server/static:/data/static -v D:/software_workspace_new/151hlwcxgs/fastapi_project/cxgs_fastapi_base/server/logs:/data/logs fastapi:1.0

执行结果如下图:

命令释义:

--name:启动后的实例名称

-p: 需要映射的端口,可以设置多个

-e ENV: 设置系统环境变量,在config.py中设置

-e STATIC: 设置静态路径

-v: 映射代码和镜像的路径,包括日志、代码、静态文件等

2)、进入操作台命令,打包成镜像后的目录样子

docker exec -it fastapi1.0 bash

1、data目录结构

2、data/apps 目录结构

3、data/conf 目录结构

4、data/logs 目录结构

5、data/package 目录结构

 

3)、nginx、supervisor启动后的进程如下。

4)、启动后如下,前端服务也可正常代理访问

四、部署线上

1、导出镜像

docker save fastapi:1.0 > E:\hup\Angel\fastapi1.0.tar

2、导入镜像:docker load < 镜像路径

docker load < fastapi1.0.tar

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈建华呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值